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, + ]); + }); +});