Created
January 26, 2022 03:29
-
-
Save trueharuu/30a14b02543e26826ae036b099dec907 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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