Skip to content

Commit

Permalink
Added mapCompleted
Browse files Browse the repository at this point in the history
  • Loading branch information
guillemcordoba committed Apr 28, 2024
1 parent d5b0728 commit 7088291
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/signals/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@holochain-open-dev/signals",
"version": "0.300.0-dev.4",
"version": "0.300.0-dev.5",
"description": "Holochain async-signals to build reusable holochain-open-dev modules",
"author": "[email protected]",
"main": "dist/index.js",
Expand Down
1 change: 1 addition & 0 deletions packages/signals/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ export * from "./join-map.js";
export * from "./utils.js";
export * from "./holochain.js";
export * from "./watch.js";
export * from "./map-completed.js";
21 changes: 21 additions & 0 deletions packages/signals/src/map-completed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { AsyncComputed, AsyncSignal } from "async-signals";

/**
* Transforms the value for the given signal, when its status is 'completed'.
*
* When the status of the given `AsyncSignal` is other than 'completed', it returns that result.
*/
export function mapCompleted<T, U>(
asyncSignal: AsyncSignal<T>,
mapFn: (value: T) => U
): AsyncSignal<U> {
return new AsyncComputed(() => {
const result = asyncSignal.get();
if (result.status !== "completed") return result;
const value = mapFn(result.value);
return {
status: "completed",
value,
};
});
}
23 changes: 23 additions & 0 deletions packages/signals/tests/map-completed.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { expect, it } from "vitest";
import { fromPromise } from "async-signals";

import { mapCompleted, watch } from "../src";

const sleep = (ms) => new Promise((r) => setTimeout(() => r(), ms));

it("mapCompleted", async () => {
const signal = fromPromise(async () => {
await sleep(10);
return 1;
});
const signal2 = mapCompleted(signal, (n) => n + 1);

watch(signal2, () => {});

expect(signal2.get().status).to.be.equal("pending");

await sleep(20);

expect(signal2.get().status).to.be.equal("completed");
expect(signal2.get().value).to.be.equal(2);
});

0 comments on commit 7088291

Please sign in to comment.