All files / services/utils/deepWeakMap index.ts

93.75% Statements 30/32
75% Branches 3/4
90% Functions 9/10
96.77% Lines 30/31
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 40 41 42 43 44 45 46 47 48 49 50 51 529x 9x   168x 264x     264x     9x   54x   9x 41x   9x 325x 325x 108x   325x   9x 61x   9x 120x 120x 168x   120x 120x   9x 48x 48x 96x   48x 48x   9x   9x            
import * as objectPath from 'object-path';
 
type PathPart = string | number;
 
type PatIh = PathPart | PathPart[];

function flattenPaths(paths: Path[]): string[] {
  return paths.reduce((accumulatedPath: string[], nextPath) => {
    if (Array.isArray(nextPath)) {
      return [...accumulatedPath, ...nextPath.map(pathPart => `${pathPart}`)];
    }
    return [...accumulatedPath, `${nextPath}`];
  }, []) as string[];
}
 
export class DeepWeakMap<
  Key extends Object,
  Value,
  Structure = { [key: string]: Value }
> {
  private map: WeakMap<Key, Structure>;
  constructor() {
    this.map = new WeakMap();
  }
 
  isEmpty(target: Key) {
    return !Object.keys(this.getAll(target)).length;
  }
 
  getAll(target: Key): Structure {
    const { map } = this;
    if (!map.has(target)) {
      map.set(target, {} as Structure);
    }
    return map.get(target);
  }
 
  set(target: Key, path: Path, value: Value) {
    objectPath.set(this.getAll(target), path, value);
  }
 
  get(target: Key, ...paths: Path[]): Value {
    const path = flattenPaths(paths);
    return objectPath.get(this.getAll(target), path);
  }
 
  has(target: Key, ...paths: Path[]): boolean {
    const path = flattenPaths(paths);
    return !!this.get(target, ...paths);
  }
}