Last active
March 5, 2019 21:55
-
-
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
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 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