Last active
June 29, 2016 08:34
-
-
Save leebyron/b4f17148b68c74aa7357e31f0f3ec921 to your computer and use it in GitHub Desktop.
An array filter function which does not create a new array if no items are removed.
This file contains hidden or 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
function maybeFilter(array, predicate) { | |
var newArray; | |
array.forEach((item, i) => { | |
if (predicate(item)) { | |
if (newArray) { | |
newArray.push(item) | |
} | |
} else if (!newArray) { | |
newArray = array.slice(0, i) | |
} | |
}) | |
return newArray || array; | |
} |
Note that this is only safe if you treat the result of this function as if it were immutable. Mutating the result may in some cases be mutating the original input as well which may be surprising. If you are not mutating the output, then this function may help reduce memory footprint if a filter rarely removes items, and more importantly allows for input === maybeFilter(input, myFunction)
to very cheaply know if the filter did or did not remove anything.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
🆒