Skip to content

Commit 1bbca7a

Browse files
feat: add array difference algorithm
1 parent 5c39e87 commit 1bbca7a

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 difference
3+
* @description Returns a new array with elements that are in the first
4+
* array but not in the second array.
5+
* @param {Array} arr1 - The first input array
6+
* @param {Array} arr2 - The second input array
7+
* @returns {Array} - Array of elements in arr1 but not in arr2
8+
* @see https://en.wikipedia.org/wiki/Complement_(set_theory)
9+
* @example difference([1, 2, 3], [2, 3, 4]) => [1]
10+
* @example difference([1, 2, 3], [1, 2, 3]) => []
11+
* @example difference([1, 2, 3], []) => [1, 2, 3]
12+
*/
13+
const difference = (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 arr1.filter((item) => !set2.has(item))
19+
}
20+
21+
export { difference }
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { difference } from '../Difference.js'
2+
3+
describe('difference', () => {
4+
test('difference([1,2,3],[2,3,4]) returns [1]', () => {
5+
expect(difference([1, 2, 3], [2, 3, 4])).toEqual([1])
6+
})
7+
8+
test('difference([1,2,3],[1,2,3]) returns []', () => {
9+
expect(difference([1, 2, 3], [1, 2, 3])).toEqual([])
10+
})
11+
12+
test('difference([1,2,3],[]) returns [1,2,3]', () => {
13+
expect(difference([1, 2, 3], [])).toEqual([1, 2, 3])
14+
})
15+
16+
test('difference([],[1,2,3]) returns []', () => {
17+
expect(difference([], [1, 2, 3])).toEqual([])
18+
})
19+
20+
test('difference([1,2,3],[4,5,6]) returns [1,2,3]', () => {
21+
expect(difference([1, 2, 3], [4, 5, 6])).toEqual([1, 2, 3])
22+
})
23+
24+
test('difference works with strings', () => {
25+
expect(difference(['a', 'b', 'c'], ['b', 'c', 'd'])).toEqual(['a'])
26+
})
27+
28+
test('difference does not mutate original arrays', () => {
29+
const arr1 = [1, 2, 3]
30+
const arr2 = [2, 3, 4]
31+
difference(arr1, arr2)
32+
expect(arr1).toEqual([1, 2, 3])
33+
expect(arr2).toEqual([2, 3, 4])
34+
})
35+
36+
test('difference keeps duplicates from arr1 not in arr2', () => {
37+
expect(difference([1, 1, 2, 3], [2, 3])).toEqual([1, 1])
38+
})
39+
40+
test('throws TypeError for non-array first input', () => {
41+
expect(() => difference('123', [1, 2])).toThrow(TypeError)
42+
})
43+
44+
test('throws TypeError for non-array second input', () => {
45+
expect(() => difference([1, 2], '123')).toThrow(TypeError)
46+
})
47+
})

0 commit comments

Comments
 (0)