Skip to content

Commit

Permalink
feat(list): add filter many helper
Browse files Browse the repository at this point in the history
  • Loading branch information
ssube committed Aug 1, 2020
1 parent 56e96f3 commit 077d05f
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/List.ts
Expand Up @@ -63,3 +63,22 @@ export function isList<TVal>(list: TVal | ReadonlyArray<TVal>): list is Readonly
export function isList<TVal>(list: TVal | ReadonlyArray<TVal>): list is ReadonlyArray<TVal> {
return Array.isArray(list);
}

export function isEmpty(val: Optional<Array<unknown> | ReadonlyArray<unknown>>): boolean {
return !Array.isArray(val) || val.length === 0;
}

export function filterMany<T1>(cb: (a: T1) => boolean, l1: Array<T1>): Array<T1>;
export function filterMany<T1, T2>(cb: (a: T1, b: T2) => boolean, l1: Array<T1>, l2: Array<T2>): [Array<T1>, Array<T2>];
export function filterMany<T1, T2, T3>(cb: (a: T1, b: T2) => boolean, l1: Array<T1>, l2: Array<T2>, l3: Array<T3>): [Array<T1>, Array<T2>, Array<T3>];
export function filterMany<T1, T2, T3, T4>(cb: (a: T1, b: T2) => boolean, l1: Array<T1>, l2: Array<T2>, l3: Array<T3>, l4: Array<T4>): [Array<T1>, Array<T2>, Array<T3>, Array<T4>];
export function filterMany(cb: (...d: Array<unknown>) => boolean, ...l: Array<Array<unknown>>): Array<Array<unknown>> {
const results = [];
for (let i = 0; i < l[0].length; ++i) {
const slice = l.map((li) => li[i]);
if (cb(...slice)) {
results.push(slice);
}
}
return results;
}
35 changes: 35 additions & 0 deletions test/utils/TestList.ts
@@ -0,0 +1,35 @@
import { expect } from 'chai';
import { match, stub } from 'sinon';

import { filterMany } from '../../src/List';

describe('list utils', async () => {
describe('filter many helper', async () => {
it('should call the predicate with an item from each list', async () => {
const cb = stub().returns(true);
const results = filterMany(cb, [1], ['a']);

expect(results.length).to.equal(1);
expect(cb).to.have.callCount(1);
expect(cb).to.have.been.calledWithMatch(match.number, match.string);
});

it('should call the predicate for each slice', async () => {
const data = [1, 2, 3, 4, 5];
const cb = stub().returns(true);
const results = filterMany(cb, data);

expect(results.length).to.equal(data.length);
expect(cb).to.have.callCount(data.length);
});

it('should keep slices that passed the predicate', async () => {
const data = [1, 2, 3, 4, 5];
const cb = stub().returns(false);
const results = filterMany(cb, data);

expect(results.length).to.equal(0);
expect(cb).to.have.callCount(data.length);
});
});
});

0 comments on commit 077d05f

Please sign in to comment.