Skip to content

Commit

Permalink
Merge dae014d into e477679
Browse files Browse the repository at this point in the history
  • Loading branch information
stwa committed Jun 19, 2020
2 parents e477679 + dae014d commit d3ca430
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/signal.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,18 @@
* @typedef Signal
*/

let defaultEquals = (a, b) => a === b;

/**
* Creates a new Signal.
*
* @param {*} state The initial state.
* @param {*} options The signals options.
* @returns {Signal} The created signal.
*/
export function signal(state) {
export function signal(state, options = {}) {
let outputs = [];
let { equals = defaultEquals } = options;

return {
value() {
Expand All @@ -43,7 +47,7 @@ export function signal(state) {
let prev = state;
state = next;

if (prev !== next) {
if (!equals(prev, next)) {
outputs.forEach(fn => fn(this, prev, next));
}
},
Expand Down Expand Up @@ -76,16 +80,18 @@ export function signal(state) {
/**
* Creates a new SignalFn.
*
* @param {function} fn The initial state
* @param {*} state The initial state
* @param {function} fn The compute function.
* @param {*} state The initial state.
* @param {*} options The signals options.
* @returns {SignalFn} The created signal.
*/
export function signalFn(fn, state) {
export function signalFn(fn, state, options = {}) {
let inputs = [];
let outputs = [];
let disconnectors = new WeakMap();
let freeWatchers = [];
let dirty = true;
let { equals = defaultEquals } = options;

return {
value() {
Expand Down Expand Up @@ -121,7 +127,7 @@ export function signalFn(fn, state) {
let prev = state;
state = next;

if (prev !== next) {
if (!equals(prev, next)) {
outputs.forEach(fn => fn(this, prev, next));
}
},
Expand Down
21 changes: 21 additions & 0 deletions src/signal.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,15 @@ describe("signal", () => {
expect(outputs[0]).toBe(2);
expect(outputs[1]).toBe(1);
});
it("uses provided equals", () => {
let updates = 0;
let s = signal("1", { equals: (a, b) => a == b });
s.connect(() => updates++);
s.reset(1);
expect(updates).toBe(0);
s.reset(2);
expect(updates).toBe(1);
});
});

describe("signalFn", () => {
Expand Down Expand Up @@ -183,4 +192,16 @@ describe("signalFn", () => {
disconnect();
expect(freed).toBe(1);
});
it("uses provided equals", () => {
let updates = 0;
let s1 = signal("1");
let s2 = signalFn(() => s1.value(), s1.value(), {
equals: (a, b) => a == b,
});
s2.connect(() => updates++);
s1.reset(1);
expect(updates).toBe(0);
s1.reset(2);
expect(updates).toBe(1);
});
});

0 comments on commit d3ca430

Please sign in to comment.