Last active
February 8, 2023 09:47
-
-
Save xaliphostes/f551857ff9be5254d4f015277cee0300 to your computer and use it in GitHub Desktop.
Factory of functions using string names
This file contains hidden or 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
type myFunction = (params: any) => void | |
/* eslint @typescript-eslint/no-explicit-any: off -- need to have any here for the factory */ | |
namespace Factory { | |
const map_: Map<string, myFunction> = new Map() | |
export const bind = (obj: myFunction, name: string = '') => { | |
name.length === 0 ? map_.set(obj.name, obj) : map_.set(name, obj) | |
} | |
export const call = (name:string, params: any = undefined) => { | |
const fct = map_.get(name) | |
if (fct) { | |
return fct(params) | |
} | |
return undefined | |
} | |
export const exists = (name: string): boolean => { | |
return map_.get(name) !== undefined | |
} | |
export const names = (): string[] => { | |
return Array.from(map_.keys()) | |
} | |
} | |
// ============ example | |
const fct1 = (msg: string) => console.log(`fct 1 with msg=${msg}`) | |
const fct2 = (value: number) => console.log(`fct 2 with value=${value}`) | |
const fct3 = () => console.log(`fct 3`) | |
const fct4 = (o: any) => console.log(o) | |
Factory.bind(fct1) | |
Factory.bind(fct2) | |
Factory.bind(fct3) | |
Factory.bind(fct4) | |
// --------------- Using | |
Factory.call('fct1', 'Hello World') | |
Factory.call('fct2', 1000) | |
Factory.call('fct3') | |
Factory.call('fct4', {a: 1, b: 'coucou'}) | |
console.log(Factory.exists('fct1')) | |
console.log(Factory.exists('fct5')) | |
console.log(Factory.names()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment