From 39e08a5e59f626ab713602bce8b645eeec2b94cf Mon Sep 17 00:00:00 2001 From: Craig Weber Date: Tue, 3 Sep 2024 15:11:07 -0400 Subject: [PATCH] feat: add _.compact replacement (#35) --- src/index.ts | 1 + src/utils/compact.ts | 14 ++++++++++++++ tests/utils/compact.test.ts | 29 +++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) create mode 100644 src/utils/compact.ts create mode 100644 tests/utils/compact.test.ts diff --git a/src/index.ts b/src/index.ts index 48129d5..256711c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -29,6 +29,7 @@ export * from './utils/is-null'; export * from './utils/is-not-null-or-undefined'; export * from './utils/chunk'; +export * from './utils/compact'; export * from './utils/flatten'; export * from './utils/pick'; export * from './utils/pluck'; diff --git a/src/utils/compact.ts b/src/utils/compact.ts new file mode 100644 index 0000000..4ed3936 --- /dev/null +++ b/src/utils/compact.ts @@ -0,0 +1,14 @@ +type FalsyVals = '' | 0 | false | null | undefined; + +function notFalsy(value: T | FalsyVals): value is T { + return value !== '' + && value !== 0 + && value !== false + && value !== null + && value !== undefined + && !(typeof value === 'number' && isNaN(value)); +} + +export function compact(arr: (T | FalsyVals)[]): T[] { + return arr.filter(notFalsy); +} diff --git a/tests/utils/compact.test.ts b/tests/utils/compact.test.ts new file mode 100644 index 0000000..f286512 --- /dev/null +++ b/tests/utils/compact.test.ts @@ -0,0 +1,29 @@ +import { expect } from 'chai'; +import { compact } from '../../src'; + +describe('compact', () => { + + it('compact arrays', () => { + const arrA: (string | number | boolean | null | undefined)[] = [ + 'foo', + 0, + '', + true, + false, + null, + 'hello', + undefined, + 42, + NaN, + ]; + + const arrB: (string | number | boolean)[] = compact(arrA); + + expect(arrB).to.eql([ + 'foo', + true, + 'hello', + 42, + ]); + }); +});