1
0
Fork 0

feat(list): add filter many helper

This commit is contained in:
ssube 2020-08-01 10:01:00 -05:00
parent 56e96f35e8
commit 077d05f7c4
Signed by: ssube
GPG Key ID: 3EED7B957D362AF1
2 changed files with 54 additions and 0 deletions

View File

@ -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
test/utils/TestList.ts Normal file
View File

@ -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);
});
});
});