Created
December 11, 2023 09:53
-
-
Save bigmistqke/fa6543ba56ab5b09479905e2469aecff to your computer and use it in GitHub Desktop.
ArrayInPlace
This file contains 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
/** | |
* 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