mirror of
https://github.com/toss/es-toolkit.git
synced 2024-11-24 11:45:26 +03:00
perf(uniq): Improve performance of uniq
function (#40)
* fix<uniq>: make uniq function to use Set * test(uniq): write additional test codes for uniq function * Update src/array/uniq.ts --------- Co-authored-by: Sojin Park <raon0211@gmail.com>
This commit is contained in:
parent
0a02cdcaea
commit
d7c37c9fb6
@ -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]);
|
||||
});
|
||||
});
|
||||
|
@ -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));
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user