Last active
August 22, 2018 02:16
-
-
Save westc/21095b56aa3aa03300fce3aed6f77c3b to your computer and use it in GitHub Desktop.
YourJS candidate function: Takes the keys to copy from the specified subject and place in the returned object. This can be called as a partial function.
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
console.loadYourJS({ functions: ['has'] }); | |
//\\ | |
var { has } = YourJS; | |
//\\ | |
// requires has() | |
function only(opt_subject, keys, opt_initial) { | |
function f(subject, opt_initial) { | |
var result = {}; | |
return keys.reduce(function (result, key) { | |
if (has(subject, key)) { | |
result[key] = subject[key]; | |
} | |
return result; | |
}, opt_initial || {}); | |
} | |
return keys ? f(opt_subject, opt_initial) : ((keys = opt_subject), f); | |
} | |
//\\ | |
var people = [ | |
'Female: Celia Cruz', | |
'Male: Antonio Banderas', | |
'Female: Estefania Delarosa', | |
'Male: Tiago Morais', | |
'Male: Victor Hughes', | |
'Female: Britney Stalls' | |
].map(x => (([g, f, l]) => ({ gender: g, firstName: f, lastName: l }))(x.split(/:? /))); | |
//\\ | |
var onlyNames = only(['firstName', 'lastName']); | |
people.forEach(x => console.log('Names:', onlyNames(x))); | |
//\\ | |
people.forEach(x => console.log('Gender:', only(x, ['gender']))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See it in action here:
https://www.yourjs.com/console/?gist=21095b56aa3aa03300fce3aed6f77c3b&file=only.js