Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions Sources/c/c.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import Foundation.NSLock

public struct MissingRequiredKeysError<Key: Hashable>: Error {
public let keys: Set<Key>
}

public protocol Cacheable: AnyObject {
associatedtype Key: Hashable

Expand All @@ -16,6 +20,20 @@ public protocol Cacheable: AnyObject {

/// Remove the value in the `cache` using the `key`.
func remove(_ key: Key)

/// Checks if the given `key` has a value or not
func contains(_ key: Key) -> Bool

/// Checks to make sure the cache has the required keys, otherwise it will throw an error
func require(keys: Set<Key>) throws -> Self

/// Checks to make sure the cache has the required key, otherwise it will throw an error
func require(_ key: Key) throws -> Self

/// Returns a Dictionary containing only the key value pairs where the value is the same type as the generic type `Value`
func valuesInCache<Value>(
ofType: Value.Type
) -> [Key: Value]
}

/// Composition
Expand Down Expand Up @@ -68,6 +86,31 @@ public enum c {
cache[key] = nil
lock.unlock()
}

open func contains(_ key: Key) -> Bool {
cache[key] != nil
}

open func require(keys: Set<Key>) throws -> Self {
let missingKeys = keys
.filter { contains($0) == false }

guard missingKeys.isEmpty else {
throw MissingRequiredKeysError(keys: missingKeys)
}

return self
}

open func require(_ key: Key) throws -> Self {
try require(keys: [key])
}

open func valuesInCache<Value>(
ofType: Value.Type = Value.self
) -> [Key: Value] {
cache.compactMapValues { $0 as? Value }
}
}

public class Cache: KeyedCache<AnyHashable> {
Expand Down
8 changes: 8 additions & 0 deletions Tests/cTests/cTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,14 @@ final class cTests: XCTestCase {

let resolvedValue: Double = cache.resolve("🥧")

try t.assert(try cache.require("🥧").contains("🥧"))

try t.assert(resolvedValue, isEqualTo: .pi)

cache.remove("🥧")

try t.assert(notTrue: cache.contains("🥧"))

let nilValue: Double? = cache.get("🥧")

try t.assert(isNil: nilValue)
Expand Down Expand Up @@ -174,6 +178,10 @@ final class cTests: XCTestCase {
XCTAssertEqual(json.resolve(.number), 5)
XCTAssertEqual(json.resolve(.bool), false)

XCTAssertEqual(json.valuesInCache(ofType: String.self).count, 1)
XCTAssertEqual(json.valuesInCache(ofType: Int.self).count, 2)
XCTAssertEqual(json.valuesInCache(ofType: Bool.self).count, 1)

let invalid_key: Bool? = json.get(.invalid_key)

XCTAssertNil(json.get(.invalid_key))
Expand Down