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..f76cfc7 --- /dev/null +++ b/src/utils/compact.ts @@ -0,0 +1,13 @@ +type FalseyVals = '' | 0 | false | null | undefined; + +function notFalsy(value: T | FalsyVals): value is T { + return value !== '' + && value !== 0 + && value !== false + && value !== null + && value !== undefined; +}; + +export function compact(arr: (T | FalseyVals)[]): T[] { + return arr.filter(notFalsey); +} diff --git a/tests/utils/compact.test.ts b/tests/utils/compact.test.ts new file mode 100644 index 0000000..ac7ac65 --- /dev/null +++ b/tests/utils/compact.test.ts @@ -0,0 +1,28 @@ +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, + ]; + + const arrB: (string | number | boolean)[] = compact(arrA); + + expect(arrB).to.eql([ + 'foo', + true, + 'hello', + 42, + ]); + }); +});