//================================================================ /** * @packageDocumentation * @module std */ //================================================================ import { HashMap } from "../container/HashMap"; import { MutableSingleton } from "./MutableSingleton"; import { equal } from "../ranges/algorithm/iterations"; import { hash } from "../functional/hash"; /** * Variadic mutable singleton generator. * * @author Jeongho Nam - https://github.com/samchon */ export class VariadicMutableSingleton { /** * @hidden */ private readonly closure_: (...args: Args) => Promise; /** * @hidden */ private readonly dict_: HashMap>; /* --------------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------------- */ public constructor( closure: (...args: Args) => Promise, hashFunc: (args: Args) => number = (args) => hash(...args), pred: (x: Args, y: Args) => boolean = equal, ) { this.closure_ = closure; this.dict_ = new HashMap(hashFunc, pred); } public set(...items: [...Args, T]): Promise { const args: Args = items.slice(0, items.length - 1) as Args; const value: T = items[items.length - 1]; return this._Get_singleton(args).set(value); } public reload(...args: Args): Promise { return this._Get_singleton(args).reload(...args); } public clear(): Promise; public clear(...args: Args): Promise; public async clear(...args: Args): Promise { if (args.length === 0) this.dict_.clear(); else await this._Get_singleton(args).clear(); } /* --------------------------------------------------------------- ACCESSORS --------------------------------------------------------------- */ public get(...args: Args): Promise { return this._Get_singleton(args).get(...args); } public is_loaded(...args: Args): Promise { return this._Get_singleton(args).is_loaded(); } /** * @hidden */ private _Get_singleton(args: Args): MutableSingleton { let it: HashMap.Iterator< Args, MutableSingleton > = this.dict_.find(args); if (it.equals(this.dict_.end()) === true) it = this.dict_.emplace( args, new MutableSingleton(this.closure_), ).first; return it.second; } }