Created
June 21, 2018 09:57
-
-
Save joeytwiddle/ea27d537585894830154fdaa797a079d to your computer and use it in GitHub Desktop.
Some Array functions for Objects
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
// The functional way | |
const objUtils = { | |
mapProps(obj, mapFn) { | |
return Object.entries(obj).reduce((a, [key, value]) => ( | |
{ ...a, [key]: mapFn(value) } | |
), {}); | |
}, | |
filterProps(obj, filterFn) { | |
return Object.entries(obj).reduce((a, [key, value]) => ( | |
filterFn(value) | |
? { ...a, [key]: value } | |
: a | |
), {}); | |
}, | |
}; | |
// The imperative way | |
const objUtils = { | |
mapProps(obj, mapFn) { | |
const out = {}; | |
for (const [key, value] of Object.entries(obj)) { | |
out[key] = mapFn(value); | |
} | |
return out; | |
}, | |
filterProps(obj, filterFn) { | |
const out = {}; | |
for (const [key, value] of Object.entries(obj)) { | |
if (filterFn(value)) { | |
out[key] = value; | |
} | |
} | |
return out; | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment