Skip to content

Instantly share code, notes, and snippets.

@tanvirraj
Forked from steveruizok/cache.ts
Created September 22, 2022 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanvirraj/5be3d5f5635de60b92528937545f3b25 to your computer and use it in GitHub Desktop.
Save tanvirraj/5be3d5f5635de60b92528937545f3b25 to your computer and use it in GitHub Desktop.
weak map gist
export class Cache<T extends object, K> {
items = new WeakMap<T, K>()
get<P extends T>(item: P, cb: (item: P) => K) {
if (!this.items.has(item)) {
this.items.set(item, cb(item))
}
return this.items.get(item)!
}
access(item: T) {
return this.items.get(item)
}
set(item: T, value: K) {
this.items.set(item, value)
}
has(item: T) {
return this.items.has(item)
}
invalidate(item: T) {
this.items.delete(item)
}
bust() {
this.items = new WeakMap()
}
}
class Example {
getOutline(shape) {
const sides = 5
const ratio = 1
const cx = w / 2
const cy = h / 2
const ix = (cx * ratio) / 2
const iy = (cy * ratio) / 2
const step = PI2 / sides / 2
return Array.from(Array(sides * 2)).map((_, i) => {
const theta = -TAU + i * step
return new Vec2d(
cx + (i % 2 ? ix : cx) * Math.cos(theta),
cy + (i % 2 ? iy : cy) * Math.sin(theta)
)
})
}
outline(shape: T) {
return outlines.get<T>(shape, (shape) => this.getOutline(shape))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment