Sketch HashMap impl.

This commit is contained in:
Jesse Brault 2025-09-23 20:04:26 -05:00
parent 2a2936ef02
commit 5f1233a393

View File

@ -0,0 +1,58 @@
pub trait HashCode
fn hash() -> USize
end
pub int Map<K, V>
fn get(key: K) -> Option<&V>
fn put(key: K, value: V) -> Void
fn take(key: K) -> Option<V>
end
pub class HashMap<K, V>(hasher: impl HashCode[K]) : Map<K, V>
class Entry<K, V>(pub key: K, pub value: V) end
let mut buckets: List<List<Entry<K, V>>> = ArrayList(size: 10, init: { [] })
fn getBucketIndex(key: K) -> Int
hasher.hash(key) & buckets.size()
end
impl fn put(key: K, value: V) -> Void
let bucket = buckets[getBucketIndex(key)]
bucket.add(Entry(key, value))
end
impl fn get(key: K) -> Option<&V>
let bucket = buckets[getBucketIndex(key)] // bucket: &List<Entry<K, V>>
bucket.find { it.key == key } // it: &Entry<K, V>
.map { it.value } // it.value: &V
end
impl fn take(key: K) -> Option<V>
let mut bucket = buckets.take(getBucketIndex(key), []) // bucket: List<Entry<K, V>>
if bucket.findIndex { it.key == key } is Some(index) then
let entry = bucket.remove(index) // entry: Entry<K, V>
Some(entry.value) // moved out of Entry
else
None
end
end
end
impl HashCode for String
fn hash() -> Int = todo()
end
class Greeter(pub greeting: String) end
fn main()
let greeterMap: Map<String, Greeter> = HashMap(HashCode[]) // Short for HashCode[String]
greeterMap.put("friendly", Greeter("Friendly hello!"))
greeterMap.put("nasty", Greeter("Nasty hello!"))
let friendlyGreeter: &Greeter = greeterMap.get("friendly").unwrap()
println friendlyGreeter.greeting
let nastyGreeter: Greeter = greeterMap.take("nasty").unwrap()
println nastyGreeter.greeting
end