Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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