liveBook · Manning

Combinator

As explained in Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond

A higher-order function or construct that builds a new operation by composing or transforming existing ones.

A clock stream may emit the same displayed time many times. A combinator transforms an observable into a new observable—for example, formatting dates or removing repeated values—without changing the original stream. section 33.2

currentTime$.map(data => `${date.getHours()}:${date.getMinutes()}`).distinct();

Map each date to a time string, then use distinct to suppress repeated strings. section 33.2

A custom combinator takes an observable and a function, subscribes to the existing stream, and returns a new observable. It can forward only values that pass a test. A complete version would also forward errors and completion. section 33.3 section 33.4

function filter (obs$, fn) {                               1
  return new Observable(observer => obs$.subscribe({       2
    next(val) {
      if (fn(val)) observer.next(val);                     3
    }
  }));
}
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":59},{\"line\":0,\"ch\":60}],[{\"line\":1,\"ch\":59},{\"line\":1,\"ch\":60}],[{\"line\":3,\"ch\":59},{\"line\":3,\"ch\":60}]]"}
!@%STYLE%@!

This filter combinator subscribes to an existing observable and forwards a value only when the supplied function accepts it. section 33.3

Filter a number stream

Applying the filter combinator to 1, 2, 3, 4, and 5 with an odd-number test produces a new stream containing 1, 3, and 5. section 33.3

How Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond covers it

How deep it goes
Defines combinators through subscription and new-observable creation, then walks through filtering; error and completion forwarding are deferred.
Examples
Uses a clock stream formatted into distinct time strings and a number stream filtered to odd values.
What it assumes
Introduces observable creation and subscription before composing streams, without stating other prerequisites.
What you can do after
Build it from scratch by subscribing to an existing observable and forwarding transformed or selected values through a new observable.
How it connects
Connects combinators to observables, subscriptions, map, filter, and stream composition.

Also explained in

Compare how 4 books explain combinator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond. The section links point to the parts of the book it draws on.