Skip to content

Commit 600fe10

Browse files
feat: add array unique algorithm
1 parent 5c39e87 commit 600fe10

2 files changed

Lines changed: 64 additions & 0 deletions

File tree

‎Data-Structures/Array/Unique.js‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* @function unique
3+
* @description Returns a new array with all duplicate values removed,
4+
* preserving the order of first occurrence.
5+
* @param {Array} arr - The input array
6+
* @returns {Array} - A new array with only unique values
7+
* @see https://en.wikipedia.org/wiki/Set_(abstract_data_type)
8+
* @example unique([1, 2, 2, 3]) => [1, 2, 3]
9+
* @example unique([1, 1, 1]) => [1]
10+
* @example unique([1, "1", 1]) => [1, "1"]
11+
*/
12+
const unique = (arr) => {
13+
if (!Array.isArray(arr)) {
14+
throw new TypeError('Input must be an array')
15+
}
16+
return [...new Set(arr)]
17+
}
18+
19+
export { unique }
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { unique } from '../Unique.js'
2+
3+
describe('unique', () => {
4+
test('unique([1, 2, 2, 3]) returns [1, 2, 3]', () => {
5+
expect(unique([1, 2, 2, 3])).toEqual([1, 2, 3])
6+
})
7+
8+
test('unique([1, 1, 1]) returns [1]', () => {
9+
expect(unique([1, 1, 1])).toEqual([1])
10+
})
11+
12+
test("unique([1, '1', 1]) returns [1, '1']", () => {
13+
expect(unique([1, '1', 1])).toEqual([1, '1'])
14+
})
15+
16+
test('unique([]) returns []', () => {
17+
expect(unique([])).toEqual([])
18+
})
19+
20+
test('unique with no duplicates returns same values', () => {
21+
expect(unique([1, 2, 3])).toEqual([1, 2, 3])
22+
})
23+
24+
test('unique preserves order of first occurrence', () => {
25+
expect(unique([3, 1, 2, 1, 3])).toEqual([3, 1, 2])
26+
})
27+
28+
test('unique works with strings', () => {
29+
expect(unique(['a', 'b', 'a', 'c'])).toEqual(['a', 'b', 'c'])
30+
})
31+
32+
test('unique does not mutate original array', () => {
33+
const arr = [1, 2, 2, 3]
34+
unique(arr)
35+
expect(arr).toEqual([1, 2, 2, 3])
36+
})
37+
38+
test('throws TypeError for non-array input', () => {
39+
expect(() => unique('123')).toThrow(TypeError)
40+
})
41+
42+
test('throws TypeError for null input', () => {
43+
expect(() => unique(null)).toThrow(TypeError)
44+
})
45+
})

0 commit comments

Comments
 (0)