Skip to content

Instantly share code, notes, and snippets.

@khanlou
Last active July 6, 2021 00:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khanlou/f01475a2ece9facb8e1cbc97288b4ac8 to your computer and use it in GitHub Desktop.
Save khanlou/f01475a2ece9facb8e1cbc97288b4ac8 to your computer and use it in GitHub Desktop.
struct Placeholder<Key, Value where Key: Hashable> {
var values: [(Key, Value)] = []
func firstValue(matchingKey key: Key) -> Value? {
return values.lazy.filter({ $0.0 == key }).first?.1
}
}
struct Dictionary<Key, Value where Key: Hashable> {
private var storage = Array(count: 8, repeatedValue: Placeholder<Key, Value>())
subscript(key: Key) -> Value? {
get {
let position = abs(key.hashValue) % storage.count
return storage[position].firstValue(matchingKey: key)
}
set {
guard let value = newValue else { return }
let position = abs(key.hashValue) % storage.count
storage[position].values.append((key, value))
}
}
}
var d = Dictionary<String, String>()
d["123"] = "asdf"
d["123"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment