Skip to content

Commit

Permalink
Add firstValue(where:)
Browse files Browse the repository at this point in the history
  • Loading branch information
mxcl committed Jun 17, 2018
1 parent 6d75d00 commit b96bb7b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
8 changes: 6 additions & 2 deletions Sources/Error.swift
Expand Up @@ -2,7 +2,7 @@ import Foundation

public enum PMKError: Error {
/**
The completionHandler with form (T?, ErrorType?) was called with (nil, nil)
The completionHandler with form `(T?, Error?)` was called with `(nil, nil)`.
This is invalid as per Cocoa/Apple calling conventions.
*/
case invalidCallingConvention
Expand All @@ -26,7 +26,11 @@ public enum PMKError: Error {
/// `nil` was returned from `compactMap`
case compactMap(Any, Any.Type)

/// the lastValue or firstValue of a sequence was requested but the sequence was empty
/**
The lastValue or firstValue of a sequence was requested but the sequence was empty.
Also used if all values of this collection failed the test passed to `firstValue(where:)`.
*/
case emptySequence
}

Expand Down
9 changes: 9 additions & 0 deletions Sources/Thenable.swift
Expand Up @@ -372,6 +372,15 @@ public extension Thenable where T: Collection {
}
}

func firstValue(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, where test: @escaping (T.Iterator.Element) -> Bool) -> Promise<T.Iterator.Element> {
return map(on: on, flags: flags) {
for x in $0 where test(x) {
return x
}
throw PMKError.emptySequence
}
}

/// - Returns: a promise fulfilled with the last value of this `Collection` or, if empty, a promise rejected with PMKError.emptySequence.
var lastValue: Promise<T.Iterator.Element> {
return map(on: nil) { aa in
Expand Down

0 comments on commit b96bb7b

Please sign in to comment.