Skip to content
This repository has been archived by the owner on Sep 22, 2020. It is now read-only.

Recipes

Tylor Steinberger edited this page Feb 3, 2017 · 7 revisions
toObject<V>(map: HashMap<string, V>): HashMap<string, V> & { [key: string]: V }

Use a proxy to create an "object" that can be destructured and used just like a regular object.

import { HashMap, fromArray, get, has, keys, remove, set } from '@typed/hashmap';

function toObject<V>(
  map: HashMap<string, V>): HashMap<string, V> & { [key: string]: V } 
{
  return new Proxy(Object.assign({}, map), {
    get(target, property) {
      return get(property.toString(), target) || void 0;
    },

    has(target, property) {
      return has(property.toString(), target);
    },

    set(target, property, value) {
      // immutably mutate the target :/
      (target as any).node = (set(property, value, target) as any).node;
      return value;
    },

    getOwnPropertyDescriptor(target, property) {
      return {
        configurable: true,
        enumerable: true,
        value: get(property, target) || void 0,
      };
    },

    ownKeys(target) {
      return Array.from(keys(target));
    },

    deleteProperty(target, property) {
      // immutably mutate the target :/
      (target as any).node = (remove(property, target) as any).node;
      return true;
    },
  }) as HashMap<string, V> & { [key: string]: V };
}
Clone this wiki locally