-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunique.ts
More file actions
41 lines (39 loc) · 1.04 KB
/
unique.ts
File metadata and controls
41 lines (39 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* @fileoverview Deduplicate an array via `Set`. Preserves
* first-occurrence order.
*/
import { SetCtor } from '../primordials/map-set'
/**
* Get unique values from an array.
*
* Returns a new array containing only the unique values from the input array.
* Uses `Set` internally for efficient deduplication. Order of first occurrence
* is preserved.
*
* @param arr - The array to deduplicate (can be readonly)
* @returns New array with duplicate values removed
*
* @example
* ```ts
* // Remove duplicate numbers
* arrayUnique([1, 2, 2, 3, 1, 4])
* // Returns: [1, 2, 3, 4]
*
* // Remove duplicate strings
* arrayUnique(['apple', 'banana', 'apple', 'cherry'])
* // Returns: ['apple', 'banana', 'cherry']
*
* // Works with readonly arrays
* const readonlyArr = [1, 1, 2] as const
* arrayUnique(readonlyArr)
* // Returns: [1, 2]
*
* // Empty arrays return empty
* arrayUnique([])
* // Returns: []
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function arrayUnique<T>(arr: T[] | readonly T[]): T[] {
return [...new SetCtor(arr)]
}