Skip to content

Instantly share code, notes, and snippets.

@westc westc/filterMap.js
Last active Feb 13, 2019

Embed
What would you like to do?
YourJS candidate function: Maps values from an array if they dont match the negative criteria (opt_badValue).
function filterMap(arr, fn, opt_badValue) {
for (var result, value, isBadValueNaN = opt_badValue !== opt_badValue, ret = [], i = 0, l = arr.length; i < l; i++) {
result = fn(value = arr[i], i, arr);
if (isBadValueNaN ? result === result : result !== opt_badValue) {
ret.push(result);
}
}
return ret;
}
//\\
// Filter out all values divisible by 3 and multiply them by 2
filterMap([1,2,3,4,5,6,7,8,9], function(x) {
if (x % 3) {
return x * 2;
}
});
//\\
// Do "x * abs(x) / x" which is similar to "abs(x)" except 0 will cause
// a NaN which should be filtered out
filterMap([-5,-4,-3,-2,-1,0,1,2,3,4,5], x => x * Math.abs(x) / x, NaN);
@westc

This comment has been minimized.

Copy link
Owner Author

westc commented Aug 10, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.