Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Attempt at creating a Ruby-ish Hash using JavaScript's Proxy.
'use strict';
const values = new Map();
const getValues = hash => {
const v = values.get(hash) || new Map();
values.set(hash, v);
return v;
};
class Hash extends Map {
constructor(...args) {
super(...args);
return new Proxy(this, {
set(target, prop, value) {
const desc = Reflect.getOwnPropertyDescriptor(target, prop);
if (desc && typeof desc.value === 'function') {
return target[prop](value);
}
if (desc && typeof desc.set === 'function') {
target[prop] = value;
return value;
}
target.set(prop, value);
return value;
},
get(target, prop, receiver) {
if (!(prop in target)) {
return target.get(prop);
}
if (typeof target[prop] === 'function') {
return target[prop].bind(target);
}
return target[prop];
}
});
}
set(key, value) {
const values = getValues(this);
values.set(value, key);
return super.set(key, value);
}
delete(key) {
const values = getValues(this);
const value = this.get(key);
values.delete(value);
return super.delete(key);
}
key(value) {
const values = getValues(this);
return values.get(value);
}
}
const hash = new Hash([['foo', 'bar'], ['baz', 'qux']]);
hash.baz = 'whatever';
console.log(hash.key('bar'));
console.log(hash.has('baz'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment