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/Difference.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* @function difference
* @description Returns a new array with elements that are in the first
* array but not in the second array.
* @param {Array} arr1 - The first input array
* @param {Array} arr2 - The second input array
* @returns {Array} - Array of elements in arr1 but not in arr2
* @see https://en.wikipedia.org/wiki/Complement_(set_theory)
* @example difference([1, 2, 3], [2, 3, 4]) => [1]
* @example difference([1, 2, 3], [1, 2, 3]) => []
* @example difference([1, 2, 3], []) => [1, 2, 3]
*/
const difference = (arr1, arr2) => {
if (!Array.isArray(arr1) || !Array.isArray(arr2)) {
throw new TypeError('Both inputs must be arrays')
}
const set2 = new Set(arr2)
return arr1.filter((item) => !set2.has(item))
}

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

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

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

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

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

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

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

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

test('difference keeps duplicates from arr1 not in arr2', () => {
expect(difference([1, 1, 2, 3], [2, 3])).toEqual([1, 1])
})

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

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