Last active
August 24, 2018 13:08
-
-
Save abesmon/e35df343ad8a02de2e3bf5ff68a8d5db to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import PromiseKit | |
/** | |
Каждый раз, когда будет вызван nextUnused будет возвращаться | |
объект входного итератора, на котором применен модификатор, но модификатор применяется только единожды. | |
Все следующие вызховы будет просто отдаваться объект, который был изменен в первый вызов. | |
После того как будет вызван useCallback (второй элемент кортежа), курсор перейдет к следующему объекту. | |
Следующий запрошенный объект снова будет запрошен из оригинального итератора, пройдет через модификатор и до следующего вызова useCallback будет отдаваться без дополнительных модификаций | |
*/ | |
fileprivate class OneTimeModifyIterator<TCollection: Collection, U> { | |
typealias ModifiedObjectPromise = Promise<U> | |
typealias IteratorType = IndexingIterator<TCollection> | |
typealias T = TCollection.Element | |
private var currentObject: T? | |
private var currentModifiedObjectPromise: ModifiedObjectPromise? | |
private var iterator: IteratorType | |
private let modifier: (T) -> ModifiedObjectPromise | |
init(_ plainIterator: IteratorType, modifier: @escaping (T) -> ModifiedObjectPromise) { | |
self.iterator = plainIterator | |
self.modifier = modifier | |
} | |
// Должен отдавать следующий | |
func nextUnused() -> (ModifiedObjectPromise, () -> Void)? { | |
if currentObject == nil { | |
currentObject = iterator.next() | |
guard currentObject != nil else { return nil } | |
currentModifiedObjectPromise = modifier(currentObject!) | |
} | |
guard currentModifiedObjectPromise != nil else { return nil } | |
return (currentModifiedObjectPromise!, setAsUsed) | |
} | |
private func setAsUsed() { | |
currentObject = nil | |
currentModifiedObjectPromise = nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment