Skip to content

Commit

Permalink
perf(pull): faster pull (#915)
Browse files Browse the repository at this point in the history
* improve pull

* fix lint error

* refactor to use hasOwn

---------

Co-authored-by: Sojin Park <raon0211@gmail.com>
  • Loading branch information
tuhm1 and raon0211 authored Dec 27, 2024
1 parent c26a1fc commit a6f8081
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
42 changes: 42 additions & 0 deletions benchmarks/performance/pull.bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { bench, describe } from 'vitest';
import { pull as pullToolkit } from 'es-toolkit/compat';
import { pull as pullLodash } from 'lodash';

describe('pull array size 100', () => {
const array = [...Array(100)].map((_, i) => i);
const even = [...Array(50)].map((_, i) => i * 2);

bench('es-toolkit/pull', () => {
pullToolkit([...array], even);
});

bench('lodash/pull', () => {
pullLodash([...array], ...even);
});
});

describe('pull array size 1000', () => {
const array = [...Array(1000)].map((_, i) => i);
const even = [...Array(500)].map((_, i) => i * 2);

bench('es-toolkit/pull', () => {
pullToolkit([...array], [...even]);
});

bench('lodash/pull', () => {
pullLodash([...array], ...even);
});
});

describe('pull array size 10000', () => {
const array = [...Array(10000)].map((_, i) => i);
const even = [...Array(5000)].map((_, i) => i * 2);

bench('es-toolkit/pull', () => {
pullToolkit([...array], [...even]);
});

bench('lodash/pull', () => {
pullLodash([...array], ...even);
});
});
15 changes: 13 additions & 2 deletions src/array/pull.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,23 @@
*/
export function pull<T>(arr: T[], valuesToRemove: readonly unknown[]): T[] {
const valuesSet = new Set(valuesToRemove);
let resultIndex = 0;

for (let i = arr.length - 1; i >= 0; i--) {
for (let i = 0; i < arr.length; i++) {
if (valuesSet.has(arr[i])) {
arr.splice(i, 1);
continue;
}

// For handling sparse arrays
if (!Object.hasOwn(arr, i)) {
delete arr[resultIndex++];
continue;
}

arr[resultIndex++] = arr[i];
}

arr.length = resultIndex;

return arr;
}

0 comments on commit a6f8081

Please sign in to comment.