Skip to content

Commit

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

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

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

0 comments on commit f188660

Please sign in to comment.