Skip to content

Commit

Permalink
add asyncMapKeys operator
Browse files Browse the repository at this point in the history
  • Loading branch information
dreymonde committed May 1, 2022
1 parent 36290c8 commit 3a9d673
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions Sources/Shallows/Async.swift
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,22 @@ extension ReadOnlyStorageProtocol {
})
}

public func asyncMapKeys<OtherKey>(
to type: OtherKey.Type = OtherKey.self,
_ transform: @escaping (OtherKey) async throws -> Key)
-> ReadOnlyStorage<OtherKey, Value> {
return ReadOnlyStorage<OtherKey, Value>(storageName: storageName, retrieve: { key, completion in
Task {
do {
let newKey = try await transform(key)
self.retrieve(forKey: newKey, completion: completion)
} catch {
completion(.failure(error))
}
}
})
}

public func validate(_ isValid: @escaping (Value) async throws -> Bool) -> ReadOnlyStorage<Key, Value> {
return asyncMapValues(to: Value.self) { value in
if try await isValid(value) {
Expand Down Expand Up @@ -121,6 +137,22 @@ extension WriteOnlyStorageProtocol {
})
}

public func asyncMapKeys<OtherKey>(
to type: OtherKey.Type = OtherKey.self,
_ transform: @escaping (OtherKey) async throws -> Key)
-> WriteOnlyStorage<OtherKey, Value> {
return WriteOnlyStorage<OtherKey, Value>(storageName: storageName, set: { value, key, completion in
Task {
do {
let newKey = try await transform(key)
self.set(value, forKey: newKey, completion: completion)
} catch {
completion(.failure(error))
}
}
})
}

public func validate(_ isValid: @escaping (Value) async throws -> Bool) -> WriteOnlyStorage<Key, Value> {
return asyncMapValues(to: Value.self) { value in
if try await isValid(value) {
Expand All @@ -144,6 +176,12 @@ extension StorageProtocol {
write: asWriteOnlyStorage().asyncMapValues(transformOut))
}

public func asyncMapKeys<OtherKey>(to type: OtherKey.Type = OtherKey.self,
_ transform: @escaping (OtherKey) async throws -> Key) -> Storage<OtherKey, Value> {
return Storage(read: asReadOnlyStorage().asyncMapKeys(transform),
write: asWriteOnlyStorage().asyncMapKeys(transform))
}

public func validate(_ isValid: @escaping (Value) async throws -> Bool) -> Storage<Key, Value> {
return asyncMapValues(
to: Value.self,
Expand Down

0 comments on commit 3a9d673

Please sign in to comment.