refactor(utils): improve filterInPlace performance with optimized loop structure

This commit is contained in:
productdevbook 2025-01-14 22:04:41 +03:00
parent bc38403daf
commit 57f4e5738f

View File

@ -14,21 +14,19 @@ export function toArray<T> (value: T | T[]): T[] {
* and standard filterInPlace implementations. * and standard filterInPlace implementations.
*/ */
export function filterInPlace<T> (array: T[], predicate: (item: T, index: number, arr: T[]) => unknown) { export function filterInPlace<T> (array: T[], predicate: (item: T, index: number, arr: T[]) => unknown) {
let i = array.length const len = array.length
if (i <= 16) { if (len <= 16) {
while (i--) { for (let i = len; i--; i >= 0) {
if (!predicate(array[i]!, i, array)) { if (!predicate(array[i]!, i, array)) {
array.splice(i, 1) array.splice(i, 1)
} }
} }
} else { } else {
while (i--) { for (let i = len; i--; i >= 0) {
if (!predicate(array[i]!, i, array)) { if (!predicate(array[i]!, i, array)) {
const last = --array.length const last = --array.length
if (i < last) { if (i < last) { array[i] = array[last]! }
array[i] = array[last] as T
}
} }
} }
} }