Last active
November 7, 2017 23:26
-
-
Save Veejay/103aaf396397ceb5afbb4764392a59a5 to your computer and use it in GitHub Desktop.
Object extension
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
const wrap = (object) => { | |
return new Proxy(object, { | |
get(target, property, receiver) { | |
switch (property) { | |
case 'store': | |
return (...args) => { | |
return Reflect.set(object, ...args) | |
} | |
break | |
case 'fetch': | |
return (...args) => { | |
const [key, defaultValue] = args | |
return Reflect.get(object, key) || defaultValue | |
} | |
break | |
case 'map': | |
return (...args) => { | |
const [mapper] = args | |
return Object.keys(object).map(key => { | |
return mapper(key, object[key]) | |
}) | |
} | |
} | |
} | |
}) | |
} | |
``` | |
const a = {foobar: 2} | |
const b = wrap(a) | |
b.store('lukaku', 9) | |
=> true | |
b.fetch('foobar') | |
=> 2 | |
a | |
=> {foobar: 2, lukaku: 9} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment