From 27883ac5c0663f9e350a7949a36a7b5e9d137337 Mon Sep 17 00:00:00 2001 From: sarthakgupta1907-cell Date: Fri, 6 Nov 2026 11:00:38 +0530 Subject: [PATCH] feat: add array union algorithm --- Data-Structures/Array/Union.js | 20 ++++++++++ Data-Structures/Array/test/Union.test.js | 47 ++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 Data-Structures/Array/Union.js create mode 100644 Data-Structures/Array/test/Union.test.js diff --git a/Data-Structures/Array/Union.js b/Data-Structures/Array/Union.js new file mode 100644 index 0000000000..d6fdf50850 --- /dev/null +++ b/Data-Structures/Array/Union.js @@ -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 } diff --git a/Data-Structures/Array/test/Union.test.js b/Data-Structures/Array/test/Union.test.js new file mode 100644 index 0000000000..81354e1cf7 --- /dev/null +++ b/Data-Structures/Array/test/Union.test.js @@ -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) + }) +})