-
Notifications
You must be signed in to change notification settings - Fork 2
/
structure.ts
39 lines (28 loc) · 1018 Bytes
/
structure.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import type { IStructure } from "../interface/i-structure";
export type TypeResultBuilder = (key: string) => number;
class Structure<T> implements IStructure<T> {
#arrData: T[];
#getIndexFromCompilerFn: TypeResultBuilder;
constructor(arrKeys: string[]) {
this.#arrData = new Array(arrKeys.length);
this.#getIndexFromCompilerFn = this.#builder(arrKeys);
}
#builder(arrKeys: string[]): TypeResultBuilder {
return function (key: string) {
let functionBody = "switch(keyValue) { ";
for (let m = 0; m < arrKeys.length; m++) {
functionBody += `case "${arrKeys[m]}": return ${m}; `;
}
functionBody += `default: throw new Error("key is not found"); }`;
return new Function("keyValue", functionBody)(key);
};
}
set(keyStructure: string, value: T): IStructure<T> {
this.#arrData[this.#getIndexFromCompilerFn(keyStructure)] = value;
return this;
}
get(keyStructure: string): T {
return this.#arrData[this.#getIndexFromCompilerFn(keyStructure)];
}
}
export default Structure;