72 lines
1.5 KiB
TypeScript
72 lines
1.5 KiB
TypeScript
export class StateRegistry<V, R> {
|
|
private registry: Map<string, V | undefined> = new Map();
|
|
|
|
private result: R | undefined;
|
|
|
|
/**
|
|
* If the key exists, return false.
|
|
*/
|
|
public insertKey = (key: string) => {
|
|
if (this.registry.has(key)) {
|
|
return false;
|
|
} else {
|
|
this.registry.set(key, undefined);
|
|
return true;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* If the `key` dose not exists, return `false`.
|
|
*
|
|
* Use insertKey before updateValue.
|
|
*/
|
|
public updateValue = (key: string, value: V) => {
|
|
if (this.registry.has(key)) {
|
|
this.registry.set(key, value);
|
|
return true;
|
|
} else {
|
|
return false;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* If the `key` dose not exists, return `false`.
|
|
*/
|
|
public deleteEntry = (key: string) => {
|
|
if (this.registry.has(key)) {
|
|
this.registry.delete(key);
|
|
return true;
|
|
} else {
|
|
return false;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* If the `value` of an entry is found to be `undefined`, return `false`.
|
|
*/
|
|
public checkAllReady = () => {
|
|
for (const e of this.registry.values()) {
|
|
if (e == undefined) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
};
|
|
|
|
/**
|
|
* Using your own logic to calculate and return the `result`.
|
|
*
|
|
* Or use `this.result` to access it.
|
|
*/
|
|
public calculateResult = (
|
|
callback: (registry: Map<String, V | undefined>) => R,
|
|
) => {
|
|
this.result = callback(this.registry);
|
|
return this.result;
|
|
};
|
|
|
|
public getResult = () => {
|
|
return this.result;
|
|
};
|
|
}
|