From 6484f607c6c29c0887a13c36eee3e4342458884c Mon Sep 17 00:00:00 2001 From: sarthakgupta1907-cell Date: Fri, 6 Nov 2026 11:06:03 +0530 Subject: [PATCH] feat: add array compact algorithm --- Data-Structures/Array/Compact.js | 18 ++++++++ Data-Structures/Array/test/Compact.test.js | 53 ++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 Data-Structures/Array/Compact.js create mode 100644 Data-Structures/Array/test/Compact.test.js diff --git a/Data-Structures/Array/Compact.js b/Data-Structures/Array/Compact.js new file mode 100644 index 0000000000..eee7282a28 --- /dev/null +++ b/Data-Structures/Array/Compact.js @@ -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 } diff --git a/Data-Structures/Array/test/Compact.test.js b/Data-Structures/Array/test/Compact.test.js new file mode 100644 index 0000000000..6d57395edb --- /dev/null +++ b/Data-Structures/Array/test/Compact.test.js @@ -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) + }) +})