From 463040e7d272a4e4d9144700a7e7799059c44435 Mon Sep 17 00:00:00 2001 From: Zach Eriksen Date: Mon, 11 Jan 2021 11:21:21 -0600 Subject: [PATCH] init --- Sources/Chain/Chain.swift | 41 +++++++++++++++++++++++++-- Tests/ChainTests/ChainTests.swift | 46 +++++++++++++++++++++++++++---- 2 files changed, 80 insertions(+), 7 deletions(-) diff --git a/Sources/Chain/Chain.swift b/Sources/Chain/Chain.swift index f945881..9791ab5 100644 --- a/Sources/Chain/Chain.swift +++ b/Sources/Chain/Chain.swift @@ -1,3 +1,40 @@ -struct Chain { - var text = "Hello, World!" +import Foundation + +public typealias ChainAction = () -> Void + +public indirect enum Chain { + case end + case complete(ChainAction?) + case link(ChainAction, Chain) + case background(ChainAction, Chain) + case multi([Chain]) +} + +public extension Chain { + func run() { + switch self { + case .end: + print("[\(Date())] Chain: End") + case .complete(let completion): + print("[\(Date())] Chain: Complete") + completion?() + case .link(let action, + let next): + print("[\(Date())] Chain: Link") + action() + next.run() + case .background(let action, + let next): + print("[\(Date())] Chain: Background") + DispatchQueue.global().async { + action() + DispatchQueue.main.async { + next.run() + } + } + case .multi(let links): + print("[\(Date())] Chain: Multi") + links.forEach { $0.run() } + } + } } diff --git a/Tests/ChainTests/ChainTests.swift b/Tests/ChainTests/ChainTests.swift index af807a8..289d864 100644 --- a/Tests/ChainTests/ChainTests.swift +++ b/Tests/ChainTests/ChainTests.swift @@ -3,12 +3,48 @@ import XCTest final class ChainTests: XCTestCase { func testExample() { - // This is an example of a functional test case. - // Use XCTAssert and related functions to verify your tests produce the correct - // results. - XCTAssertEqual(Chain().text, "Hello, World!") + var isLooping = true + + var text = "" + + + Chain.link( + { print(0) }, + .link( + { print(1) }, + .background( + { print(2) + sleep(3) + }, + .link( + { print(3) }, + .complete { + text = "Hello, World?" + } + ) + ) + ) + ) + .run() + + Chain.background( + { + sleep(5) + }, + .link( + { + XCTAssertEqual(text, "Hello, World!") + }, + .complete { + isLooping = false + } + ) + ) + .run() + + while isLooping { } } - + static var allTests = [ ("testExample", testExample), ]