Skip to content

Instantly share code, notes, and snippets.

@leebyron
Last active June 29, 2016 08:34
Show Gist options
  • Save leebyron/b4f17148b68c74aa7357e31f0f3ec921 to your computer and use it in GitHub Desktop.
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.
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;
}
@benjamn
Copy link

benjamn commented Jun 28, 2016

🆒

@leebyron
Copy link
Author

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