Skip to content

Commit

Permalink
Update RefdsDictionary.swift
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelesantos committed Oct 28, 2024
1 parent 187d6a9 commit ce4fa2a
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions Sources/RefdsShared/Foundation/RefdsDictionary.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,42 @@ public actor RefdsDictionary<
> {
private var elements: [Key: Value] = [:]
private let keyPath: KeyPath<Value, Transform>
private let maxCapacity: Int?

public init(
for type: Value.Type,
by keyPath: KeyPath<Value, Transform>
by keyPath: KeyPath<Value, Transform>,
maxCapacity: Int? = nil
) {
self.keyPath = keyPath
self.maxCapacity = maxCapacity
}

public subscript(key: Key) -> Value? {
get { elements[key] }
set {
guard let newValue else { return remove(for: key) }
guard canInsert else { return }
if elements[key] == nil { insert(for: key) }
elements[key] = newValue
}
}

@discardableResult
public func removeFirst() -> Value? {
guard let firstKey = keys.first else { return nil }
let element = elements[firstKey]
remove(for: firstKey)
return element
}

public var count: Int { keys.count }
public var keys: [Key] = []
public var values: [Value] {
keys.compactMap { elements[$0] }
public var values: [Value] { keys.compactMap { elements[$0] } }

private var canInsert: Bool {
guard let maxCapacity else { return true }
return count < maxCapacity
}

private func insert(for key: Key) {
Expand Down

0 comments on commit ce4fa2a

Please sign in to comment.