Skip to content

Instantly share code, notes, and snippets.

@gl2748
Last active March 5, 2019 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gl2748/2c7edec89434234ced6db757b6237b07 to your computer and use it in GitHub Desktop.
Save gl2748/2c7edec89434234ced6db757b6237b07 to your computer and use it in GitHub Desktop.
use proxy to add map and reduce array methods to an object in javascript
const o = {
x: {
v: "hello"
},
y: {
v: "world"
}
};
const handler = {
get: (obj, prop) => {
if (prop === "map") {
return cb => Object.keys(obj).map((k, i) => cb(obj[k], i, obj));
}
if (prop === "reduce") {
const reducer = cb => (acc, curr, idx) =>{
return cb(acc, obj[curr], idx, obj)
}
return (cb, init) => Object.keys(obj).reduce(reducer(cb), init)
}
if (props === "length") {
return Object.keys(obj).length;
}
return obj[prop];
}
};
const x = new Proxy(o, handler)
console.log('Length', x.length)
console.log('Map', x.map(y => y.v));
const reducer = (acc, curr, idx, src) => {
return [...acc, {idx: idx, val: curr.v}]
}
console.log('Reduce', x.reduce(reducer, []))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment