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 ec7828c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/List.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

export type List<A> = () => Generator<A, unknown, undefined>;

export function of<A>(a: A): List<A> {
Expand Down Expand Up @@ -27,6 +28,21 @@ 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
15 changes: 15 additions & 0 deletions src/__tests__/List.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { InfiniteList } from '../InfiniteList';
import type { List } from '../List';
import * as List_ from '../List';
import type { NonEmptyList } from '../NonEmptyList';
import * as InfiniteList_ from '../InfiniteList';

describe('List', () => {
describe('type', () => {
Expand Down Expand Up @@ -69,6 +70,20 @@ 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 ec7828c

Please sign in to comment.