Skip to content

Commit

Permalink
Additions: "Also" for side-effects and "debug" for printing debug mes…
Browse files Browse the repository at this point in the history
…sages (#33)

* Add a function for performing side-effects and a debug function like rxswift

* Add also & debug tests
  • Loading branch information
nicorichard authored Mar 5, 2022
1 parent f76632b commit 2752554
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 0 deletions.
12 changes: 12 additions & 0 deletions Sources/Genything/gen/debug/Gen+also.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
public extension Gen {
/// Invokes the provided closure for each value produced by the receiver in order to perform intermediary actions or side-effects
///
/// - Returns: A generator which which produces identical values to the receiver
func also(_ run: @escaping (T) throws -> Void) rethrows -> Gen<T> {
Gen<T> { ctx in
let value = generate(context: ctx)
try run(value)
return value
}
}
}
32 changes: 32 additions & 0 deletions Sources/Genything/gen/debug/Gen+debug.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import Foundation

public extension Gen {
/// Logs a print statement for each value produced by the receiver
///
/// - Parameter tag: Optional tag which can be used to easily identify which debug statement a log belongs to
///
/// - Returns: A generator which which produces identical values to the receiver
func debug(_ tag: String = "", file: StaticString = #fileID, line: UInt = #line) -> Gen<T> {
let prefix: String = {
if tag.isEmpty {
return "\(file):\(line)"
}
return "\(tag)"
}()

return also {
log(prefix, $0)
}
}

private func log(_ tag: String, _ value: T) {
let timestamp = dateFormatter.string(from: Date())
print("\(timestamp): [\(tag)] -> \(value)")
}
}

private var dateFormatter: DateFormatter = {
let df = DateFormatter()
df.dateFormat = "HH:mm:ss.SSS"
return df
}()
16 changes: 16 additions & 0 deletions Tests/GenythingTests/gen/debug/GenAlsoTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import XCTest
import Genything
import GenythingTest

class Gen_AlsoTests: XCTestCase {
func test_also_runs_side_effect_once_per_generation() {
let iterations = 100

var count = 0
_ = Gen.constant(()).also {
count += 1
}.take(iterations)

XCTAssertEqual(iterations, count)
}
}
13 changes: 13 additions & 0 deletions Tests/GenythingTests/gen/debug/GenDebugTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import XCTest
import Genything
import GenythingTest

class Gen_DebugTests: XCTestCase {
func test_debug_printsAsExpected() {
_ = Gen.from(1...5)
.debug()
.map { $0 * 2 }
.debug("*2")
.take(5)
}
}

0 comments on commit 2752554

Please sign in to comment.