Practice: Generic Cache
Combine Map and generics for a typed cache.
Example
class Cache<K, V> {
private m = new Map<K, V>();
get(k: K, make: () => V): V {
if (!this.m.has(k)) this.m.set(k, make());
return this.m.get(k)!;
}
}
const c = new Cache<string, number>();
console.log(c.get("a", () => 1), c.get("a", () => 2));Result
1 1
Exercise
Non-null assertion.
this.m.get(k)Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.