Skip to content

Commit

Permalink
feat: add to to fx
Browse files Browse the repository at this point in the history
  • Loading branch information
ppeeou committed Oct 14, 2024
1 parent e28b55e commit 85e13c8
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
34 changes: 34 additions & 0 deletions src/Lazy/fx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,22 @@ class FxAsyncIterable<A> {
return this.asyncIterable[Symbol.asyncIterator]();
}

/**
* It takes a user-defined function that transforms the current object and returns the result of that transformation.
*
* @example
* ```ts
* const arrSize = await fx([5, 2, 3, 1, 4, 5, 3])
* .toAsync()
* .filter((n) => n % 2 === 1)
* .map((n) => n * 10)
* .to((iterable) => size(uniq(iterable)));
* ```
*/
to<R>(converter: (asyncIterable: this) => R): R {
return converter(this);
}

/**
* Returns AsyncIterable of values by running each applying `f`.
*
Expand Down Expand Up @@ -301,6 +317,24 @@ export class FxIterable<A> {
return this.iterable[Symbol.iterator]();
}

/**
* It takes a user-defined function that transforms the current object and returns the result of that transformation.
*
*
* @example
* ```ts
* const size = fx([5, 2, 3, 1, 4, 5, 3])
* .filter(n => n % 2 === 1)
* .map(n => n * 10)
* .to(iterable => new Set(iterable)) // convert set
* .add(10)
* .size;
* ```
*/
to<R>(converter: (iterable: this) => R): R {
return converter(this);
}

/**
* Returns Iterable of values by running each applying `f`.
*
Expand Down
21 changes: 20 additions & 1 deletion test/Lazy/fx.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { fx, toArray, toAsync } from "../../src";
import { fx, size, toArray, toAsync, uniq } from "../../src";

describe("fx", function () {
describe("sync", function () {
Expand All @@ -16,6 +16,15 @@ describe("fx", function () {
.toArray();
expect(res).toEqual([11, 12, 13, 14, 15]);
});

it("`to` method", function () {
const arrSize = fx([5, 2, 3, 1, 4, 5, 3])
.filter((n) => n % 2 === 1)
.map((n) => n * 10)
.to((iterable) => new Set(iterable))
.add(10).size;
expect(arrSize).toEqual(3);
});
});

describe("async", () => {
Expand All @@ -39,5 +48,15 @@ describe("fx", function () {
.toArray();
expect(res2).toEqual([11, 12, 13, 14, 15]);
});

it("`to` method", async function () {
const arrSize = await fx([5, 2, 3, 1, 4, 5, 3])
.toAsync()
.filter((n) => n % 2 === 1)
.map((n) => n * 10)
.to((iterable) => size(uniq(iterable)));

expect(arrSize).toEqual(3);
});
});
});

0 comments on commit 85e13c8

Please sign in to comment.