Created
May 18, 2021 06:25
-
-
Save jonschlinkert/bcfc1fed2514da56da4d9d24bb55a7cd to your computer and use it in GitHub Desktop.
Attempt at creating a Ruby-ish Hash using JavaScript's Proxy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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