Rudimentary support for comparators.

This commit is contained in:
Timothy Farrell 2017-11-02 00:19:57 -05:00
parent cb63685e7e
commit 1e10b27f69
3 changed files with 7 additions and 4 deletions

View File

@ -1,4 +1,4 @@
export function computed(fn, dependencies = []) {
export function computed(fn, dependencies = [], comparator = eq) {
const subscribers = new Set();
const dependents = new Set();
let isDirty = true;
@ -21,7 +21,7 @@ export function computed(fn, dependencies = []) {
if (isDirty) {
const newVal = fn.apply(null, dependencies.map(runParam));
isDirty = false;
if (newVal !== val) {
if (!comparator(newVal, val)) {
val = newVal;
subscribers.forEach(s => s(val));
}

View File

@ -1,8 +1,10 @@
export function observable(store) {
import { eq } from './util.js';
export function observable(store, comparator = eq) {
const subscribers = new Set();
const accessor = function _observable(newVal) {
if (newVal !== undefined && store !== newVal) {
if (newVal !== undefined && !comparator(store, newVal)) {
store = newVal;
subscribers.forEach(s => s(store));
}

View File

@ -0,0 +1 @@
export const eq = (a, b) => a === b;