Skip to content

Commit 6484f60

Browse files
feat: add array compact algorithm
1 parent 5c39e87 commit 6484f60

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

‎Data-Structures/Array/Compact.js‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* @function compact
3+
* @description Removes all falsy values from an array.
4+
* Falsy values are: false, null, 0, "", undefined, NaN.
5+
* @param {Array} arr - The input array
6+
* @returns {Array} - A new array with all falsy values removed
7+
* @see https://en.wikipedia.org/wiki/Truthiness
8+
* @example compact([1, false, 2, null, 3, undefined]) => [1, 2, 3]
9+
* @example compact([0, 1, "", 2, NaN, 3]) => [1, 2, 3]
10+
*/
11+
const compact = (arr) => {
12+
if (!Array.isArray(arr)) {
13+
throw new TypeError('Input must be an array')
14+
}
15+
return arr.filter(Boolean)
16+
}
17+
18+
export { compact }
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import { compact } from '../Compact.js'
2+
3+
describe('compact', () => {
4+
test('compact removes false values', () => {
5+
expect(compact([1, false, 2])).toEqual([1, 2])
6+
})
7+
8+
test('compact removes null values', () => {
9+
expect(compact([1, null, 2])).toEqual([1, 2])
10+
})
11+
12+
test('compact removes undefined values', () => {
13+
expect(compact([1, undefined, 2])).toEqual([1, 2])
14+
})
15+
16+
test('compact removes 0 values', () => {
17+
expect(compact([1, 0, 2])).toEqual([1, 2])
18+
})
19+
20+
test('compact removes empty string values', () => {
21+
expect(compact([1, '', 2])).toEqual([1, 2])
22+
})
23+
24+
test('compact removes NaN values', () => {
25+
expect(compact([1, NaN, 2])).toEqual([1, 2])
26+
})
27+
28+
test('compact removes all falsy values together', () => {
29+
expect(compact([1, false, 2, null, 3, undefined])).toEqual([1, 2, 3])
30+
})
31+
32+
test('compact empty array returns empty array', () => {
33+
expect(compact([])).toEqual([])
34+
})
35+
36+
test('compact array with no falsy values returns same values', () => {
37+
expect(compact([1, 2, 3])).toEqual([1, 2, 3])
38+
})
39+
40+
test('compact does not mutate original array', () => {
41+
const arr = [1, false, 2, null]
42+
compact(arr)
43+
expect(arr).toEqual([1, false, 2, null])
44+
})
45+
46+
test('throws TypeError for non-array input', () => {
47+
expect(() => compact('123')).toThrow(TypeError)
48+
})
49+
50+
test('throws TypeError for null input', () => {
51+
expect(() => compact(null)).toThrow(TypeError)
52+
})
53+
})

0 commit comments

Comments
 (0)