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
21 changes: 21 additions & 0 deletions Data-Structures/Array/Intersection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* @function intersection
* @description Returns a new array containing elements that exist
* in both input arrays. Each element in the result is unique.
* @param {Array} arr1 - The first input array
* @param {Array} arr2 - The second input array
* @returns {Array} - Array of elements present in both arrays
* @see https://en.wikipedia.org/wiki/Intersection_(set_theory)
* @example intersection([1, 2, 3], [2, 3, 4]) => [2, 3]
* @example intersection([1, 2], [3, 4]) => []
* @example intersection([1, 1, 2], [1, 2, 2]) => [1, 2]
*/
const intersection = (arr1, arr2) => {
if (!Array.isArray(arr1) || !Array.isArray(arr2)) {
throw new TypeError('Both inputs must be arrays')
}
const set2 = new Set(arr2)
return [...new Set(arr1.filter((item) => set2.has(item)))]
}

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

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

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

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

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

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

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

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

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

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

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