Functional Reactive Bindings, Part 2: The Combinators
This is the second of four parts on how Functional Reactive Bindings works, and how to make such a thing. Part 1 covered the language and its syntax tree. This part is about what each node of that tree becomes: an observer. Part 3 turns observers around into bindings, and part 4 is what I would do over.
The code is FRB at
dcad2e1,
most of it in
observers.js,
and every printed result came from running the example there.
The contract #
Every observer in FRB is a function of this shape:
function observe(emit, scope) {
// ...arrange to call emit with the value, now and whenever it changes...
return cancel;
}
It calls emit with the current value right away, then again each time the
value changes, until someone calls the cancel function it returned.
The part that makes everything compose is that emit returns something too.
If emit sets up observers of its own, for whatever it needs to do with the
value, it returns their canceler.
The observer keeps that canceler, calls it before emitting the next value,
and calls it when it is canceled itself.
So the observers for a value never outlive the value.
That is the design pattern that shall not be named, the one I described in the talk: a function that takes a callback, where the callback returns something of the same kind the function does. Here, both return cancelers.
The simplest observers ignore change altogether.
function makeLiteralObserver(literal) {
return function observeLiteral(emit) {
return emit(literal);
};
}
function observeValue(emit, scope) {
return emit(scope.value);
}
They emit once, and the canceler they return is whatever emit returned,
because they have nothing of their own to cancel.
Underneath: change events #
Observers need something to observe. FRB gets it from Collections version 1, which teaches plain objects and arrays to report their changes. There are three kinds.
- Property changes. To observe a property of an object, Collections
replaces the property with a getter and setter
(
listen/property-changes.js). The setter does nothing if the value is the same, and otherwise dispatches a “will change” event, stores the value, and dispatches a change event. It calls through to an existing getter and setter if there was one, and it keeps the old descriptor so that it could put it back when no one is listening, though version 1 never got around to doing that. - Range changes. To observe an array, Collections swaps its prototype for
one whose mutation methods dispatch changes
(
listen/array-changes.js), or, where__proto__is not supported, defines those methods on the array itself. Every mutation funnels intoswap(start, length, plus), which reports a range change:plus, the values added,minus, the values removed, and theindexwhere it happened. An array does not know aboutarray[3] = x, so you writearray.set(3, x). - Map changes. Maps, and arrays too, report a key and its new value, or
undefinedfor a deletion.
A range change is all an observer needs to update a derived array, and it is what makes FRB incremental.
FRB wraps a range change listener in one more convention.
function observeRangeChange(collection, emit, scope) {
// ...
function rangeChange(plus, minus, index) {
if (cancel) cancel();
cancel = emit(plus, minus, index);
}
rangeChange(collection.toArray(), [], 0);
var cancelRangeChange = collection.addRangeChangeListener(
rangeChange,
null,
scope.beforeChange
);
// ...
}
The current content arrives as the first range change, everything added at index 0. So every array combinator below has one code path for “here is the collection” and “here is what changed”, and never a separate one for initialization.
The compile step #
compile-observer.js
walks the syntax tree from the bottom up.
Leaves become the simple observers above.
Every other node looks up a maker by its type, in a table, and calls it
with the observers it compiled for the node’s arguments.
var argObservers = syntax.args.map(this.compile, this);
return compilers[syntax.type].apply(null, argObservers);
compilers: {
property: Observers.makePropertyObserver,
get: Observers.makeGetObserver,
"if": Observers.makeConditionalObserver,
not: Observers.makeNotObserver,
and: Observers.makeAndObserver,
or: Observers.makeOrObserver,
mapBlock: Observers.makeMapBlockObserver,
filterBlock: Observers.makeFilterBlockObserver,
sortedBlock: Observers.makeSortedBlockObserver,
reversed: Observers.makeReversedObserver,
flatten: Observers.makeFlattenObserver,
view: Observers.makeViewObserver,
sum: Observers.makeSumObserver,
has: Observers.makeHasObserver,
// ...and thirty-six more
}
The arithmetic and comparison operators fill in the rest of the table from
operators.js.
For a name the table does not know, the compiler makes a generic method
observer and remembers it.
The result of compiling is a tree of closures with the same shape as the
syntax tree.
Nothing is parsed or looked up again while it runs.
Calling the root with an emit and a scope sets the whole tree observing.
Properties #
The property observer is the heart of FRB.
function observeProperty(object, key, emit, scope) {
if (object == null) return emit();
var cancel;
function propertyChange(value, key, object) {
if (cancel) cancel();
cancel = emit(value, key, object);
}
PropertyChanges.addOwnPropertyChangeListener(
object,
key,
propertyChange,
scope.beforeChange
);
propertyChange(object[key], key, object);
return function cancelPropertyObserver() {
if (cancel) cancel();
PropertyChanges.removeOwnPropertyChangeListener(
object,
key,
propertyChange,
scope.beforeChange
);
};
}
function makePropertyObserver(observeObject, observeKey) {
return function observeProperty(emit, scope) {
return observeKey(function replaceKey(key) {
if (typeof key !== "string" && typeof key !== "number") return emit();
return observeObject(function replaceObject(object) {
if (object == null) return emit();
if (object.observeProperty) {
return object.observeProperty(key, emit, scope);
} else {
return _observeProperty(object, key, emit, scope);
}
}, scope);
}, scope);
};
}
The maker observes the key, and for each key observes the object, and for
each object observes the property.
Each layer is an emit that returns the canceler of the layer inside it.
So for foo.bar, replacing foo cancels the observer of the old foo.bar
before it observes the new one.
var object = {foo: {bar: 10}};
var cancel = observe(object, "foo.bar", function (bar) {
console.log("foo.bar =", bar);
});
object.foo.bar = 20;
var oldFoo = object.foo;
object.foo = {bar: 30};
oldFoo.bar = 40;
cancel();
object.foo.bar = 50;
foo.bar = 10
foo.bar = 20
foo.bar = 30
The old foo says nothing when it changes, and after cancel() nothing
does.
The observers rearrange themselves as the object graph changes, and one call
takes down the whole tree.
Two more things are worth taking from this code.
An object can answer for itself, with an observeProperty method, which is
how a component or a proxy could make a computed property observable.
And an undefined object or key emits undefined instead of throwing, so a
path that is not there yet waits until it is.
What it costs: one listener for each live link of the path. A change re-observes only the part of the path after it.
get is the same for keyed collections: map.get(key) observes the key,
then the collection, then listens for map changes and emits when one is for
its key.
Every map change on the collection reaches the listener, which compares
keys, so it costs a comparison per change to that map.
Operators #
The arithmetic, comparison and string operators share one maker.
function makeOperatorObserverMaker(operator) {
return function makeOperatorObserver(/*...observers*/) {
// ...collect the arguments into observers...
var observeOperands = makeObserversObserver(observers);
var observeOperandChanges = makeRangeContentObserver(observeOperands);
return function observeOperator(emit, scope) {
return observeOperandChanges(function (operands) {
if (!operands.every(Operators.defined)) return emit();
return emit(operator.apply(void 0, operands));
}, scope);
};
};
}
It observes all of the operands into one array, whose slots it updates with
set, observes that array’s content, and applies the operator to the whole
array whenever any slot changes.
If any operand is null or undefined, it emits undefined.
x + y undefined (y is not there yet)
x + y 3 after y = 2
x + y 12 after x = 10
Equality is an operator too, and it is shallow.
a == b compares with Object.equals, which looks inside arrays, but it
only observes a and b, not their content.
a == b true a = [1, 2], b = [1, 2]
nothing, after b.push(3)
a == b false after b = [1, 2, 3]
What it costs: one operator application per change to any operand.
Not every operator fits that mold.
! must turn undefined into true, so it has its own maker.
And &&, ||, ?: and ?? short-circuit, so they cannot observe all of
their operands at once.
function makeAndObserver(observeLeft, observeRight) {
return function observeAnd(emit, scope) {
return observeLeft(function replaceLeft(left) {
if (!left) {
return emit(left);
} else {
return observeRight(emit, scope);
}
}, scope);
};
}
The right side is observed only while the left is true.
When the left becomes false, the canceler that emit returned takes down
the observer of the right side, and the right side stops costing anything.
The conditional is the same with three operands: it observes the condition,
then only the branch the condition chose.
Observers that branch this way are what make FRB lazy, and they come for free
from the contract.
Many combinators wrap their emit in makeUniq, which drops a value equal
to the one before it, so that an and that stays false does not wake
everything downstream.
Arrays that do not get replaced #
Before the array combinators, one rule they all follow. An observer of an array emits one output array, once, and from then on only changes its content. Even when the input array is replaced outright, the output array stays the same object, and gets a range change that swaps its old content for the new.
That rule is in a decorator, makeNonReplacing.
function makeNonReplacing(wrapped) {
return function makeNonReplacingObserver() {
var observe = wrapped.apply(this, arguments);
return function observeArrayWithoutReplacing(emit, scope) {
var output = [];
var cancelObserver = observe(function (input) {
function rangeChange(plus, minus, index) {
output.swap(index, minus.length, plus);
}
if (!input || !input.addRangeChangeListener) {
output.clear();
} else {
// equivalent to: output.swap(0, output.length, input);
merge(output, input);
input.addRangeChangeListener(rangeChange, null, scope.beforeChange);
return function cancelRangeChange() {
input.removeRangeChangeListener(rangeChange, null, scope.beforeChange);
};
}
}, scope);
var cancel = emit(output);
return function cancelNonReplacingObserver() {
if (cancelObserver) cancelObserver();
if (cancel) cancel();
};
};
};
}
The wrapped observer may replace its own output whenever its input is
replaced.
The decorator mirrors whichever array it currently has into a single output,
with merge, which finds the shortest run of insertions and deletions from
the old content to the new (an adaptation of the longest common subsequence
algorithm in Cormen and company’s Introduction to Algorithms) rather than
swapping everything.
This matters because of what is downstream.
Whoever holds the output, a sum, another map, or a repetition drawing
rows in a document, keeps listening to the same array forever, and only ever
sees small changes.
Map #
items.map{expression} observes the input’s range changes, and for each
value added, compiles nothing (that was done once) but calls the block’s
observer in a nested scope whose value is that element.
function rangeChange(plus, minus, index) {
swap(indexRefs, index, minus.length, plus.map(function (value, offset) {
return {index: index + offset};
}));
update(index + plus.length);
// ...cancel the observers of the values removed...
swap(cancelers, index, minus.length, plus.map(function (value, offset) {
var indexRef = indexRefs[index + offset];
return observeRelation(function replaceRelationOutput(value) {
if (initialized) {
output.set(indexRef.index, value);
} else {
initial[offset] = value;
}
}, scope.nest(value));
}));
initialized = true;
output.swap(index, minus.length, initial);
}
It keeps three arrays in step with the input: the output, the cancelers of
each element’s observer, and an index reference for each element, a little
object holding its current index.
Each element’s observer writes through its index reference, not a captured
index, so when an insertion shifts everything after it, update renumbers
the references and the observers keep writing to the right slots.
The block’s values for a whole range change are gathered first and spliced in
with one swap, so a splice of a hundred values is one range change out, not
a hundred.
var source = {items: [1, 2, 3]};
var target = {};
bind(target, "doubled", {"<-": "items.map{* 2}", source: source});
var doubled = target.doubled;
source.items.push(4);
source.items.splice(0, 1);
source.items = [7, 8];
target.doubled === doubled; // true
doubled range change: plus [8] minus [] at 3
doubled range change: plus [] minus [2] at 0
doubled range change: plus [14,16] minus [4,6,8] at 0
({* 2} is {this * 2}: the empty expression is the value.)
When the block’s value for one element changes, as when one row’s quantity
changes in rows.map{price * quantity}, the map sets one slot of its
output, which is a range change of one value at that index.
What it costs: for a range change, one block observer made for each value added and one canceled for each removed, and a walk to renumber the index references after the change, which is linear in the distance to the end of the array.
Filter #
filter is built on map.
It maps the input to its predicates, and observes that array of booleans.
It keeps a running count, cumulativeLengths, of how many values pass
before each index.
That converts a change at an index of the input into a change at an index of
the output: a range change of predicates at index i becomes a swap at
cumulativeLengths[i] in the output, removing the values that used to pass
and adding the ones that pass now.
If those are the same, it says nothing.
numbers.filter{!(%2)} [2,4,6]
after push(8) evens range change: plus [8] minus [] at 3
after push(9) (nothing)
after splice(1, 1) evens range change: plus [] minus [2] at 0
Because the predicates are live, a value that starts to pass is spliced in where it belongs.
list.filter{ok}.map{name} ["A","C"]
after list[1].ok = true names range change: plus ["B"] minus [] at 1
What it costs: what the map of predicates costs, plus recomputing the running counts from the change to the end.
some and every are filters with a length.
collection.some{p} is whether collection.filter{p}.length is not zero,
and collection.every{p} is whether collection.filter{!p}.length is zero.
That is literally how they are written.
function makeEveryBlockObserver(observeCollection, observePredicate) {
var observeNotPredicate = makeConverterObserver(observePredicate, Operators.not);
var observeFilter = makeFilterBlockObserver(observeCollection, observeNotPredicate);
var observeLength = makePropertyObserver(observeFilter, observeLengthLiteral);
return makeConverterObserver(observeLength, Operators.not);
}
Sorted #
people.sorted{age} is a Schwartzian transform, decorate, sort,
undecorate, done incrementally.
It maps each value to an entry, [value, age], keeps the entries in a
SortedArray from Collections, and maps the sorted entries back to their
values.
A range change of entries deletes the entries removed from the sorted array
and adds the entries added, each by binary search.
When one person’s age changes, their entry is replaced, which comes out as two range changes: one removal and one insertion.
people.sorted{age}.map{name} ["Bo","Ann","Cy"]
after people[0].age = 50 byAge range change: plus [] minus ["Ann"] at 1
byAge range change: plus ["Ann"] minus [] at 2
What it costs: a binary search for each value added or removed, plus the splice to put it there.
sortedSet{key} is the same idea emitting a SortedSet instead of an
array, and keeping only the last of the values with equal keys, by way of
group, below.
Reversed #
function makeReplacingReversedObserver(observeArray) {
return function observeReversed(emit, scope) {
return observeArray(function (input) {
if (!input) return emit();
var output = [];
function rangeChange(plus, minus, index) {
var reflected = output.length - index - minus.length;
output.swap(reflected, minus.length, plus.reversed());
}
var cancelRangeChange = observeRangeChange(input, rangeChange, scope);
var cancel = emit(output);
return function cancelReversedObserver() {
if (cancel) cancel();
cancelRangeChange();
};
}, scope);
};
}
That is the whole combinator, and a model for the rest.
A change at index that removes minus.length values lands, reflected, at
length - index - minus.length in the output, with the values added in
reverse.
a.reversed() [3,2,1]
after a.push(4) r range change: plus [4] minus [] at 0
after a.splice(1,1) r range change: plus [] minus [2] at 2
What it costs: the size of the change.
Flatten and concat #
groups.flatten() observes the outer array, and an inner range change
observer for each inner array.
Like filter, it keeps a running total, here of the lengths of the inner
arrays, to translate an index within an inner array to an index in the
output, and like map, it keeps index references for the inner arrays so
their observers can find their own offsets after the outer array shifts.
groups.flatten() [1,2,3,4,5] groups = [[1,2],[3],[4,5]]
after groups[1].push(3.5) flat range change: plus [3.5] minus [] at 3
after groups.splice(0,1) flat range change: plus [] minus [1,2] at 0
a.concat(b, c) is the flatten of the tuple [a, b, c], and is written that
way.
What it costs: the size of the change, plus updating the running totals after it.
Sum, average and other aggregates #
Sums and averages are kept by a utility that sets up some state for each input array and folds each range change into it.
function makeCollectionObserverMaker(setup) {
return function (observeCollection) {
return function (emit, scope) {
emit = makeUniq(emit);
return observeCollection(function (collection) {
if (!collection) return emit();
var rangeChange = setup(collection, emit);
return observeRangeChange(collection, function (plus, minus, index) {
return emit(rangeChange(plus, minus, index));
}, scope);
}, scope);
};
};
}
exports.makeSumObserver = makeCollectionObserverMaker(function setup() {
var sum = 0;
return function rangeChange(plus, minus, index) {
plus = plus.filter(isNumber);
minus = minus.filter(isNumber);
sum += plus.sum() - minus.sum();
return sum;
};
});
The sum subtracts what was removed and adds what was added. The average keeps a count beside it. Values that are not numbers are left out of both.
n.sum() 6 n.average() 2
after push(4) 10 2.5
after splice(0, 2, 10) 17 5.666666666666667
min and max keep entries of value and key in a Heap from Collections,
and listen for map changes on the heap: when the entry at index 0 changes,
the minimum or maximum changed.
last() watches range changes, keeps the length, and ignores changes that
cannot reach the last slot.
only() emits the single value of a collection with exactly one, and
undefined otherwise.
one() emits any value at all, whichever the collection can find fastest.
xs.min{v}.v 1 xs.last().v 2 xs = [{v:3},{v:1},{v:2}]
after push({v:0}) min 0, last 0
after push({v:9}) max 9, last 9
xs.only() undefined, then "one" after a push, then undefined after another
What it costs: for sums and averages, the size of the change.
For min and max, a heap insertion or deletion for each value.
join and split are not incremental at all: join joins the whole array
again on every change.
Has #
collection.has(value) observes the value and the collection, and on every
range change asks the collection again.
set.has(key) false set = [1, 2], key = 3
after push(3) true
after key = 9 false
The code says why it is not incremental:
// This could be done incrementally if there were
// guarantees of uniqueness, but if there are
// guarantees of uniqueness, the data structure can
// probably efficiently check
What it costs: one has for each change: linear for an array, constant for
a set.
Windows, enumerations and ranges #
all.view(start, length) is a sliding window, and the most intricate
combinator in the file.
It observes the input’s range changes, the start, and the length.
When the window moves by less than its length, it slides: it adds the values
coming into view at one end and removes the ones going out of view at the
other, instead of replacing the window.
Changes to the input before the window shift it; changes within it are
spliced in and the window trimmed or refilled to its length; changes after
it are ignored.
all.view(start, length) ["b","c","d"] start 1, length 3
after start = 2 window range change: plus ["e"] minus [] at 3
window range change: plus [] minus ["b"] at 0
after length = 4 window range change: plus ["f"] minus [] at 3
This is the combinator for a long list on a short screen: scroll by one row, and one row is drawn.
xs.enumerate() makes [index, value] pairs, updating the indexes of the
pairs after each change.
n.range() makes [0, 1, … n - 1], and grows or shrinks it with one range
change however far n moves.
n.range() [0,1,2]
after n = 5 r range change: plus [3,4] minus [] at 3
after n = 2 r range change: plus [] minus [2,3,4] at 2
Groups, keys, values and entries #
words.group{.0} groups values by a key, here the first letter.
It maps each value to [value, key], and keeps a Map from each key to its
class, a collection of the same type as the input, made with
constructClone.
It adds a class when its first member arrives and deletes it when its last
member leaves.
groupMap emits the map itself; group emits its entries, by way of the
entries observer.
words.group{.0} [["a",["apple","avocado"]],["b",["banana"]]]
after push("blueberry"), splice(0, 1)
[["a",["avocado"]],["b",["banana","blueberry"]]]
m.entries(), m.keys() and m.values() turn a map’s changes into an
array of [key, value] pairs in insertion order, and maps of it.
toMap() goes the other way, from an object, a map, or an array of entries.
What it costs: a map operation for each value.
Deleting an entry finds it in the entries array by indexOf, which is linear.
Strings and paths #
startsWith, endsWith and contains observe the needle, make a regular
expression of it when it changes, and test the haystack whenever it
changes.
data.path(expr) is the strangest combinator, and the most telling.
It observes expr as a string, parses and compiles it whenever it
changes, and observes the result against data.
The language can observe expressions written in itself.
data.path(expr) 1 expr = "a.b", data = {a: {b: 1}, c: 2}
after expr = "c" 2
after data.c = 3 3
Scope #
Blocks run in a nested scope, and scope.nest(value) makes one.
function Scope(value) {
this.parent = null;
this.value = value;
}
Scope.prototype.nest = function (value) {
var child = Object.create(this);
child.value = value;
child.parent = this;
return child;
};
A child inherits everything from its parent, the parameters, the document,
the components, by prototype, and has its own value and a link to its
parent.
^expression observes the expression in the parent scope, and
x.(expression) observes it in a child scope whose value is x.
items.map{this * ^factor} [3,6] items = [1, 2], factor = 3
after factor = 4 [4,8]
Names nobody defined #
The compiler’s table is open. For a function name it does not know, it makes a method observer, which observes the object and the arguments and then looks on the object for, in order:
- a method named
make+ the name +Observer, which it treats as an observer maker of its own, given the argument observers; - a method named
observe+ the name, which it treats as an observer; - a method of the name itself, which it calls with the arguments whenever the object or an argument changes.
name.toUpperCase() "FRB" name = "frb"
after name = "gutentag" "GUTENTAG"
The third makes any pure method usable in a binding.
The first two let a collection or a component bring its own incremental
observer for an operation FRB never heard of.
Properties and get have the same escape hatch, through observeProperty
and observeGet methods.
What it all costs #
| Combinator | Per change |
|---|---|
| property, get | re-observe the path after the change |
| operators | one application |
&& || ?: ?? |
observe only the operands that matter |
| map | one block observer per value added or removed, renumber to the end |
| filter, some, every | as map, plus running counts to the end |
| sorted | a binary search and splice per value |
| reversed, flatten, concat | the size of the change, plus running totals |
| sum, average | the size of the change |
| min, max | a heap operation per value |
| has | one has on the collection |
| view | the values entering and leaving the window |
| enumerate | renumber to the end |
| join, split | all of it |
The memory is what you would expect: an output array per array combinator, a canceler per element per block, and a listener per link.
Making one #
These are the rules I would give anyone building such a thing.
- Let the callback return a canceler. Every observer that depends on a value returns the canceler of what it set up for that value. Rearranging and tearing down the graph then takes no bookkeeping at all.
- Deliver the initial state as the first change. Then every combinator has one path, for changes.
- Emit arrays once. Replace content, never arrays, so that everything downstream can keep listening to the same object and see only small changes.
- Write through index references. An element’s observer should not capture its index; insertions move it.
- Keep running totals. Prefix sums translate indexes from input to output for filter and flatten.
- Build combinators from combinators.
someandeveryare filters,sortedis a map of entries,concatis a flatten,groupis a map of entries, andkeysis a map of entries. - Leave the table open. A type should be able to supply its own observer for any operation.
Next, binders, and how FRB meets the world.
Functional Reactive Bindings:
- The Language
- The Combinators
- Binders and Integration
- What I Would Do Over