Instantly share code, notes, and snippets.

@westc /mapFilter.js
Last active Aug 22, 2018

Embed
What would you like to do?
YourJS candidate function: Maps values in an array or an object only if the mapped value is true-ish.
console.loadYourJS({ functions: ['forOf', 'typeOf'] });
//\\
var { forOf, typeOf } = YourJS;
//\\
// requires forOf() and typeOf()
function mapFilter(subject, mapper, opt_onlyRemoveUndefined) {
var result,
isArray = typeOf(subject).indexOf('Array') >= 0 && 'function' === typeof subject.splice,
propsToRemove = [];
forOf(subject, function(v, k) {
result = mapper(v, k, subject);
if (opt_onlyRemoveUndefined ? result !== undefined : result) {
subject[k] = result;
}
else {
propsToRemove.unshift(k);
}
});
propsToRemove.forEach(function(k) {
if (isArray) {
subject.splice(k, 1);
}
else {
delete subject[k];
}
});
return subject;
}
//\\
mapFilter([1,2,3,4,5,6,7,8,9], x => x % 4 && x * 2);
//\\
mapFilter([1,2,3,4,5,6,7,8,9], x => x % 4 && x * 2, true);
//\\
mapFilter([1,2,3,4,5,6,7,8,9], x => x % 4 ? x * 2 : x > 5 ? undefined : 0, true);
@westc

This comment has been minimized.

Owner

westc commented Aug 10, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment