Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add to to fx #288

Merged
merged 1 commit into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});
});
});
Loading