Skip to content

Commit 27883ac

Browse files
feat: add array union algorithm
1 parent 5c39e87 commit 27883ac

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

‎Data-Structures/Array/Union.js‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @function union
3+
* @description Returns a new array containing all unique elements
4+
* from both input arrays, preserving order of first occurrence.
5+
* @param {Array} arr1 - The first input array
6+
* @param {Array} arr2 - The second input array
7+
* @returns {Array} - Array of all unique elements from both arrays
8+
* @see https://en.wikipedia.org/wiki/Union_(set_theory)
9+
* @example union([1, 2, 3], [2, 3, 4]) => [1, 2, 3, 4]
10+
* @example union([1, 2], [3, 4]) => [1, 2, 3, 4]
11+
* @example union([1, 1, 2], [2, 3]) => [1, 2, 3]
12+
*/
13+
const union = (arr1, arr2) => {
14+
if (!Array.isArray(arr1) || !Array.isArray(arr2)) {
15+
throw new TypeError('Both inputs must be arrays')
16+
}
17+
return [...new Set([...arr1, ...arr2])]
18+
}
19+
20+
export { union }
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { union } from '../Union.js'
2+
3+
describe('union', () => {
4+
test('union([1,2,3],[2,3,4]) returns [1,2,3,4]', () => {
5+
expect(union([1, 2, 3], [2, 3, 4])).toEqual([1, 2, 3, 4])
6+
})
7+
8+
test('union([1,2],[3,4]) returns [1,2,3,4]', () => {
9+
expect(union([1, 2], [3, 4])).toEqual([1, 2, 3, 4])
10+
})
11+
12+
test('union([1,1,2],[2,3]) returns [1,2,3]', () => {
13+
expect(union([1, 1, 2], [2, 3])).toEqual([1, 2, 3])
14+
})
15+
16+
test('union with empty first array returns arr2 values', () => {
17+
expect(union([], [1, 2, 3])).toEqual([1, 2, 3])
18+
})
19+
20+
test('union with empty second array returns arr1 values', () => {
21+
expect(union([1, 2, 3], [])).toEqual([1, 2, 3])
22+
})
23+
24+
test('union with identical arrays returns same values', () => {
25+
expect(union([1, 2, 3], [1, 2, 3])).toEqual([1, 2, 3])
26+
})
27+
28+
test('union works with strings', () => {
29+
expect(union(['a', 'b'], ['b', 'c'])).toEqual(['a', 'b', 'c'])
30+
})
31+
32+
test('union does not mutate original arrays', () => {
33+
const arr1 = [1, 2, 3]
34+
const arr2 = [2, 3, 4]
35+
union(arr1, arr2)
36+
expect(arr1).toEqual([1, 2, 3])
37+
expect(arr2).toEqual([2, 3, 4])
38+
})
39+
40+
test('throws TypeError for non-array first input', () => {
41+
expect(() => union('123', [1, 2])).toThrow(TypeError)
42+
})
43+
44+
test('throws TypeError for non-array second input', () => {
45+
expect(() => union([1, 2], '123')).toThrow(TypeError)
46+
})
47+
})

0 commit comments

Comments
 (0)