Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Created February 21, 2016 18:56
Show Gist options
  • Save lovasoa/2f0f6e80d8fb14e8cff7 to your computer and use it in GitHub Desktop.
Save lovasoa/2f0f6e80d8fb14e8cff7 to your computer and use it in GitHub Desktop.
mapfilter function, just like map, but can also discard elements. Equivalent to array.map(fun).filter(n => n !== undefined)
function mapfilter(array, fun) {
// Equivalent to array.map(fun).filter(x => x !== undefined)
var res = [];
for(var i=0; i<array.length; i++) {
var r = fun(array[i], i, array);
if (r !== void 0) res.push(r);
}
return res;
}
@lovasoa
Copy link
Author

lovasoa commented Feb 21, 2016

Exemple use :

mapfilter([-10, 0, 100], n => n<0 ? undefined : Math.sqrt(n)) // [0, 10]

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