Skip to content
Open
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
20 changes: 20 additions & 0 deletions Data-Structures/Array/Union.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @function union
* @description Returns a new array containing all unique elements
* from both input arrays, preserving order of first occurrence.
* @param {Array} arr1 - The first input array
* @param {Array} arr2 - The second input array
* @returns {Array} - Array of all unique elements from both arrays
* @see https://en.wikipedia.org/wiki/Union_(set_theory)
* @example union([1, 2, 3], [2, 3, 4]) => [1, 2, 3, 4]
* @example union([1, 2], [3, 4]) => [1, 2, 3, 4]
* @example union([1, 1, 2], [2, 3]) => [1, 2, 3]
*/
const union = (arr1, arr2) => {
if (!Array.isArray(arr1) || !Array.isArray(arr2)) {
throw new TypeError('Both inputs must be arrays')
}
return [...new Set([...arr1, ...arr2])]
}

export { union }
47 changes: 47 additions & 0 deletions Data-Structures/Array/test/Union.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { union } from '../Union.js'

describe('union', () => {
test('union([1,2,3],[2,3,4]) returns [1,2,3,4]', () => {
expect(union([1, 2, 3], [2, 3, 4])).toEqual([1, 2, 3, 4])
})

test('union([1,2],[3,4]) returns [1,2,3,4]', () => {
expect(union([1, 2], [3, 4])).toEqual([1, 2, 3, 4])
})

test('union([1,1,2],[2,3]) returns [1,2,3]', () => {
expect(union([1, 1, 2], [2, 3])).toEqual([1, 2, 3])
})

test('union with empty first array returns arr2 values', () => {
expect(union([], [1, 2, 3])).toEqual([1, 2, 3])
})

test('union with empty second array returns arr1 values', () => {
expect(union([1, 2, 3], [])).toEqual([1, 2, 3])
})

test('union with identical arrays returns same values', () => {
expect(union([1, 2, 3], [1, 2, 3])).toEqual([1, 2, 3])
})

test('union works with strings', () => {
expect(union(['a', 'b'], ['b', 'c'])).toEqual(['a', 'b', 'c'])
})

test('union does not mutate original arrays', () => {
const arr1 = [1, 2, 3]
const arr2 = [2, 3, 4]
union(arr1, arr2)
expect(arr1).toEqual([1, 2, 3])
expect(arr2).toEqual([2, 3, 4])
})

test('throws TypeError for non-array first input', () => {
expect(() => union('123', [1, 2])).toThrow(TypeError)
})

test('throws TypeError for non-array second input', () => {
expect(() => union([1, 2], '123')).toThrow(TypeError)
})
})
Loading