Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 4 additions & 8 deletions src/utils/uniq.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
const iterateeUniq = <T, U>(arr: T[], iteratee: (value: T, i: number, arr: T[]) => U): T[] => {
const result: T[] = [],
seen: U[] = [];
seen = new Set<U>();

for (let i = 0, length = arr.length; i < length; i++) {
const value = arr[i],
computed = iteratee(value, i, arr);

if (seen.indexOf(computed) === -1) {
seen.push(computed);
if (!seen.has(computed)) {
seen.add(computed);
result.push(value);
}
}
Expand All @@ -33,11 +33,7 @@ const sortedUniq = <T, U>(arr: T[]): T[] => {


const standardUniq = <T>(arr: T[]): T[] => {
const result = arr.filter((value, index, _arr) => {
return _arr.indexOf(value) === index;
});

return result;
return Array.from(new Set(arr));
};


Expand Down
43 changes: 43 additions & 0 deletions tests/utils/uniq.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,47 @@ describe('uniq', () => {
expect(uniq([ 4, 4, 1, 1, 2, 3, 4 ], false, isEven)).to.eql([ 4, 1 ]);
});


it('handles 40,000 elements in under 50ms', () => {
const arr: string[] = [];

for (let i = 0; i < 40000; i++) {
arr.push('item-' + (Math.random() < 0.3 ? i % Math.floor(40000 * 0.7) : i));
}

// Warmup to avoid JIT noise
uniq(arr);

const start = performance.now(),
result = uniq(arr);

expect(performance.now() - start).to.be.lessThan(50);
expect(result.length).to.be.greaterThan(0);
expect(result.length).to.be.lessThan(arr.length);
});


it('handles 40,000 elements with iteratee in under 50ms', () => {
const arr: string[] = [];

for (let i = 0; i < 40000; i++) {
arr.push('item-' + i);
}

// Iteratee that produces many unique computed values, causing the
// seen array to grow large and indexOf to become O(n)
const iteratee = (v: string): string => {
return v + '-computed';
};

// Warmup
uniq(arr, false, iteratee);

const start = performance.now(),
result = uniq(arr, false, iteratee);

expect(performance.now() - start).to.be.lessThan(50);
expect(result.length).to.strictlyEqual(40000);
});

});
Loading