UNPKG

@itexpert-dev/key-value-storage

Version:

key-value storage like C# dictionary

43 lines (40 loc) 1.49 kB
import {IAppendValueParams} from "./IAppendValueParams"; import {IDictionary} from '@itexpert-dev/i-dictionary' import {isNull, isUndefined} from "@itexpert-dev/tiny-helpers"; export class KeyValueStorage<U>{ private _storage: IDictionary<U> = {}; private forceAppend(params: IAppendValueParams<U>){ this._storage[params.key] = params.value } public add(...params: IAppendValueParams<U>[]){ for(let param of params){ if(isNull(param.key)){ throw new Error(`can not put data with null key`) } if(isUndefined(param.key)){ throw new Error(`can not put data with undefined key`) } if(this._storage.hasOwnProperty(param.key)) { if (param.force === true) { this.forceAppend(param) } else { throw new Error(`data with key ${param.key} already exist use force=true flag for override`) } } else { this.forceAppend(param) } } } public remove(key: string){ delete this._storage[key] } public get(key: string): U{ if (!this._storage.hasOwnProperty(key)){ throw new Error(`data with key: ${key} is missing!`); } return this._storage[key] } public check(key: string): boolean{ return this._storage.hasOwnProperty(key); } }