Skip to content

Instantly share code, notes, and snippets.

@bigmistqke
Created December 11, 2023 09:53
Show Gist options
  • Save bigmistqke/fa6543ba56ab5b09479905e2469aecff to your computer and use it in GitHub Desktop.
Save bigmistqke/fa6543ba56ab5b09479905e2469aecff to your computer and use it in GitHub Desktop.
ArrayInPlace
/**
* array extended with mutable/in-place array-methods
*/
class ArrayInPlace<T = number> extends Array {
commands: Command<T>[] = [];
constructor(values: T[]) {
super();
Array.prototype.push.apply(this, values);
}
mapInPlace(fn: (value: T, index: number) => T) {
for (let index = 0; index < this.length; index++) {
this[index] = fn(this[index], index);
}
return this;
}
filterInPlace(fn: (value: T, index: number) => boolean) {
let deleteCount = 0;
const length = this.length;
for (let index = length - 1; index >= 0; index--) {
if (!fn(this[index], index)) {
deleteCount++;
if (index === 0) {
this.splice(index, deleteCount);
}
continue;
}
if (deleteCount > 0) {
this.splice(index, deleteCount);
}
}
return this;
}
set(index: number, value: T) {
this[index] = value;
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment