Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(uniq): Improve performance of uniq function #40

Merged
merged 4 commits into from
Jun 13, 2024
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
31 changes: 31 additions & 0 deletions src/array/uniq.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,35 @@ describe('uniq', () => {
it('uniq function creates unique elements from the array passed as an argument.', () => {
expect(uniq([11, 2, 3, 44, 11, 2, 3])).toEqual([11, 2, 3, 44]);
});
it('uniq function works with strings.', () => {
expect(uniq(['a', 'b', 'b', 'c', 'a'])).toEqual(['a', 'b', 'c']);
});
it('uniq function works with boolean values.', () => {
expect(uniq([true, false, true, false, false])).toEqual([true, false]);
});
it('uniq function works with nullish values.', () => {
expect(uniq([null, undefined, null, undefined])).toEqual([null, undefined]);
});
it('uniq function works with empty arrays.', () => {
expect(uniq([])).toEqual([]);
});
it('uniq function works with multiple types.', () => {
expect(uniq([1, 'a', 2, 'b', 1, 'a'])).toEqual([1, 'a', 2, 'b']);
});
it('uniq function keeps its original order.', () => {
expect(uniq([1, 2, 2, 3, 4, 4, 5])).toEqual([1, 2, 3, 4, 5]);
});
it('uniq function should create a new array.', () => {
const array = [1, 2, 3];
const result = uniq(array);

expect(result).toEqual([1, 2, 3]);
expect(result).not.toBe(array);
});
it('uniq function should not mutate the original array.', () => {
const array = [1, 2, 3, 2, 1, 3];
uniq(array);

expect(array).toEqual([1, 2, 3, 2, 1, 3]);
});
});
12 changes: 1 addition & 11 deletions src/array/uniq.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,5 @@
* // result will be [1, 2, 3, 4, 5]
*/
export function uniq<T>(arr: T[]): T[] {
const result: T[] = [];

for (const item of arr) {
if (result.includes(item)) {
continue;
}

result.push(item);
}

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