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
18 changes: 18 additions & 0 deletions Data-Structures/Array/Compact.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* @function compact
* @description Removes all falsy values from an array.
* Falsy values are: false, null, 0, "", undefined, NaN.
* @param {Array} arr - The input array
* @returns {Array} - A new array with all falsy values removed
* @see https://en.wikipedia.org/wiki/Truthiness
* @example compact([1, false, 2, null, 3, undefined]) => [1, 2, 3]
* @example compact([0, 1, "", 2, NaN, 3]) => [1, 2, 3]
*/
const compact = (arr) => {
if (!Array.isArray(arr)) {
throw new TypeError('Input must be an array')
}
return arr.filter(Boolean)
}

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

describe('compact', () => {
test('compact removes false values', () => {
expect(compact([1, false, 2])).toEqual([1, 2])
})

test('compact removes null values', () => {
expect(compact([1, null, 2])).toEqual([1, 2])
})

test('compact removes undefined values', () => {
expect(compact([1, undefined, 2])).toEqual([1, 2])
})

test('compact removes 0 values', () => {
expect(compact([1, 0, 2])).toEqual([1, 2])
})

test('compact removes empty string values', () => {
expect(compact([1, '', 2])).toEqual([1, 2])
})

test('compact removes NaN values', () => {
expect(compact([1, NaN, 2])).toEqual([1, 2])
})

test('compact removes all falsy values together', () => {
expect(compact([1, false, 2, null, 3, undefined])).toEqual([1, 2, 3])
})

test('compact empty array returns empty array', () => {
expect(compact([])).toEqual([])
})

test('compact array with no falsy values returns same values', () => {
expect(compact([1, 2, 3])).toEqual([1, 2, 3])
})

test('compact does not mutate original array', () => {
const arr = [1, false, 2, null]
compact(arr)
expect(arr).toEqual([1, false, 2, null])
})

test('throws TypeError for non-array input', () => {
expect(() => compact('123')).toThrow(TypeError)
})

test('throws TypeError for null input', () => {
expect(() => compact(null)).toThrow(TypeError)
})
})
Loading