JavaScript defaultdict
This is a port of python's defaultdict to JavaScript. It uses proxies to create objects that return values other than undefined
for attributes that haven't yet been set.
This package needs native Proxy support to work.
Install
yarn add defaultdict-proxy
Usage
If called with undefined
, null
, a boolean, number, string or symbol, defaultdict
returns a proxy object that returns this value for unset attributes. If called with an array or object, accessing unset attributes returns a shallow copy of the array or object. If defaultdict
is given a function, it returns a proxy object that has unset attributes initialized to the result of executing the function.
import defaultdict from 'defaultdict-proxy';
const dd1 = defaultdict([]);
dd1.a = { b: 0 };
dd1.a.b === 0;
dd1.b.push(42);
dd1.b;
dd1.c;
dd1.d === dd1.e;
const dd2 = defaultdict(() => new Date());
const dd3 = defaultdict(attr => attr);
dd3.blah
const dd4 = defaultdict(() => x => x);
License
MIT