Skip to content

Commit a321568

Browse files
feat: add array intersection algorithm
1 parent 5c39e87 commit a321568

2 files changed

Lines changed: 68 additions & 0 deletions

File tree

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

0 commit comments

Comments
 (0)