Skip to content

Commit

Permalink
Implement chain
Browse files Browse the repository at this point in the history
  • Loading branch information
cyberixae committed Sep 22, 2022
1 parent 477cb34 commit fd10bae
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
16 changes: 16 additions & 0 deletions src/List.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,22 @@ export function map<A, B>(f: (a: A) => B): (la: List<A>) => List<B> {
};
}

export function chain<A, B>(f: (a: A) => List<B>): (la: List<A>) => List<B> {
return (la) =>
function* () {
const ha = la();
while (true) {
const { done, value } = ha.next();
if (done) {
return;
}
const lb = f(value);
const hb = lb();
yield* hb;
}
};
}

export function take(n: number): <A>(la: List<A>) => List<A> {
return (la) =>
function* () {
Expand Down
16 changes: 15 additions & 1 deletion src/__tests__/List.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { pipe } from 'fp-ts/function';

import type { InfiniteList } from '../InfiniteList';
import * as InfiniteList_ from '../InfiniteList';
import type { List } from '../List';
import * as List_ from '../List';
import type { NonEmptyList } from '../NonEmptyList';
Expand Down Expand Up @@ -30,7 +31,9 @@ describe('List', () => {
expect(array).toStrictEqual([123, 456]);
});
it('should destruct an empty List', async () => {
const list: List<number> = function* () { return };
const list: List<number> = function* () {
return;
};
const array: Array<number> = List_.toArray(list);
expect(array).toStrictEqual([]);
});
Expand Down Expand Up @@ -69,6 +72,17 @@ describe('List', () => {
});
});

describe('chain function', () => {
const input = [1, 2, 3];
const result = pipe(
input,
List_.fromArray,
List_.chain((n: number) => pipe(InfiniteList_.of(n), List_.take(n))),
List_.toArray,
);
expect(result).toStrictEqual([1, 2, 2, 3, 3, 3]);
});

describe('take function', () => {
const input = [123, 456];
it('should support limiting list length to zero', async () => {
Expand Down

0 comments on commit fd10bae

Please sign in to comment.