Skip to content

Instantly share code, notes, and snippets.

@trueharuu
Created January 26, 2022 03:29
Show Gist options
  • Save trueharuu/30a14b02543e26826ae036b099dec907 to your computer and use it in GitHub Desktop.
Save trueharuu/30a14b02543e26826ae036b099dec907 to your computer and use it in GitHub Desktop.
export class FunctionMap<T> {
private items: Array<() => T>;
private self: typeof FunctionMap = FunctionMap;
constructor(items: Array<[string, T]>) {
this.items = items.map(([k, v]) => this.self.toFunction(k, v));
}
static toFunction<T>(key: string, value: T) {
const wrap = {
[key]: () => value
}
return wrap[key]
}
clear() {
this.items = [];
return this;
}
delete(key: string) {
if (!this.has(key)) throw new Error(`Function '${key}' not found`)
let fn = this.getFunction(key)!
let idx = this.items.indexOf(fn)
this.items.splice(idx, 1)
return this
}
deleteFunction(fn: () => T) {
return this.delete(fn.name)
}
entries(): Array<[string, T]> {
return this.items.map(v => [v.name, v()])
}
forEach(fn: (value: T, key: string, map: this) => void) {
this.items.forEach((value) => fn(value(), value.name, this))
return this
}
get(key: string): T | undefined {
let fn = this.getFunction(key)
return fn ? fn() : undefined
}
getFunction(key: string): (() => T) | undefined {
return this.items.find(value => value.name === key) as () => T
}
has(key: string) {
return this.getFunction(key) !== undefined
}
hasFunction(fn: () => T) {
return this.has(fn.name)
}
set(key: string, value: T) {
let to = this.self.toFunction(key, value)
let fn = this.getFunction(key)
if (fn === undefined) {
this.items.push(to)
return this
}
let idx = this.items.indexOf(fn)
this.items[idx] = to
return this
}
setFunction(value: () => T) {
return this.set(value.name, value())
}
get size() {
return this.items.length
}
get keys() {
return this.items.map(v => v.name)
}
get values() {
return this.items.map(v => v())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment