Skip to content

Instantly share code, notes, and snippets.

@pofat
Created January 12, 2022 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pofat/91faa5381b18693eeaec2b63693d6f62 to your computer and use it in GitHub Desktop.
Save pofat/91faa5381b18693eeaec2b63693d6f62 to your computer and use it in GitHub Desktop.
[Effect<Output, Failure>] -> Effect<[Output], Failure>
extension Effect {
// Zip with other effects
func zip<Others: Collection>(with others: Others)
-> Effect<[Output], Failure>
where Others.Element == Effect<Output, Failure> {
let first = map { [$0] }
.eraseToEffect()
return others
.reduce(first) { zipped, next in
zipped
.zip(next)
.map { $0.0 + [$0.1] }
.eraseToEffect()
}
.eraseToEffect()
}
}
// Use this for effect array
func zip<Output, Failure: Error>(_ effects: [Effect<Output, Failure>]) -> Effect<[Output], Failure> {
switch effects.count {
case 0:
return .none
case 1:
return effects[effects.startIndex].zip(with: [Effect<Output, Failure>]())
default:
let first = effects[effects.startIndex]
let others = effects[effects.index(after: effects.startIndex)...]
return first.zip(with: others)
}
}
// Usage
let first = Effect<Int, Never>(value: 1)
let second = Effect<Int, Never>(value: 2)
let third = Effect<Int, Never>(value: 3)
let forth = Effect<Int, Never>(value: 4)
let zipped = zip([first, second, third, forth]) // Effect<[Int], Never>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment