Skip to content

Instantly share code, notes, and snippets.

@Phoenix35
Last active June 17, 2021 10:21
Show Gist options
  • Save Phoenix35/30f1ed82fbf81485b3bfe6ffd19b49c9 to your computer and use it in GitHub Desktop.
Save Phoenix35/30f1ed82fbf81485b3bfe6ffd19b49c9 to your computer and use it in GitHub Desktop.
// In-place mutation
export function arrayBulkDelete (array, valueOrPredicate) {
const { length } = array,
predicate = typeof valueOrPredicate === "function"
? valueOrPredicate
: (x) => x === valueOrPredicate,
indicesToDelete = [];
let lastIndex = -2;
for (let i = 0; i < length; ++i) {
if (predicate(array[i], i)) {
if (i - 1 === lastIndex) // consecutive
indicesToDelete[indicesToDelete.length - 1][1] = i;
else
indicesToDelete.push([i, i]);
lastIndex = i;
}
}
if (lastIndex === -2)
return;
for (let i = indicesToDelete.length - 1; i >= 0; --i) {
const [ start, end ] = indicesToDelete[i];
array.splice(start, end - start + 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment