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

Add tap maybe #19

Closed
wants to merge 3 commits into from
Closed
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
25 changes: 25 additions & 0 deletions src/connector.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,31 @@ export function rawConnector(connectorId, connectorFn) {
registry.set(connectorId, connectorFn);
}

/**
* Connects the `tapFn` to the connector identified by `connectorId` and starts
* applying the stream, from the connected signal, as pairs of current/previous
* values.
*
* @param {string} connectorId The connector identifier.
* @param {function} tapFn A function that is mapped over the stream of `curr`
* and `prev` values from the connected signal.
*
* @example
*
* let s = signal("foo");
* rawConnector("myConnector", () => s)
*
* tap("myConnector", (curr, prev) => {
* console.log(`Got $curr, was $prev`);
* });
*
* s.update("bar"); // => "Got bar, was foo"
* s.update("baz"); // => "Got baz, was bar"
*/
export function tap(connectorId, tapFn) {
return connect(connectorId).connect((_, prev, next) => tapFn(next, prev));
}

/**
* Clears all registered connectors.
*/
Expand Down
19 changes: 19 additions & 0 deletions src/connector.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
connector,
rawConnector,
withInputSignals,
tap,
} from "./connector";
import { signal, signalFn } from "./signal";

Expand Down Expand Up @@ -115,3 +116,21 @@ describe("clearConnectors", () => {
expect(s2).toBeFalsy();
});
});

describe("tap", () => {
it("applies tapFn with curr, prev from the tapped signal", () => {
let s = signal("foo");
connector("conn", () => s.value());
let pairs = [];
tap("conn", (curr, prev) => {
pairs.push(`${curr}-${prev}`);
});
s.reset("bar");
s.reset("baz");
s.reset("goo");
expect(pairs.length).toBe(3);
expect(pairs[0]).toBe("bar-foo");
expect(pairs[1]).toBe("baz-bar");
expect(pairs[2]).toBe("goo-baz");
});
});