Skip to content

Commit

Permalink
feat: add _.compact replacement (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
crgwbr committed Sep 3, 2024
1 parent 2885ba4 commit 39e08a5
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
14 changes: 14 additions & 0 deletions src/utils/compact.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
type FalsyVals = '' | 0 | false | null | undefined;

function notFalsy<T>(value: T | FalsyVals): value is T {
return value !== ''
&& value !== 0
&& value !== false
&& value !== null
&& value !== undefined
&& !(typeof value === 'number' && isNaN(value));
}

export function compact<T>(arr: (T | FalsyVals)[]): T[] {
return arr.filter(notFalsy);
}
29 changes: 29 additions & 0 deletions tests/utils/compact.test.ts
Original file line number Diff line number Diff line change
@@ -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,
]);
});
});

0 comments on commit 39e08a5

Please sign in to comment.