UNPKG

115 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3 typeof define === 'function' && define.amd ? define(['exports'], factory) :
4 (factory((global.most = {})));
5}(this, (function (exports) { 'use strict';
6
7/** @license MIT License (c) copyright 2010-2016 original author or authors */
8/** @author Brian Cavalier */
9/** @author John Hann */
10
11function Stream (source) {
12 this.source = source;
13}
14
15Stream.prototype.run = function (sink, scheduler) {
16 return this.source.run(sink, scheduler)
17};
18
19/** @license MIT License (c) copyright 2010-2016 original author or authors */
20
21// Non-mutating array operations
22
23// cons :: a -> [a] -> [a]
24// a with x prepended
25function cons (x, a) {
26 var l = a.length;
27 var b = new Array(l + 1);
28 b[0] = x;
29 for (var i = 0; i < l; ++i) {
30 b[i + 1] = a[i];
31 }
32 return b
33}
34
35// append :: a -> [a] -> [a]
36// a with x appended
37function append (x, a) {
38 var l = a.length;
39 var b = new Array(l + 1);
40 for (var i = 0; i < l; ++i) {
41 b[i] = a[i];
42 }
43
44 b[l] = x;
45 return b
46}
47
48// drop :: Int -> [a] -> [a]
49// drop first n elements
50function drop (n, a) { // eslint-disable-line complexity
51 if (n < 0) {
52 throw new TypeError('n must be >= 0')
53 }
54
55 var l = a.length;
56 if (n === 0 || l === 0) {
57 return a
58 }
59
60 if (n >= l) {
61 return []
62 }
63
64 return unsafeDrop(n, a, l - n)
65}
66
67// unsafeDrop :: Int -> [a] -> Int -> [a]
68// Internal helper for drop
69function unsafeDrop (n, a, l) {
70 var b = new Array(l);
71 for (var i = 0; i < l; ++i) {
72 b[i] = a[n + i];
73 }
74 return b
75}
76
77// tail :: [a] -> [a]
78// drop head element
79function tail (a) {
80 return drop(1, a)
81}
82
83// copy :: [a] -> [a]
84// duplicate a (shallow duplication)
85function copy (a) {
86 var l = a.length;
87 var b = new Array(l);
88 for (var i = 0; i < l; ++i) {
89 b[i] = a[i];
90 }
91 return b
92}
93
94// map :: (a -> b) -> [a] -> [b]
95// transform each element with f
96function map (f, a) {
97 var l = a.length;
98 var b = new Array(l);
99 for (var i = 0; i < l; ++i) {
100 b[i] = f(a[i]);
101 }
102 return b
103}
104
105// reduce :: (a -> b -> a) -> a -> [b] -> a
106// accumulate via left-fold
107function reduce (f, z, a) {
108 var r = z;
109 for (var i = 0, l = a.length; i < l; ++i) {
110 r = f(r, a[i], i);
111 }
112 return r
113}
114
115// replace :: a -> Int -> [a]
116// replace element at index
117function replace (x, i, a) { // eslint-disable-line complexity
118 if (i < 0) {
119 throw new TypeError('i must be >= 0')
120 }
121
122 var l = a.length;
123 var b = new Array(l);
124 for (var j = 0; j < l; ++j) {
125 b[j] = i === j ? x : a[j];
126 }
127 return b
128}
129
130// remove :: Int -> [a] -> [a]
131// remove element at index
132function remove (i, a) { // eslint-disable-line complexity
133 if (i < 0) {
134 throw new TypeError('i must be >= 0')
135 }
136
137 var l = a.length;
138 if (l === 0 || i >= l) { // exit early if index beyond end of array
139 return a
140 }
141
142 if (l === 1) { // exit early if index in bounds and length === 1
143 return []
144 }
145
146 return unsafeRemove(i, a, l - 1)
147}
148
149// unsafeRemove :: Int -> [a] -> Int -> [a]
150// Internal helper to remove element at index
151function unsafeRemove (i, a, l) {
152 var b = new Array(l);
153 var j;
154 for (j = 0; j < i; ++j) {
155 b[j] = a[j];
156 }
157 for (j = i; j < l; ++j) {
158 b[j] = a[j + 1];
159 }
160
161 return b
162}
163
164// removeAll :: (a -> boolean) -> [a] -> [a]
165// remove all elements matching a predicate
166function removeAll (f, a) {
167 var l = a.length;
168 var b = new Array(l);
169 var j = 0;
170 for (var x = (void 0), i = 0; i < l; ++i) {
171 x = a[i];
172 if (!f(x)) {
173 b[j] = x;
174 ++j;
175 }
176 }
177
178 b.length = j;
179 return b
180}
181
182// findIndex :: a -> [a] -> Int
183// find index of x in a, from the left
184function findIndex (x, a) {
185 for (var i = 0, l = a.length; i < l; ++i) {
186 if (x === a[i]) {
187 return i
188 }
189 }
190 return -1
191}
192
193// isArrayLike :: * -> boolean
194// Return true iff x is array-like
195function isArrayLike (x) {
196 return x != null && typeof x.length === 'number' && typeof x !== 'function'
197}
198
199/** @license MIT License (c) copyright 2010-2016 original author or authors */
200
201// id :: a -> a
202var id = function (x) { return x; };
203
204// compose :: (b -> c) -> (a -> b) -> (a -> c)
205var compose = function (f, g) { return function (x) { return f(g(x)); }; };
206
207// apply :: (a -> b) -> a -> b
208var apply = function (f, x) { return f(x); };
209
210/** @license MIT License (c) copyright 2010-2016 original author or authors */
211/** @author Brian Cavalier */
212/** @author John Hann */
213
214/**
215 * Create a new Disposable which will dispose its underlying resource.
216 * @param {function} dispose function
217 * @param {*?} data any data to be passed to disposer function
218 * @constructor
219 */
220function Disposable (dispose, data) {
221 this._dispose = dispose;
222 this._data = data;
223}
224
225Disposable.prototype.dispose = function () {
226 return this._dispose(this._data)
227};
228
229/** @license MIT License (c) copyright 2010-2016 original author or authors */
230/** @author Brian Cavalier */
231/** @author John Hann */
232
233function SettableDisposable () {
234 this.disposable = void 0;
235 this.disposed = false;
236 this._resolve = void 0;
237
238 var self = this;
239 this.result = new Promise(function (resolve) {
240 self._resolve = resolve;
241 });
242}
243
244SettableDisposable.prototype.setDisposable = function (disposable) {
245 if (this.disposable !== void 0) {
246 throw new Error('setDisposable called more than once')
247 }
248
249 this.disposable = disposable;
250
251 if (this.disposed) {
252 this._resolve(disposable.dispose());
253 }
254};
255
256SettableDisposable.prototype.dispose = function () {
257 if (this.disposed) {
258 return this.result
259 }
260
261 this.disposed = true;
262
263 if (this.disposable !== void 0) {
264 this.result = this.disposable.dispose();
265 }
266
267 return this.result
268};
269
270/** @license MIT License (c) copyright 2010-2016 original author or authors */
271/** @author Brian Cavalier */
272/** @author John Hann */
273
274function isPromise (p) {
275 return p !== null && typeof p === 'object' && typeof p.then === 'function'
276}
277
278/** @license MIT License (c) copyright 2010-2016 original author or authors */
279/** @author Brian Cavalier */
280/** @author John Hann */
281var map$1 = map;
282var identity = id;
283
284/**
285 * Call disposable.dispose. If it returns a promise, catch promise
286 * error and forward it through the provided sink.
287 * @param {number} t time
288 * @param {{dispose: function}} disposable
289 * @param {{error: function}} sink
290 * @return {*} result of disposable.dispose
291 */
292function tryDispose (t, disposable, sink) {
293 var result = disposeSafely(disposable);
294 return isPromise(result)
295 ? result.catch(function (e) {
296 sink.error(t, e);
297 })
298 : result
299}
300
301/**
302 * Create a new Disposable which will dispose its underlying resource
303 * at most once.
304 * @param {function} dispose function
305 * @param {*?} data any data to be passed to disposer function
306 * @return {Disposable}
307 */
308function create (dispose, data) {
309 return once(new Disposable(dispose, data))
310}
311
312/**
313 * Create a noop disposable. Can be used to satisfy a Disposable
314 * requirement when no actual resource needs to be disposed.
315 * @return {Disposable|exports|module.exports}
316 */
317function empty$1 () {
318 return new Disposable(identity, void 0)
319}
320
321/**
322 * Create a disposable that will dispose all input disposables in parallel.
323 * @param {Array<Disposable>} disposables
324 * @return {Disposable}
325 */
326function all (disposables) {
327 return create(disposeAll, disposables)
328}
329
330function disposeAll (disposables) {
331 return Promise.all(map$1(disposeSafely, disposables))
332}
333
334function disposeSafely (disposable) {
335 try {
336 return disposable.dispose()
337 } catch (e) {
338 return Promise.reject(e)
339 }
340}
341
342/**
343 * Create a disposable from a promise for another disposable
344 * @param {Promise<Disposable>} disposablePromise
345 * @return {Disposable}
346 */
347
348
349/**
350 * Create a disposable proxy that allows its underlying disposable to
351 * be set later.
352 * @return {SettableDisposable}
353 */
354function settable () {
355 return new SettableDisposable()
356}
357
358/**
359 * Wrap an existing disposable (which may not already have been once()d)
360 * so that it will only dispose its underlying resource at most once.
361 * @param {{ dispose: function() }} disposable
362 * @return {Disposable} wrapped disposable
363 */
364function once (disposable) {
365 return new Disposable(disposeMemoized, memoized(disposable))
366}
367
368function disposeMemoized (memoized) {
369 if (!memoized.disposed) {
370 memoized.disposed = true;
371 memoized.value = disposeSafely(memoized.disposable);
372 memoized.disposable = void 0;
373 }
374
375 return memoized.value
376}
377
378function memoized (disposable) {
379 return { disposed: false, disposable: disposable, value: void 0 }
380}
381
382/** @license MIT License (c) copyright 2010-2016 original author or authors */
383/** @author Brian Cavalier */
384/** @author John Hann */
385
386function fatalError (e) {
387 setTimeout(function () {
388 throw e
389 }, 0);
390}
391
392/** @license MIT License (c) copyright 2010-2016 original author or authors */
393/** @author Brian Cavalier */
394/** @author John Hann */
395
396function PropagateTask (run, value, sink) {
397 this._run = run;
398 this.value = value;
399 this.sink = sink;
400 this.active = true;
401}
402
403PropagateTask.event = function (value, sink) {
404 return new PropagateTask(emit, value, sink)
405};
406
407PropagateTask.end = function (value, sink) {
408 return new PropagateTask(end, value, sink)
409};
410
411PropagateTask.error = function (value, sink) {
412 return new PropagateTask(error, value, sink)
413};
414
415PropagateTask.prototype.dispose = function () {
416 this.active = false;
417};
418
419PropagateTask.prototype.run = function (t) {
420 if (!this.active) {
421 return
422 }
423 this._run(t, this.value, this.sink);
424};
425
426PropagateTask.prototype.error = function (t, e) {
427 if (!this.active) {
428 return fatalError(e)
429 }
430 this.sink.error(t, e);
431};
432
433function error (t, e, sink) {
434 sink.error(t, e);
435}
436
437function emit (t, x, sink) {
438 sink.event(t, x);
439}
440
441function end (t, x, sink) {
442 sink.end(t, x);
443}
444
445/** @license MIT License (c) copyright 2010-2016 original author or authors */
446/** @author Brian Cavalier */
447/** @author John Hann */
448
449/**
450 * Stream containing only x
451 * @param {*} x
452 * @returns {Stream}
453 */
454function of (x) {
455 return new Stream(new Just(x))
456}
457
458function Just (x) {
459 this.value = x;
460}
461
462Just.prototype.run = function (sink, scheduler) {
463 return scheduler.asap(new PropagateTask(runJust, this.value, sink))
464};
465
466function runJust (t, x, sink) {
467 sink.event(t, x);
468 sink.end(t, void 0);
469}
470
471/**
472 * Stream containing no events and ends immediately
473 * @returns {Stream}
474 */
475function empty () {
476 return EMPTY
477}
478
479function EmptySource () {}
480
481EmptySource.prototype.run = function (sink, scheduler) {
482 var task = PropagateTask.end(void 0, sink);
483 scheduler.asap(task);
484
485 return create(disposeEmpty, task)
486};
487
488function disposeEmpty (task) {
489 return task.dispose()
490}
491
492var EMPTY = new Stream(new EmptySource());
493
494/**
495 * Stream containing no events and never ends
496 * @returns {Stream}
497 */
498function never () {
499 return NEVER
500}
501
502function NeverSource () {}
503
504NeverSource.prototype.run = function () {
505 return empty$1()
506};
507
508var NEVER = new Stream(new NeverSource());
509
510/** @license MIT License (c) copyright 2010-2016 original author or authors */
511/** @author Brian Cavalier */
512/** @author John Hann */
513
514function fromArray (a) {
515 return new Stream(new ArraySource(a))
516}
517
518function ArraySource (a) {
519 this.array = a;
520}
521
522ArraySource.prototype.run = function (sink, scheduler) {
523 return scheduler.asap(new PropagateTask(runProducer, this.array, sink))
524};
525
526function runProducer (t, array, sink) {
527 for (var i = 0, l = array.length; i < l && this.active; ++i) {
528 sink.event(t, array[i]);
529 }
530
531 this.active && sink.end(t);
532}
533
534/** @license MIT License (c) copyright 2010-2016 original author or authors */
535/** @author Brian Cavalier */
536/** @author John Hann */
537
538/*global Set, Symbol*/
539var iteratorSymbol;
540// Firefox ships a partial implementation using the name @@iterator.
541// https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14
542if (typeof Set === 'function' && typeof new Set()['@@iterator'] === 'function') {
543 iteratorSymbol = '@@iterator';
544} else {
545 iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator ||
546 '_es6shim_iterator_';
547}
548
549function isIterable (o) {
550 return typeof o[iteratorSymbol] === 'function'
551}
552
553function getIterator (o) {
554 return o[iteratorSymbol]()
555}
556
557/** @license MIT License (c) copyright 2010-2016 original author or authors */
558/** @author Brian Cavalier */
559/** @author John Hann */
560
561function fromIterable (iterable) {
562 return new Stream(new IterableSource(iterable))
563}
564
565function IterableSource (iterable) {
566 this.iterable = iterable;
567}
568
569IterableSource.prototype.run = function (sink, scheduler) {
570 return scheduler.asap(new PropagateTask(runProducer$1, getIterator(this.iterable), sink))
571};
572
573function runProducer$1 (t, iterator, sink) {
574 var r = iterator.next();
575
576 while (!r.done && this.active) {
577 sink.event(t, r.value);
578 r = iterator.next();
579 }
580
581 sink.end(t, r.value);
582}
583
584function symbolObservablePonyfill(root) {
585 var result;
586 var Symbol = root.Symbol;
587
588 if (typeof Symbol === 'function') {
589 if (Symbol.observable) {
590 result = Symbol.observable;
591 } else {
592 result = Symbol('observable');
593 Symbol.observable = result;
594 }
595 } else {
596 result = '@@observable';
597 }
598
599 return result;
600}
601
602/* global window */
603var root;
604
605if (typeof self !== 'undefined') {
606 root = self;
607} else if (typeof window !== 'undefined') {
608 root = window;
609} else if (typeof global !== 'undefined') {
610 root = global;
611} else if (typeof module !== 'undefined') {
612 root = module;
613} else {
614 root = Function('return this')();
615}
616
617var result = symbolObservablePonyfill(root);
618
619/** @license MIT License (c) copyright 2010-2016 original author or authors */
620/** @author Brian Cavalier */
621/** @author John Hann */
622
623function getObservable (o) { // eslint-disable-line complexity
624 var obs = null;
625 if (o) {
626 // Access foreign method only once
627 var method = o[result];
628 if (typeof method === 'function') {
629 obs = method.call(o);
630 if (!(obs && typeof obs.subscribe === 'function')) {
631 throw new TypeError('invalid observable ' + obs)
632 }
633 }
634 }
635
636 return obs
637}
638
639/** @license MIT License (c) copyright 2010-2016 original author or authors */
640/** @author Brian Cavalier */
641/** @author John Hann */
642
643function tryEvent (t, x, sink) {
644 try {
645 sink.event(t, x);
646 } catch (e) {
647 sink.error(t, e);
648 }
649}
650
651function tryEnd (t, x, sink) {
652 try {
653 sink.end(t, x);
654 } catch (e) {
655 sink.error(t, e);
656 }
657}
658
659/** @license MIT License (c) copyright 2010-2016 original author or authors */
660/** @author Brian Cavalier */
661/** @author John Hann */
662
663function fromObservable (observable) {
664 return new Stream(new ObservableSource(observable))
665}
666
667function ObservableSource (observable) {
668 this.observable = observable;
669}
670
671ObservableSource.prototype.run = function (sink, scheduler) {
672 var sub = this.observable.subscribe(new SubscriberSink(sink, scheduler));
673 if (typeof sub === 'function') {
674 return create(sub)
675 } else if (sub && typeof sub.unsubscribe === 'function') {
676 return create(unsubscribe, sub)
677 }
678
679 throw new TypeError('Observable returned invalid subscription ' + String(sub))
680};
681
682function SubscriberSink (sink, scheduler) {
683 this.sink = sink;
684 this.scheduler = scheduler;
685}
686
687SubscriberSink.prototype.next = function (x) {
688 tryEvent(this.scheduler.now(), x, this.sink);
689};
690
691SubscriberSink.prototype.complete = function (x) {
692 tryEnd(this.scheduler.now(), x, this.sink);
693};
694
695SubscriberSink.prototype.error = function (e) {
696 this.sink.error(this.scheduler.now(), e);
697};
698
699function unsubscribe (subscription) {
700 return subscription.unsubscribe()
701}
702
703/** @license MIT License (c) copyright 2010-2016 original author or authors */
704/** @author Brian Cavalier */
705/** @author John Hann */
706
707function from (a) { // eslint-disable-line complexity
708 if (a instanceof Stream) {
709 return a
710 }
711
712 var observable = getObservable(a);
713 if (observable != null) {
714 return fromObservable(observable)
715 }
716
717 if (Array.isArray(a) || isArrayLike(a)) {
718 return fromArray(a)
719 }
720
721 if (isIterable(a)) {
722 return fromIterable(a)
723 }
724
725 throw new TypeError('from(x) must be observable, iterable, or array-like: ' + a)
726}
727
728/** @license MIT License (c) copyright 2010-2016 original author or authors */
729/** @author Brian Cavalier */
730/** @author John Hann */
731
732/**
733 * Create a stream that emits the current time periodically
734 * @param {Number} period periodicity of events in millis
735 * @param {*} deprecatedValue @deprecated value to emit each period
736 * @returns {Stream} new stream that emits the current time every period
737 */
738function periodic (period, deprecatedValue) {
739 return new Stream(new Periodic(period, deprecatedValue))
740}
741
742function Periodic (period, value) {
743 this.period = period;
744 this.value = value;
745}
746
747Periodic.prototype.run = function (sink, scheduler) {
748 return scheduler.periodic(this.period, PropagateTask.event(this.value, sink))
749};
750
751/** @license MIT License (c) copyright 2010-2016 original author or authors */
752/** @author Brian Cavalier */
753/** @author John Hann */
754
755function ScheduledTask (delay, period, task, scheduler) {
756 this.time = delay;
757 this.period = period;
758 this.task = task;
759 this.scheduler = scheduler;
760 this.active = true;
761}
762
763ScheduledTask.prototype.run = function () {
764 return this.task.run(this.time)
765};
766
767ScheduledTask.prototype.error = function (e) {
768 return this.task.error(this.time, e)
769};
770
771ScheduledTask.prototype.dispose = function () {
772 this.scheduler.cancel(this);
773 return this.task.dispose()
774};
775
776/** @license MIT License (c) copyright 2010-2016 original author or authors */
777/** @author Brian Cavalier */
778/** @author John Hann */
779
780function defer (task) {
781 return Promise.resolve(task).then(runTask)
782}
783
784function runTask (task) {
785 try {
786 return task.run()
787 } catch (e) {
788 return task.error(e)
789 }
790}
791
792/** @license MIT License (c) copyright 2010-2016 original author or authors */
793/** @author Brian Cavalier */
794/** @author John Hann */
795
796function Scheduler (timer, timeline) {
797 this.timer = timer;
798 this.timeline = timeline;
799
800 this._timer = null;
801 this._nextArrival = Infinity;
802
803 var self = this;
804 this._runReadyTasksBound = function () {
805 self._runReadyTasks(self.now());
806 };
807}
808
809Scheduler.prototype.now = function () {
810 return this.timer.now()
811};
812
813Scheduler.prototype.asap = function (task) {
814 return this.schedule(0, -1, task)
815};
816
817Scheduler.prototype.delay = function (delay, task) {
818 return this.schedule(delay, -1, task)
819};
820
821Scheduler.prototype.periodic = function (period, task) {
822 return this.schedule(0, period, task)
823};
824
825Scheduler.prototype.schedule = function (delay, period, task) {
826 var now = this.now();
827 var st = new ScheduledTask(now + Math.max(0, delay), period, task, this);
828
829 this.timeline.add(st);
830 this._scheduleNextRun(now);
831 return st
832};
833
834Scheduler.prototype.cancel = function (task) {
835 task.active = false;
836 if (this.timeline.remove(task)) {
837 this._reschedule();
838 }
839};
840
841Scheduler.prototype.cancelAll = function (f) {
842 this.timeline.removeAll(f);
843 this._reschedule();
844};
845
846Scheduler.prototype._reschedule = function () {
847 if (this.timeline.isEmpty()) {
848 this._unschedule();
849 } else {
850 this._scheduleNextRun(this.now());
851 }
852};
853
854Scheduler.prototype._unschedule = function () {
855 this.timer.clearTimer(this._timer);
856 this._timer = null;
857};
858
859Scheduler.prototype._scheduleNextRun = function (now) { // eslint-disable-line complexity
860 if (this.timeline.isEmpty()) {
861 return
862 }
863
864 var nextArrival = this.timeline.nextArrival();
865
866 if (this._timer === null) {
867 this._scheduleNextArrival(nextArrival, now);
868 } else if (nextArrival < this._nextArrival) {
869 this._unschedule();
870 this._scheduleNextArrival(nextArrival, now);
871 }
872};
873
874Scheduler.prototype._scheduleNextArrival = function (nextArrival, now) {
875 this._nextArrival = nextArrival;
876 var delay = Math.max(0, nextArrival - now);
877 this._timer = this.timer.setTimer(this._runReadyTasksBound, delay);
878};
879
880Scheduler.prototype._runReadyTasks = function (now) {
881 this._timer = null;
882 this.timeline.runTasks(now, runTask);
883 this._scheduleNextRun(this.now());
884};
885
886/** @license MIT License (c) copyright 2010-2016 original author or authors */
887/** @author Brian Cavalier */
888/** @author John Hann */
889
890/*global setTimeout, clearTimeout*/
891
892function ClockTimer () {}
893
894ClockTimer.prototype.now = Date.now;
895
896ClockTimer.prototype.setTimer = function (f, dt) {
897 return dt <= 0 ? runAsap(f) : setTimeout(f, dt)
898};
899
900ClockTimer.prototype.clearTimer = function (t) {
901 return t instanceof Asap ? t.cancel() : clearTimeout(t)
902};
903
904function Asap (f) {
905 this.f = f;
906 this.active = true;
907}
908
909Asap.prototype.run = function () {
910 return this.active && this.f()
911};
912
913Asap.prototype.error = function (e) {
914 throw e
915};
916
917Asap.prototype.cancel = function () {
918 this.active = false;
919};
920
921function runAsap (f) {
922 var task = new Asap(f);
923 defer(task);
924 return task
925}
926
927/** @license MIT License (c) copyright 2010-2016 original author or authors */
928/** @author Brian Cavalier */
929/** @author John Hann */
930
931function Timeline () {
932 this.tasks = [];
933}
934
935Timeline.prototype.nextArrival = function () {
936 return this.isEmpty() ? Infinity : this.tasks[0].time
937};
938
939Timeline.prototype.isEmpty = function () {
940 return this.tasks.length === 0
941};
942
943Timeline.prototype.add = function (st) {
944 insertByTime(st, this.tasks);
945};
946
947Timeline.prototype.remove = function (st) {
948 var i = binarySearch(st.time, this.tasks);
949
950 if (i >= 0 && i < this.tasks.length) {
951 var at = findIndex(st, this.tasks[i].events);
952 if (at >= 0) {
953 this.tasks[i].events.splice(at, 1);
954 return true
955 }
956 }
957
958 return false
959};
960
961Timeline.prototype.removeAll = function (f) {
962 var this$1 = this;
963
964 for (var i = 0, l = this.tasks.length; i < l; ++i) {
965 removeAllFrom(f, this$1.tasks[i]);
966 }
967};
968
969Timeline.prototype.runTasks = function (t, runTask) {
970 var this$1 = this;
971
972 var tasks = this.tasks;
973 var l = tasks.length;
974 var i = 0;
975
976 while (i < l && tasks[i].time <= t) {
977 ++i;
978 }
979
980 this.tasks = tasks.slice(i);
981
982 // Run all ready tasks
983 for (var j = 0; j < i; ++j) {
984 this$1.tasks = runTasks(runTask, tasks[j], this$1.tasks);
985 }
986};
987
988function runTasks (runTask, timeslot, tasks) { // eslint-disable-line complexity
989 var events = timeslot.events;
990 for (var i = 0; i < events.length; ++i) {
991 var task = events[i];
992
993 if (task.active) {
994 runTask(task);
995
996 // Reschedule periodic repeating tasks
997 // Check active again, since a task may have canceled itself
998 if (task.period >= 0 && task.active) {
999 task.time = task.time + task.period;
1000 insertByTime(task, tasks);
1001 }
1002 }
1003 }
1004
1005 return tasks
1006}
1007
1008function insertByTime (task, timeslots) { // eslint-disable-line complexity
1009 var l = timeslots.length;
1010
1011 if (l === 0) {
1012 timeslots.push(newTimeslot(task.time, [task]));
1013 return
1014 }
1015
1016 var i = binarySearch(task.time, timeslots);
1017
1018 if (i >= l) {
1019 timeslots.push(newTimeslot(task.time, [task]));
1020 } else if (task.time === timeslots[i].time) {
1021 timeslots[i].events.push(task);
1022 } else {
1023 timeslots.splice(i, 0, newTimeslot(task.time, [task]));
1024 }
1025}
1026
1027function removeAllFrom (f, timeslot) {
1028 timeslot.events = removeAll(f, timeslot.events);
1029}
1030
1031function binarySearch (t, sortedArray) { // eslint-disable-line complexity
1032 var lo = 0;
1033 var hi = sortedArray.length;
1034 var mid, y;
1035
1036 while (lo < hi) {
1037 mid = Math.floor((lo + hi) / 2);
1038 y = sortedArray[mid];
1039
1040 if (t === y.time) {
1041 return mid
1042 } else if (t < y.time) {
1043 hi = mid;
1044 } else {
1045 lo = mid + 1;
1046 }
1047 }
1048 return hi
1049}
1050
1051function newTimeslot (t, events) {
1052 return { time: t, events: events }
1053}
1054
1055/** @license MIT License (c) copyright 2010-2016 original author or authors */
1056/** @author Brian Cavalier */
1057/** @author John Hann */
1058
1059var defaultScheduler = new Scheduler(new ClockTimer(), new Timeline());
1060
1061/** @license MIT License (c) copyright 2010-2016 original author or authors */
1062/** @author Brian Cavalier */
1063/** @author John Hann */
1064
1065function subscribe (subscriber, stream) {
1066 if (Object(subscriber) !== subscriber) {
1067 throw new TypeError('subscriber must be an object')
1068 }
1069
1070 var disposable = settable();
1071 var observer = new SubscribeObserver(fatalError, subscriber, disposable);
1072
1073 disposable.setDisposable(stream.source.run(observer, defaultScheduler));
1074
1075 return new Subscription(disposable)
1076}
1077
1078function SubscribeObserver (fatalError$$1, subscriber, disposable) {
1079 this.fatalError = fatalError$$1;
1080 this.subscriber = subscriber;
1081 this.disposable = disposable;
1082}
1083
1084SubscribeObserver.prototype.event = function (t, x) {
1085 if (!this.disposable.disposed && typeof this.subscriber.next === 'function') {
1086 this.subscriber.next(x);
1087 }
1088};
1089
1090SubscribeObserver.prototype.end = function (t, x) {
1091 if (!this.disposable.disposed) {
1092 var s = this.subscriber;
1093 var fatalError$$1 = this.fatalError;
1094 Promise.resolve(this.disposable.dispose()).then(function () {
1095 if (typeof s.complete === 'function') {
1096 s.complete(x);
1097 }
1098 }).catch(function (e) {
1099 throwError(e, s, fatalError$$1);
1100 });
1101 }
1102};
1103
1104SubscribeObserver.prototype.error = function (t, e) {
1105 var s = this.subscriber;
1106 var fatalError$$1 = this.fatalError;
1107 Promise.resolve(this.disposable.dispose()).then(function () {
1108 throwError(e, s, fatalError$$1);
1109 });
1110};
1111
1112function Subscription (disposable) {
1113 this.disposable = disposable;
1114}
1115
1116Subscription.prototype.unsubscribe = function () {
1117 this.disposable.dispose();
1118};
1119
1120function throwError (e1, subscriber, throwError) {
1121 if (typeof subscriber.error === 'function') {
1122 try {
1123 subscriber.error(e1);
1124 } catch (e2) {
1125 throwError(e2);
1126 }
1127 } else {
1128 throwError(e1);
1129 }
1130}
1131
1132/** @license MIT License (c) copyright 2010-2017 original author or authors */
1133/** @author Brian Cavalier */
1134/** @author John Hann */
1135
1136function thru (f, stream) {
1137 return f(stream)
1138}
1139
1140/** @license MIT License (c) copyright 2010-2016 original author or authors */
1141/** @author Brian Cavalier */
1142/** @author John Hann */
1143
1144function EventTargetSource (event, source, capture) {
1145 this.event = event;
1146 this.source = source;
1147 this.capture = capture;
1148}
1149
1150EventTargetSource.prototype.run = function (sink, scheduler) {
1151 function addEvent (e) {
1152 tryEvent(scheduler.now(), e, sink);
1153 }
1154
1155 this.source.addEventListener(this.event, addEvent, this.capture);
1156
1157 return create(disposeEventTarget,
1158 { target: this, addEvent: addEvent })
1159};
1160
1161function disposeEventTarget (info) {
1162 var target = info.target;
1163 target.source.removeEventListener(target.event, info.addEvent, target.capture);
1164}
1165
1166/** @license MIT License (c) copyright 2010-2016 original author or authors */
1167/** @author Brian Cavalier */
1168/** @author John Hann */
1169
1170function DeferredSink (sink) {
1171 this.sink = sink;
1172 this.events = [];
1173 this.active = true;
1174}
1175
1176DeferredSink.prototype.event = function (t, x) {
1177 if (!this.active) {
1178 return
1179 }
1180
1181 if (this.events.length === 0) {
1182 defer(new PropagateAllTask(this.sink, t, this.events));
1183 }
1184
1185 this.events.push({ time: t, value: x });
1186};
1187
1188DeferredSink.prototype.end = function (t, x) {
1189 if (!this.active) {
1190 return
1191 }
1192
1193 this._end(new EndTask(t, x, this.sink));
1194};
1195
1196DeferredSink.prototype.error = function (t, e) {
1197 this._end(new ErrorTask(t, e, this.sink));
1198};
1199
1200DeferredSink.prototype._end = function (task) {
1201 this.active = false;
1202 defer(task);
1203};
1204
1205function PropagateAllTask (sink, time, events) {
1206 this.sink = sink;
1207 this.events = events;
1208 this.time = time;
1209}
1210
1211PropagateAllTask.prototype.run = function () {
1212 var this$1 = this;
1213
1214 var events = this.events;
1215 var sink = this.sink;
1216 var event;
1217
1218 for (var i = 0, l = events.length; i < l; ++i) {
1219 event = events[i];
1220 this$1.time = event.time;
1221 sink.event(event.time, event.value);
1222 }
1223
1224 events.length = 0;
1225};
1226
1227PropagateAllTask.prototype.error = function (e) {
1228 this.sink.error(this.time, e);
1229};
1230
1231function EndTask (t, x, sink) {
1232 this.time = t;
1233 this.value = x;
1234 this.sink = sink;
1235}
1236
1237EndTask.prototype.run = function () {
1238 this.sink.end(this.time, this.value);
1239};
1240
1241EndTask.prototype.error = function (e) {
1242 this.sink.error(this.time, e);
1243};
1244
1245function ErrorTask (t, e, sink) {
1246 this.time = t;
1247 this.value = e;
1248 this.sink = sink;
1249}
1250
1251ErrorTask.prototype.run = function () {
1252 this.sink.error(this.time, this.value);
1253};
1254
1255ErrorTask.prototype.error = function (e) {
1256 throw e
1257};
1258
1259/** @license MIT License (c) copyright 2010-2016 original author or authors */
1260/** @author Brian Cavalier */
1261/** @author John Hann */
1262
1263function EventEmitterSource (event, source) {
1264 this.event = event;
1265 this.source = source;
1266}
1267
1268EventEmitterSource.prototype.run = function (sink, scheduler) {
1269 // NOTE: Because EventEmitter allows events in the same call stack as
1270 // a listener is added, use a DeferredSink to buffer events
1271 // until the stack clears, then propagate. This maintains most.js's
1272 // invariant that no event will be delivered in the same call stack
1273 // as an observer begins observing.
1274 var dsink = new DeferredSink(sink);
1275
1276 function addEventVariadic (a) {
1277 var arguments$1 = arguments;
1278
1279 var l = arguments.length;
1280 if (l > 1) {
1281 var arr = new Array(l);
1282 for (var i = 0; i < l; ++i) {
1283 arr[i] = arguments$1[i];
1284 }
1285 tryEvent(scheduler.now(), arr, dsink);
1286 } else {
1287 tryEvent(scheduler.now(), a, dsink);
1288 }
1289 }
1290
1291 this.source.addListener(this.event, addEventVariadic);
1292
1293 return create(disposeEventEmitter, { target: this, addEvent: addEventVariadic })
1294};
1295
1296function disposeEventEmitter (info) {
1297 var target = info.target;
1298 target.source.removeListener(target.event, info.addEvent);
1299}
1300
1301/** @license MIT License (c) copyright 2010-2016 original author or authors */
1302/** @author Brian Cavalier */
1303/** @author John Hann */
1304
1305/**
1306 * Create a stream from an EventTarget, such as a DOM Node, or EventEmitter.
1307 * @param {String} event event type name, e.g. 'click'
1308 * @param {EventTarget|EventEmitter} source EventTarget or EventEmitter
1309 * @param {*?} capture for DOM events, whether to use
1310 * capturing--passed as 3rd parameter to addEventListener.
1311 * @returns {Stream} stream containing all events of the specified type
1312 * from the source.
1313 */
1314function fromEvent (event, source, capture) { // eslint-disable-line complexity
1315 var s;
1316
1317 if (typeof source.addEventListener === 'function' && typeof source.removeEventListener === 'function') {
1318 if (arguments.length < 3) {
1319 capture = false;
1320 }
1321
1322 s = new EventTargetSource(event, source, capture);
1323 } else if (typeof source.addListener === 'function' && typeof source.removeListener === 'function') {
1324 s = new EventEmitterSource(event, source);
1325 } else {
1326 throw new Error('source must support addEventListener/removeEventListener or addListener/removeListener')
1327 }
1328
1329 return new Stream(s)
1330}
1331
1332/** @license MIT License (c) copyright 2010-2016 original author or authors */
1333/** @author Brian Cavalier */
1334/** @author John Hann */
1335
1336function withDefaultScheduler (source) {
1337 return withScheduler(source, defaultScheduler)
1338}
1339
1340function withScheduler (source, scheduler) {
1341 return new Promise(function (resolve, reject) {
1342 runSource(source, scheduler, resolve, reject);
1343 })
1344}
1345
1346function runSource (source, scheduler, resolve, reject) {
1347 var disposable = settable();
1348 var observer = new Drain(resolve, reject, disposable);
1349
1350 disposable.setDisposable(source.run(observer, scheduler));
1351}
1352
1353function Drain (end, error, disposable) {
1354 this._end = end;
1355 this._error = error;
1356 this._disposable = disposable;
1357 this.active = true;
1358}
1359
1360Drain.prototype.event = function (t, x) {};
1361
1362Drain.prototype.end = function (t, x) {
1363 if (!this.active) {
1364 return
1365 }
1366 this.active = false;
1367 disposeThen(this._end, this._error, this._disposable, x);
1368};
1369
1370Drain.prototype.error = function (t, e) {
1371 this.active = false;
1372 disposeThen(this._error, this._error, this._disposable, e);
1373};
1374
1375function disposeThen (end, error, disposable, x) {
1376 Promise.resolve(disposable.dispose()).then(function () {
1377 end(x);
1378 }, error);
1379}
1380
1381/** @license MIT License (c) copyright 2010-2016 original author or authors */
1382/** @author Brian Cavalier */
1383/** @author John Hann */
1384
1385/**
1386 * A sink mixin that simply forwards event, end, and error to
1387 * another sink.
1388 * @param sink
1389 * @constructor
1390 */
1391function Pipe (sink) {
1392 this.sink = sink;
1393}
1394
1395Pipe.prototype.event = function (t, x) {
1396 return this.sink.event(t, x)
1397};
1398
1399Pipe.prototype.end = function (t, x) {
1400 return this.sink.end(t, x)
1401};
1402
1403Pipe.prototype.error = function (t, e) {
1404 return this.sink.error(t, e)
1405};
1406
1407/** @license MIT License (c) copyright 2010-2016 original author or authors */
1408/** @author Brian Cavalier */
1409/** @author John Hann */
1410
1411function Filter (p, source) {
1412 this.p = p;
1413 this.source = source;
1414}
1415
1416/**
1417 * Create a filtered source, fusing adjacent filter.filter if possible
1418 * @param {function(x:*):boolean} p filtering predicate
1419 * @param {{run:function}} source source to filter
1420 * @returns {Filter} filtered source
1421 */
1422Filter.create = function createFilter (p, source) {
1423 if (source instanceof Filter) {
1424 return new Filter(and(source.p, p), source.source)
1425 }
1426
1427 return new Filter(p, source)
1428};
1429
1430Filter.prototype.run = function (sink, scheduler) {
1431 return this.source.run(new FilterSink(this.p, sink), scheduler)
1432};
1433
1434function FilterSink (p, sink) {
1435 this.p = p;
1436 this.sink = sink;
1437}
1438
1439FilterSink.prototype.end = Pipe.prototype.end;
1440FilterSink.prototype.error = Pipe.prototype.error;
1441
1442FilterSink.prototype.event = function (t, x) {
1443 var p = this.p;
1444 p(x) && this.sink.event(t, x);
1445};
1446
1447function and (p, q) {
1448 return function (x) {
1449 return p(x) && q(x)
1450 }
1451}
1452
1453/** @license MIT License (c) copyright 2010-2016 original author or authors */
1454/** @author Brian Cavalier */
1455/** @author John Hann */
1456
1457function FilterMap (p, f, source) {
1458 this.p = p;
1459 this.f = f;
1460 this.source = source;
1461}
1462
1463FilterMap.prototype.run = function (sink, scheduler) {
1464 return this.source.run(new FilterMapSink(this.p, this.f, sink), scheduler)
1465};
1466
1467function FilterMapSink (p, f, sink) {
1468 this.p = p;
1469 this.f = f;
1470 this.sink = sink;
1471}
1472
1473FilterMapSink.prototype.event = function (t, x) {
1474 var f = this.f;
1475 var p = this.p;
1476 p(x) && this.sink.event(t, f(x));
1477};
1478
1479FilterMapSink.prototype.end = Pipe.prototype.end;
1480FilterMapSink.prototype.error = Pipe.prototype.error;
1481
1482/** @license MIT License (c) copyright 2010-2016 original author or authors */
1483/** @author Brian Cavalier */
1484/** @author John Hann */
1485
1486function Map (f, source) {
1487 this.f = f;
1488 this.source = source;
1489}
1490
1491/**
1492 * Create a mapped source, fusing adjacent map.map, filter.map,
1493 * and filter.map.map if possible
1494 * @param {function(*):*} f mapping function
1495 * @param {{run:function}} source source to map
1496 * @returns {Map|FilterMap} mapped source, possibly fused
1497 */
1498Map.create = function createMap (f, source) {
1499 if (source instanceof Map) {
1500 return new Map(compose(f, source.f), source.source)
1501 }
1502
1503 if (source instanceof Filter) {
1504 return new FilterMap(source.p, f, source.source)
1505 }
1506
1507 return new Map(f, source)
1508};
1509
1510Map.prototype.run = function (sink, scheduler) { // eslint-disable-line no-extend-native
1511 return this.source.run(new MapSink(this.f, sink), scheduler)
1512};
1513
1514function MapSink (f, sink) {
1515 this.f = f;
1516 this.sink = sink;
1517}
1518
1519MapSink.prototype.end = Pipe.prototype.end;
1520MapSink.prototype.error = Pipe.prototype.error;
1521
1522MapSink.prototype.event = function (t, x) {
1523 var f = this.f;
1524 this.sink.event(t, f(x));
1525};
1526
1527/** @license MIT License (c) copyright 2010-2016 original author or authors */
1528/** @author Brian Cavalier */
1529/** @author John Hann */
1530
1531/**
1532 * Transform each value in the stream by applying f to each
1533 * @param {function(*):*} f mapping function
1534 * @param {Stream} stream stream to map
1535 * @returns {Stream} stream containing items transformed by f
1536 */
1537function map$2 (f, stream) {
1538 return new Stream(Map.create(f, stream.source))
1539}
1540
1541/**
1542* Replace each value in the stream with x
1543* @param {*} x
1544* @param {Stream} stream
1545* @returns {Stream} stream containing items replaced with x
1546*/
1547function constant (x, stream) {
1548 return map$2(function () {
1549 return x
1550 }, stream)
1551}
1552
1553/**
1554* Perform a side effect for each item in the stream
1555* @param {function(x:*):*} f side effect to execute for each item. The
1556* return value will be discarded.
1557* @param {Stream} stream stream to tap
1558* @returns {Stream} new stream containing the same items as this stream
1559*/
1560function tap (f, stream) {
1561 return new Stream(new Tap(f, stream.source))
1562}
1563
1564function Tap (f, source) {
1565 this.source = source;
1566 this.f = f;
1567}
1568
1569Tap.prototype.run = function (sink, scheduler) {
1570 return this.source.run(new TapSink(this.f, sink), scheduler)
1571};
1572
1573function TapSink (f, sink) {
1574 this.sink = sink;
1575 this.f = f;
1576}
1577
1578TapSink.prototype.end = Pipe.prototype.end;
1579TapSink.prototype.error = Pipe.prototype.error;
1580
1581TapSink.prototype.event = function (t, x) {
1582 var f = this.f;
1583 f(x);
1584 this.sink.event(t, x);
1585};
1586
1587/** @license MIT License (c) copyright 2010-2016 original author or authors */
1588/** @author Brian Cavalier */
1589/** @author John Hann */
1590
1591/**
1592 * Observe all the event values in the stream in time order. The
1593 * provided function `f` will be called for each event value
1594 * @param {function(x:T):*} f function to call with each event value
1595 * @param {Stream<T>} stream stream to observe
1596 * @return {Promise} promise that fulfills after the stream ends without
1597 * an error, or rejects if the stream ends with an error.
1598 */
1599function observe (f, stream) {
1600 return drain(tap(f, stream))
1601}
1602
1603/**
1604 * "Run" a stream by creating demand and consuming all events
1605 * @param {Stream<T>} stream stream to drain
1606 * @return {Promise} promise that fulfills after the stream ends without
1607 * an error, or rejects if the stream ends with an error.
1608 */
1609function drain (stream) {
1610 return withDefaultScheduler(stream.source)
1611}
1612
1613/** @license MIT License (c) copyright 2010-2016 original author or authors */
1614/** @author Brian Cavalier */
1615/** @author John Hann */
1616
1617/**
1618 * Generalized feedback loop. Call a stepper function for each event. The stepper
1619 * will be called with 2 params: the current seed and the an event value. It must
1620 * return a new { seed, value } pair. The `seed` will be fed back into the next
1621 * invocation of stepper, and the `value` will be propagated as the event value.
1622 * @param {function(seed:*, value:*):{seed:*, value:*}} stepper loop step function
1623 * @param {*} seed initial seed value passed to first stepper call
1624 * @param {Stream} stream event stream
1625 * @returns {Stream} new stream whose values are the `value` field of the objects
1626 * returned by the stepper
1627 */
1628function loop (stepper, seed, stream) {
1629 return new Stream(new Loop(stepper, seed, stream.source))
1630}
1631
1632function Loop (stepper, seed, source) {
1633 this.step = stepper;
1634 this.seed = seed;
1635 this.source = source;
1636}
1637
1638Loop.prototype.run = function (sink, scheduler) {
1639 return this.source.run(new LoopSink(this.step, this.seed, sink), scheduler)
1640};
1641
1642function LoopSink (stepper, seed, sink) {
1643 this.step = stepper;
1644 this.seed = seed;
1645 this.sink = sink;
1646}
1647
1648LoopSink.prototype.error = Pipe.prototype.error;
1649
1650LoopSink.prototype.event = function (t, x) {
1651 var result = this.step(this.seed, x);
1652 this.seed = result.seed;
1653 this.sink.event(t, result.value);
1654};
1655
1656LoopSink.prototype.end = function (t) {
1657 this.sink.end(t, this.seed);
1658};
1659
1660/** @license MIT License (c) copyright 2010-2016 original author or authors */
1661/** @author Brian Cavalier */
1662/** @author John Hann */
1663
1664/**
1665 * Create a stream containing successive reduce results of applying f to
1666 * the previous reduce result and the current stream item.
1667 * @param {function(result:*, x:*):*} f reducer function
1668 * @param {*} initial initial value
1669 * @param {Stream} stream stream to scan
1670 * @returns {Stream} new stream containing successive reduce results
1671 */
1672function scan (f, initial, stream) {
1673 return new Stream(new Scan(f, initial, stream.source))
1674}
1675
1676function Scan (f, z, source) {
1677 this.source = source;
1678 this.f = f;
1679 this.value = z;
1680}
1681
1682Scan.prototype.run = function (sink, scheduler) {
1683 var d1 = scheduler.asap(PropagateTask.event(this.value, sink));
1684 var d2 = this.source.run(new ScanSink(this.f, this.value, sink), scheduler);
1685 return all([d1, d2])
1686};
1687
1688function ScanSink (f, z, sink) {
1689 this.f = f;
1690 this.value = z;
1691 this.sink = sink;
1692}
1693
1694ScanSink.prototype.event = function (t, x) {
1695 var f = this.f;
1696 this.value = f(this.value, x);
1697 this.sink.event(t, this.value);
1698};
1699
1700ScanSink.prototype.error = Pipe.prototype.error;
1701ScanSink.prototype.end = Pipe.prototype.end;
1702
1703/**
1704* Reduce a stream to produce a single result. Note that reducing an infinite
1705* stream will return a Promise that never fulfills, but that may reject if an error
1706* occurs.
1707* @param {function(result:*, x:*):*} f reducer function
1708* @param {*} initial initial value
1709* @param {Stream} stream to reduce
1710* @returns {Promise} promise for the file result of the reduce
1711*/
1712function reduce$1 (f, initial, stream) {
1713 return withDefaultScheduler(new Reduce(f, initial, stream.source))
1714}
1715
1716function Reduce (f, z, source) {
1717 this.source = source;
1718 this.f = f;
1719 this.value = z;
1720}
1721
1722Reduce.prototype.run = function (sink, scheduler) {
1723 return this.source.run(new ReduceSink(this.f, this.value, sink), scheduler)
1724};
1725
1726function ReduceSink (f, z, sink) {
1727 this.f = f;
1728 this.value = z;
1729 this.sink = sink;
1730}
1731
1732ReduceSink.prototype.event = function (t, x) {
1733 var f = this.f;
1734 this.value = f(this.value, x);
1735 this.sink.event(t, this.value);
1736};
1737
1738ReduceSink.prototype.error = Pipe.prototype.error;
1739
1740ReduceSink.prototype.end = function (t) {
1741 this.sink.end(t, this.value);
1742};
1743
1744/** @license MIT License (c) copyright 2010-2016 original author or authors */
1745/** @author Brian Cavalier */
1746/** @author John Hann */
1747
1748/**
1749 * Compute a stream by unfolding tuples of future values from a seed value
1750 * Event times may be controlled by returning a Promise from f
1751 * @param {function(seed:*):{value:*, seed:*, done:boolean}|Promise<{value:*, seed:*, done:boolean}>} f unfolding function accepts
1752 * a seed and returns a new tuple with a value, new seed, and boolean done flag.
1753 * If tuple.done is true, the stream will end.
1754 * @param {*} seed seed value
1755 * @returns {Stream} stream containing all value of all tuples produced by the
1756 * unfolding function.
1757 */
1758function unfold (f, seed) {
1759 return new Stream(new UnfoldSource(f, seed))
1760}
1761
1762function UnfoldSource (f, seed) {
1763 this.f = f;
1764 this.value = seed;
1765}
1766
1767UnfoldSource.prototype.run = function (sink, scheduler) {
1768 return new Unfold(this.f, this.value, sink, scheduler)
1769};
1770
1771function Unfold (f, x, sink, scheduler) {
1772 this.f = f;
1773 this.sink = sink;
1774 this.scheduler = scheduler;
1775 this.active = true;
1776
1777 var self = this;
1778 function err (e) {
1779 self.sink.error(self.scheduler.now(), e);
1780 }
1781
1782 function start (unfold) {
1783 return stepUnfold(unfold, x)
1784 }
1785
1786 Promise.resolve(this).then(start).catch(err);
1787}
1788
1789Unfold.prototype.dispose = function () {
1790 this.active = false;
1791};
1792
1793function stepUnfold (unfold, x) {
1794 var f = unfold.f;
1795 return Promise.resolve(f(x)).then(function (tuple) {
1796 return continueUnfold(unfold, tuple)
1797 })
1798}
1799
1800function continueUnfold (unfold, tuple) {
1801 if (tuple.done) {
1802 unfold.sink.end(unfold.scheduler.now(), tuple.value);
1803 return tuple.value
1804 }
1805
1806 unfold.sink.event(unfold.scheduler.now(), tuple.value);
1807
1808 if (!unfold.active) {
1809 return tuple.value
1810 }
1811 return stepUnfold(unfold, tuple.seed)
1812}
1813
1814/** @license MIT License (c) copyright 2010-2016 original author or authors */
1815/** @author Brian Cavalier */
1816/** @author John Hann */
1817
1818/**
1819 * Compute a stream by iteratively calling f to produce values
1820 * Event times may be controlled by returning a Promise from f
1821 * @param {function(x:*):*|Promise<*>} f
1822 * @param {*} x initial value
1823 * @returns {Stream}
1824 */
1825function iterate (f, x) {
1826 return new Stream(new IterateSource(f, x))
1827}
1828
1829function IterateSource (f, x) {
1830 this.f = f;
1831 this.value = x;
1832}
1833
1834IterateSource.prototype.run = function (sink, scheduler) {
1835 return new Iterate(this.f, this.value, sink, scheduler)
1836};
1837
1838function Iterate (f, initial, sink, scheduler) {
1839 this.f = f;
1840 this.sink = sink;
1841 this.scheduler = scheduler;
1842 this.active = true;
1843
1844 var x = initial;
1845
1846 var self = this;
1847 function err (e) {
1848 self.sink.error(self.scheduler.now(), e);
1849 }
1850
1851 function start (iterate) {
1852 return stepIterate(iterate, x)
1853 }
1854
1855 Promise.resolve(this).then(start).catch(err);
1856}
1857
1858Iterate.prototype.dispose = function () {
1859 this.active = false;
1860};
1861
1862function stepIterate (iterate, x) {
1863 iterate.sink.event(iterate.scheduler.now(), x);
1864
1865 if (!iterate.active) {
1866 return x
1867 }
1868
1869 var f = iterate.f;
1870 return Promise.resolve(f(x)).then(function (y) {
1871 return continueIterate(iterate, y)
1872 })
1873}
1874
1875function continueIterate (iterate, x) {
1876 return !iterate.active ? iterate.value : stepIterate(iterate, x)
1877}
1878
1879/** @license MIT License (c) copyright 2010-2014 original author or authors */
1880/** @author Brian Cavalier */
1881/** @author John Hann */
1882
1883/**
1884 * Compute a stream using an *async* generator, which yields promises
1885 * to control event times.
1886 * @param f
1887 * @returns {Stream}
1888 */
1889function generate (f /*, ...args */) {
1890 return new Stream(new GenerateSource(f, tail(arguments)))
1891}
1892
1893function GenerateSource (f, args) {
1894 this.f = f;
1895 this.args = args;
1896}
1897
1898GenerateSource.prototype.run = function (sink, scheduler) {
1899 return new Generate(this.f.apply(void 0, this.args), sink, scheduler)
1900};
1901
1902function Generate (iterator, sink, scheduler) {
1903 this.iterator = iterator;
1904 this.sink = sink;
1905 this.scheduler = scheduler;
1906 this.active = true;
1907
1908 var self = this;
1909 function err (e) {
1910 self.sink.error(self.scheduler.now(), e);
1911 }
1912
1913 Promise.resolve(this).then(next).catch(err);
1914}
1915
1916function next (generate, x) {
1917 return generate.active ? handle(generate, generate.iterator.next(x)) : x
1918}
1919
1920function handle (generate, result) {
1921 if (result.done) {
1922 return generate.sink.end(generate.scheduler.now(), result.value)
1923 }
1924
1925 return Promise.resolve(result.value).then(function (x) {
1926 return emit$1(generate, x)
1927 }, function (e) {
1928 return error$1(generate, e)
1929 })
1930}
1931
1932function emit$1 (generate, x) {
1933 generate.sink.event(generate.scheduler.now(), x);
1934 return next(generate, x)
1935}
1936
1937function error$1 (generate, e) {
1938 return handle(generate, generate.iterator.throw(e))
1939}
1940
1941Generate.prototype.dispose = function () {
1942 this.active = false;
1943};
1944
1945/** @license MIT License (c) copyright 2010-2016 original author or authors */
1946/** @author Brian Cavalier */
1947/** @author John Hann */
1948
1949function continueWith (f, stream) {
1950 return new Stream(new ContinueWith(f, stream.source))
1951}
1952
1953function ContinueWith (f, source) {
1954 this.f = f;
1955 this.source = source;
1956}
1957
1958ContinueWith.prototype.run = function (sink, scheduler) {
1959 return new ContinueWithSink(this.f, this.source, sink, scheduler)
1960};
1961
1962function ContinueWithSink (f, source, sink, scheduler) {
1963 this.f = f;
1964 this.sink = sink;
1965 this.scheduler = scheduler;
1966 this.active = true;
1967 this.disposable = once(source.run(this, scheduler));
1968}
1969
1970ContinueWithSink.prototype.error = Pipe.prototype.error;
1971
1972ContinueWithSink.prototype.event = function (t, x) {
1973 if (!this.active) {
1974 return
1975 }
1976 this.sink.event(t, x);
1977};
1978
1979ContinueWithSink.prototype.end = function (t, x) {
1980 if (!this.active) {
1981 return
1982 }
1983
1984 tryDispose(t, this.disposable, this.sink);
1985 this._startNext(t, x, this.sink);
1986};
1987
1988ContinueWithSink.prototype._startNext = function (t, x, sink) {
1989 try {
1990 this.disposable = this._continue(this.f, x, sink);
1991 } catch (e) {
1992 sink.error(t, e);
1993 }
1994};
1995
1996ContinueWithSink.prototype._continue = function (f, x, sink) {
1997 return f(x).source.run(sink, this.scheduler)
1998};
1999
2000ContinueWithSink.prototype.dispose = function () {
2001 this.active = false;
2002 return this.disposable.dispose()
2003};
2004
2005/** @license MIT License (c) copyright 2010-2016 original author or authors */
2006/** @author Brian Cavalier */
2007/** @author John Hann */
2008
2009/**
2010 * @param {*} x value to prepend
2011 * @param {Stream} stream
2012 * @returns {Stream} new stream with x prepended
2013 */
2014function cons$1 (x, stream) {
2015 return concat(of(x), stream)
2016}
2017
2018/**
2019* @param {Stream} left
2020* @param {Stream} right
2021* @returns {Stream} new stream containing all events in left followed by all
2022* events in right. This *timeshifts* right to the end of left.
2023*/
2024function concat (left, right) {
2025 return continueWith(function () {
2026 return right
2027 }, left)
2028}
2029
2030/** @license MIT License (c) copyright 2010-2016 original author or authors */
2031/** @author Brian Cavalier */
2032/** @author John Hann */
2033
2034function IndexSink (i, sink) {
2035 this.sink = sink;
2036 this.index = i;
2037 this.active = true;
2038 this.value = void 0;
2039}
2040
2041IndexSink.prototype.event = function (t, x) {
2042 if (!this.active) {
2043 return
2044 }
2045 this.value = x;
2046 this.sink.event(t, this);
2047};
2048
2049IndexSink.prototype.end = function (t, x) {
2050 if (!this.active) {
2051 return
2052 }
2053 this.active = false;
2054 this.sink.end(t, { index: this.index, value: x });
2055};
2056
2057IndexSink.prototype.error = Pipe.prototype.error;
2058
2059/** @license MIT License (c) copyright 2010-2016 original author or authors */
2060/** @author Brian Cavalier */
2061/** @author John Hann */
2062
2063function invoke (f, args) {
2064 /*eslint complexity: [2,7]*/
2065 switch (args.length) {
2066 case 0: return f()
2067 case 1: return f(args[0])
2068 case 2: return f(args[0], args[1])
2069 case 3: return f(args[0], args[1], args[2])
2070 case 4: return f(args[0], args[1], args[2], args[3])
2071 case 5: return f(args[0], args[1], args[2], args[3], args[4])
2072 default:
2073 return f.apply(void 0, args)
2074 }
2075}
2076
2077/** @license MIT License (c) copyright 2010-2016 original author or authors */
2078/** @author Brian Cavalier */
2079/** @author John Hann */
2080
2081var map$3 = map;
2082var tail$1 = tail;
2083
2084/**
2085 * Combine latest events from all input streams
2086 * @param {function(...events):*} f function to combine most recent events
2087 * @returns {Stream} stream containing the result of applying f to the most recent
2088 * event of each input stream, whenever a new event arrives on any stream.
2089 */
2090function combine (f /*, ...streams */) {
2091 return combineArray(f, tail$1(arguments))
2092}
2093
2094/**
2095* Combine latest events from all input streams
2096* @param {function(...events):*} f function to combine most recent events
2097* @param {[Stream]} streams most recent events
2098* @returns {Stream} stream containing the result of applying f to the most recent
2099* event of each input stream, whenever a new event arrives on any stream.
2100*/
2101function combineArray (f, streams) {
2102 var l = streams.length;
2103 return l === 0 ? empty()
2104 : l === 1 ? map$2(f, streams[0])
2105 : new Stream(combineSources(f, streams))
2106}
2107
2108function combineSources (f, streams) {
2109 return new Combine(f, map$3(getSource, streams))
2110}
2111
2112function getSource (stream) {
2113 return stream.source
2114}
2115
2116function Combine (f, sources) {
2117 this.f = f;
2118 this.sources = sources;
2119}
2120
2121Combine.prototype.run = function (sink, scheduler) {
2122 var this$1 = this;
2123
2124 var l = this.sources.length;
2125 var disposables = new Array(l);
2126 var sinks = new Array(l);
2127
2128 var mergeSink = new CombineSink(disposables, sinks, sink, this.f);
2129
2130 for (var indexSink, i = 0; i < l; ++i) {
2131 indexSink = sinks[i] = new IndexSink(i, mergeSink);
2132 disposables[i] = this$1.sources[i].run(indexSink, scheduler);
2133 }
2134
2135 return all(disposables)
2136};
2137
2138function CombineSink (disposables, sinks, sink, f) {
2139 var this$1 = this;
2140
2141 this.sink = sink;
2142 this.disposables = disposables;
2143 this.sinks = sinks;
2144 this.f = f;
2145
2146 var l = sinks.length;
2147 this.awaiting = l;
2148 this.values = new Array(l);
2149 this.hasValue = new Array(l);
2150 for (var i = 0; i < l; ++i) {
2151 this$1.hasValue[i] = false;
2152 }
2153
2154 this.activeCount = sinks.length;
2155}
2156
2157CombineSink.prototype.error = Pipe.prototype.error;
2158
2159CombineSink.prototype.event = function (t, indexedValue) {
2160 var i = indexedValue.index;
2161 var awaiting = this._updateReady(i);
2162
2163 this.values[i] = indexedValue.value;
2164 if (awaiting === 0) {
2165 this.sink.event(t, invoke(this.f, this.values));
2166 }
2167};
2168
2169CombineSink.prototype._updateReady = function (index) {
2170 if (this.awaiting > 0) {
2171 if (!this.hasValue[index]) {
2172 this.hasValue[index] = true;
2173 this.awaiting -= 1;
2174 }
2175 }
2176 return this.awaiting
2177};
2178
2179CombineSink.prototype.end = function (t, indexedValue) {
2180 tryDispose(t, this.disposables[indexedValue.index], this.sink);
2181 if (--this.activeCount === 0) {
2182 this.sink.end(t, indexedValue.value);
2183 }
2184};
2185
2186/** @license MIT License (c) copyright 2010-2016 original author or authors */
2187/** @author Brian Cavalier */
2188/** @author John Hann */
2189
2190/**
2191 * Assume fs is a stream containing functions, and apply the latest function
2192 * in fs to the latest value in xs.
2193 * fs: --f---------g--------h------>
2194 * xs: -a-------b-------c-------d-->
2195 * ap(fs, xs): --fa-----fb-gb---gc--hc--hd->
2196 * @param {Stream} fs stream of functions to apply to the latest x
2197 * @param {Stream} xs stream of values to which to apply all the latest f
2198 * @returns {Stream} stream containing all the applications of fs to xs
2199 */
2200function ap (fs, xs) {
2201 return combine(apply, fs, xs)
2202}
2203
2204/** @license MIT License (c) copyright 2010-2016 original author or authors */
2205/** @author Brian Cavalier */
2206/** @author John Hann */
2207
2208/**
2209 * Transform a stream by passing its events through a transducer.
2210 * @param {function} transducer transducer function
2211 * @param {Stream} stream stream whose events will be passed through the
2212 * transducer
2213 * @return {Stream} stream of events transformed by the transducer
2214 */
2215function transduce (transducer, stream) {
2216 return new Stream(new Transduce(transducer, stream.source))
2217}
2218
2219function Transduce (transducer, source) {
2220 this.transducer = transducer;
2221 this.source = source;
2222}
2223
2224Transduce.prototype.run = function (sink, scheduler) {
2225 var xf = this.transducer(new Transformer(sink));
2226 return this.source.run(new TransduceSink(getTxHandler(xf), sink), scheduler)
2227};
2228
2229function TransduceSink (adapter, sink) {
2230 this.xf = adapter;
2231 this.sink = sink;
2232}
2233
2234TransduceSink.prototype.event = function (t, x) {
2235 var next = this.xf.step(t, x);
2236
2237 return this.xf.isReduced(next)
2238 ? this.sink.end(t, this.xf.getResult(next))
2239 : next
2240};
2241
2242TransduceSink.prototype.end = function (t, x) {
2243 return this.xf.result(x)
2244};
2245
2246TransduceSink.prototype.error = function (t, e) {
2247 return this.sink.error(t, e)
2248};
2249
2250function Transformer (sink) {
2251 this.time = -Infinity;
2252 this.sink = sink;
2253}
2254
2255Transformer.prototype['@@transducer/init'] = Transformer.prototype.init = function () {};
2256
2257Transformer.prototype['@@transducer/step'] = Transformer.prototype.step = function (t, x) {
2258 if (!isNaN(t)) {
2259 this.time = Math.max(t, this.time);
2260 }
2261 return this.sink.event(this.time, x)
2262};
2263
2264Transformer.prototype['@@transducer/result'] = Transformer.prototype.result = function (x) {
2265 return this.sink.end(this.time, x)
2266};
2267
2268/**
2269* Given an object supporting the new or legacy transducer protocol,
2270* create an adapter for it.
2271* @param {object} tx transform
2272* @returns {TxAdapter|LegacyTxAdapter}
2273*/
2274function getTxHandler (tx) {
2275 return typeof tx['@@transducer/step'] === 'function'
2276 ? new TxAdapter(tx)
2277 : new LegacyTxAdapter(tx)
2278}
2279
2280/**
2281* Adapter for new official transducer protocol
2282* @param {object} tx transform
2283* @constructor
2284*/
2285function TxAdapter (tx) {
2286 this.tx = tx;
2287}
2288
2289TxAdapter.prototype.step = function (t, x) {
2290 return this.tx['@@transducer/step'](t, x)
2291};
2292TxAdapter.prototype.result = function (x) {
2293 return this.tx['@@transducer/result'](x)
2294};
2295TxAdapter.prototype.isReduced = function (x) {
2296 return x != null && x['@@transducer/reduced']
2297};
2298TxAdapter.prototype.getResult = function (x) {
2299 return x['@@transducer/value']
2300};
2301
2302/**
2303* Adapter for older transducer protocol
2304* @param {object} tx transform
2305* @constructor
2306*/
2307function LegacyTxAdapter (tx) {
2308 this.tx = tx;
2309}
2310
2311LegacyTxAdapter.prototype.step = function (t, x) {
2312 return this.tx.step(t, x)
2313};
2314LegacyTxAdapter.prototype.result = function (x) {
2315 return this.tx.result(x)
2316};
2317LegacyTxAdapter.prototype.isReduced = function (x) {
2318 return x != null && x.__transducers_reduced__
2319};
2320LegacyTxAdapter.prototype.getResult = function (x) {
2321 return x.value
2322};
2323
2324/** @license MIT License (c) copyright 2010-2016 original author or authors */
2325/** @author Brian Cavalier */
2326/** @author John Hann */
2327
2328/**
2329 * Doubly linked list
2330 * @constructor
2331 */
2332function LinkedList () {
2333 this.head = null;
2334 this.length = 0;
2335}
2336
2337/**
2338 * Add a node to the end of the list
2339 * @param {{prev:Object|null, next:Object|null, dispose:function}} x node to add
2340 */
2341LinkedList.prototype.add = function (x) {
2342 if (this.head !== null) {
2343 this.head.prev = x;
2344 x.next = this.head;
2345 }
2346 this.head = x;
2347 ++this.length;
2348};
2349
2350/**
2351 * Remove the provided node from the list
2352 * @param {{prev:Object|null, next:Object|null, dispose:function}} x node to remove
2353 */
2354LinkedList.prototype.remove = function (x) { // eslint-disable-line complexity
2355 --this.length;
2356 if (x === this.head) {
2357 this.head = this.head.next;
2358 }
2359 if (x.next !== null) {
2360 x.next.prev = x.prev;
2361 x.next = null;
2362 }
2363 if (x.prev !== null) {
2364 x.prev.next = x.next;
2365 x.prev = null;
2366 }
2367};
2368
2369/**
2370 * @returns {boolean} true iff there are no nodes in the list
2371 */
2372LinkedList.prototype.isEmpty = function () {
2373 return this.length === 0
2374};
2375
2376/**
2377 * Dispose all nodes
2378 * @returns {Promise} promise that fulfills when all nodes have been disposed,
2379 * or rejects if an error occurs while disposing
2380 */
2381LinkedList.prototype.dispose = function () {
2382 if (this.isEmpty()) {
2383 return Promise.resolve()
2384 }
2385
2386 var promises = [];
2387 var x = this.head;
2388 this.head = null;
2389 this.length = 0;
2390
2391 while (x !== null) {
2392 promises.push(x.dispose());
2393 x = x.next;
2394 }
2395
2396 return Promise.all(promises)
2397};
2398
2399/** @license MIT License (c) copyright 2010-2016 original author or authors */
2400/** @author Brian Cavalier */
2401/** @author John Hann */
2402
2403function mergeConcurrently (concurrency, stream) {
2404 return mergeMapConcurrently(id, concurrency, stream)
2405}
2406
2407function mergeMapConcurrently (f, concurrency, stream) {
2408 return new Stream(new MergeConcurrently(f, concurrency, stream.source))
2409}
2410
2411function MergeConcurrently (f, concurrency, source) {
2412 this.f = f;
2413 this.concurrency = concurrency;
2414 this.source = source;
2415}
2416
2417MergeConcurrently.prototype.run = function (sink, scheduler) {
2418 return new Outer(this.f, this.concurrency, this.source, sink, scheduler)
2419};
2420
2421function Outer (f, concurrency, source, sink, scheduler) {
2422 this.f = f;
2423 this.concurrency = concurrency;
2424 this.sink = sink;
2425 this.scheduler = scheduler;
2426 this.pending = [];
2427 this.current = new LinkedList();
2428 this.disposable = once(source.run(this, scheduler));
2429 this.active = true;
2430}
2431
2432Outer.prototype.event = function (t, x) {
2433 this._addInner(t, x);
2434};
2435
2436Outer.prototype._addInner = function (t, x) {
2437 if (this.current.length < this.concurrency) {
2438 this._startInner(t, x);
2439 } else {
2440 this.pending.push(x);
2441 }
2442};
2443
2444Outer.prototype._startInner = function (t, x) {
2445 try {
2446 this._initInner(t, x);
2447 } catch (e) {
2448 this.error(t, e);
2449 }
2450};
2451
2452Outer.prototype._initInner = function (t, x) {
2453 var innerSink = new Inner(t, this, this.sink);
2454 innerSink.disposable = mapAndRun(this.f, x, innerSink, this.scheduler);
2455 this.current.add(innerSink);
2456};
2457
2458function mapAndRun (f, x, sink, scheduler) {
2459 return f(x).source.run(sink, scheduler)
2460}
2461
2462Outer.prototype.end = function (t, x) {
2463 this.active = false;
2464 tryDispose(t, this.disposable, this.sink);
2465 this._checkEnd(t, x);
2466};
2467
2468Outer.prototype.error = function (t, e) {
2469 this.active = false;
2470 this.sink.error(t, e);
2471};
2472
2473Outer.prototype.dispose = function () {
2474 this.active = false;
2475 this.pending.length = 0;
2476 return Promise.all([this.disposable.dispose(), this.current.dispose()])
2477};
2478
2479Outer.prototype._endInner = function (t, x, inner) {
2480 this.current.remove(inner);
2481 tryDispose(t, inner, this);
2482
2483 if (this.pending.length === 0) {
2484 this._checkEnd(t, x);
2485 } else {
2486 this._startInner(t, this.pending.shift());
2487 }
2488};
2489
2490Outer.prototype._checkEnd = function (t, x) {
2491 if (!this.active && this.current.isEmpty()) {
2492 this.sink.end(t, x);
2493 }
2494};
2495
2496function Inner (time, outer, sink) {
2497 this.prev = this.next = null;
2498 this.time = time;
2499 this.outer = outer;
2500 this.sink = sink;
2501 this.disposable = void 0;
2502}
2503
2504Inner.prototype.event = function (t, x) {
2505 this.sink.event(Math.max(t, this.time), x);
2506};
2507
2508Inner.prototype.end = function (t, x) {
2509 this.outer._endInner(Math.max(t, this.time), x, this);
2510};
2511
2512Inner.prototype.error = function (t, e) {
2513 this.outer.error(Math.max(t, this.time), e);
2514};
2515
2516Inner.prototype.dispose = function () {
2517 return this.disposable.dispose()
2518};
2519
2520/** @license MIT License (c) copyright 2010-2016 original author or authors */
2521/** @author Brian Cavalier */
2522/** @author John Hann */
2523
2524/**
2525 * Map each value in the stream to a new stream, and merge it into the
2526 * returned outer stream. Event arrival times are preserved.
2527 * @param {function(x:*):Stream} f chaining function, must return a Stream
2528 * @param {Stream} stream
2529 * @returns {Stream} new stream containing all events from each stream returned by f
2530 */
2531function flatMap (f, stream) {
2532 return mergeMapConcurrently(f, Infinity, stream)
2533}
2534
2535/**
2536 * Monadic join. Flatten a Stream<Stream<X>> to Stream<X> by merging inner
2537 * streams to the outer. Event arrival times are preserved.
2538 * @param {Stream<Stream<X>>} stream stream of streams
2539 * @returns {Stream<X>} new stream containing all events of all inner streams
2540 */
2541function join (stream) {
2542 return mergeConcurrently(Infinity, stream)
2543}
2544
2545/** @license MIT License (c) copyright 2010-2016 original author or authors */
2546/** @author Brian Cavalier */
2547/** @author John Hann */
2548
2549/**
2550 * Map each value in stream to a new stream, and concatenate them all
2551 * stream: -a---b---cX
2552 * f(a): 1-1-1-1X
2553 * f(b): -2-2-2-2X
2554 * f(c): -3-3-3-3X
2555 * stream.concatMap(f): -1-1-1-1-2-2-2-2-3-3-3-3X
2556 * @param {function(x:*):Stream} f function to map each value to a stream
2557 * @param {Stream} stream
2558 * @returns {Stream} new stream containing all events from each stream returned by f
2559 */
2560function concatMap (f, stream) {
2561 return mergeMapConcurrently(f, 1, stream)
2562}
2563
2564/** @license MIT License (c) copyright 2010-2016 original author or authors */
2565/** @author Brian Cavalier */
2566/** @author John Hann */
2567
2568var copy$1 = copy;
2569var reduce$2 = reduce;
2570
2571/**
2572 * @returns {Stream} stream containing events from all streams in the argument
2573 * list in time order. If two events are simultaneous they will be merged in
2574 * arbitrary order.
2575 */
2576function merge (/* ...streams*/) {
2577 return mergeArray(copy$1(arguments))
2578}
2579
2580/**
2581 * @param {Array} streams array of stream to merge
2582 * @returns {Stream} stream containing events from all input observables
2583 * in time order. If two events are simultaneous they will be merged in
2584 * arbitrary order.
2585 */
2586function mergeArray (streams) {
2587 var l = streams.length;
2588 return l === 0 ? empty()
2589 : l === 1 ? streams[0]
2590 : new Stream(mergeSources(streams))
2591}
2592
2593/**
2594 * This implements fusion/flattening for merge. It will
2595 * fuse adjacent merge operations. For example:
2596 * - a.merge(b).merge(c) effectively becomes merge(a, b, c)
2597 * - merge(a, merge(b, c)) effectively becomes merge(a, b, c)
2598 * It does this by concatenating the sources arrays of
2599 * any nested Merge sources, in effect "flattening" nested
2600 * merge operations into a single merge.
2601 */
2602function mergeSources (streams) {
2603 return new Merge(reduce$2(appendSources, [], streams))
2604}
2605
2606function appendSources (sources, stream) {
2607 var source = stream.source;
2608 return source instanceof Merge
2609 ? sources.concat(source.sources)
2610 : sources.concat(source)
2611}
2612
2613function Merge (sources) {
2614 this.sources = sources;
2615}
2616
2617Merge.prototype.run = function (sink, scheduler) {
2618 var this$1 = this;
2619
2620 var l = this.sources.length;
2621 var disposables = new Array(l);
2622 var sinks = new Array(l);
2623
2624 var mergeSink = new MergeSink(disposables, sinks, sink);
2625
2626 for (var indexSink, i = 0; i < l; ++i) {
2627 indexSink = sinks[i] = new IndexSink(i, mergeSink);
2628 disposables[i] = this$1.sources[i].run(indexSink, scheduler);
2629 }
2630
2631 return all(disposables)
2632};
2633
2634function MergeSink (disposables, sinks, sink) {
2635 this.sink = sink;
2636 this.disposables = disposables;
2637 this.activeCount = sinks.length;
2638}
2639
2640MergeSink.prototype.error = Pipe.prototype.error;
2641
2642MergeSink.prototype.event = function (t, indexValue) {
2643 this.sink.event(t, indexValue.value);
2644};
2645
2646MergeSink.prototype.end = function (t, indexedValue) {
2647 tryDispose(t, this.disposables[indexedValue.index], this.sink);
2648 if (--this.activeCount === 0) {
2649 this.sink.end(t, indexedValue.value);
2650 }
2651};
2652
2653/** @license MIT License (c) copyright 2010-2016 original author or authors */
2654/** @author Brian Cavalier */
2655/** @author John Hann */
2656
2657/**
2658 * When an event arrives on sampler, emit the result of calling f with the latest
2659 * values of all streams being sampled
2660 * @param {function(...values):*} f function to apply to each set of sampled values
2661 * @param {Stream} sampler streams will be sampled whenever an event arrives
2662 * on sampler
2663 * @returns {Stream} stream of sampled and transformed values
2664 */
2665function sample (f, sampler /*, ...streams */) {
2666 return sampleArray(f, sampler, drop(2, arguments))
2667}
2668
2669/**
2670 * When an event arrives on sampler, emit the latest event value from stream.
2671 * @param {Stream} sampler stream of events at whose arrival time
2672 * stream's latest value will be propagated
2673 * @param {Stream} stream stream of values
2674 * @returns {Stream} sampled stream of values
2675 */
2676function sampleWith (sampler, stream) {
2677 return new Stream(new Sampler(id, sampler.source, [stream.source]))
2678}
2679
2680function sampleArray (f, sampler, streams) {
2681 return new Stream(new Sampler(f, sampler.source, map(getSource$1, streams)))
2682}
2683
2684function getSource$1 (stream) {
2685 return stream.source
2686}
2687
2688function Sampler (f, sampler, sources) {
2689 this.f = f;
2690 this.sampler = sampler;
2691 this.sources = sources;
2692}
2693
2694Sampler.prototype.run = function (sink, scheduler) {
2695 var this$1 = this;
2696
2697 var l = this.sources.length;
2698 var disposables = new Array(l + 1);
2699 var sinks = new Array(l);
2700
2701 var sampleSink = new SampleSink(this.f, sinks, sink);
2702
2703 for (var hold, i = 0; i < l; ++i) {
2704 hold = sinks[i] = new Hold(sampleSink);
2705 disposables[i] = this$1.sources[i].run(hold, scheduler);
2706 }
2707
2708 disposables[i] = this.sampler.run(sampleSink, scheduler);
2709
2710 return all(disposables)
2711};
2712
2713function Hold (sink) {
2714 this.sink = sink;
2715 this.hasValue = false;
2716}
2717
2718Hold.prototype.event = function (t, x) {
2719 this.value = x;
2720 this.hasValue = true;
2721 this.sink._notify(this);
2722};
2723
2724Hold.prototype.end = function () {};
2725Hold.prototype.error = Pipe.prototype.error;
2726
2727function SampleSink (f, sinks, sink) {
2728 this.f = f;
2729 this.sinks = sinks;
2730 this.sink = sink;
2731 this.active = false;
2732}
2733
2734SampleSink.prototype._notify = function () {
2735 if (!this.active) {
2736 this.active = this.sinks.every(hasValue);
2737 }
2738};
2739
2740SampleSink.prototype.event = function (t) {
2741 if (this.active) {
2742 this.sink.event(t, invoke(this.f, map(getValue, this.sinks)));
2743 }
2744};
2745
2746SampleSink.prototype.end = Pipe.prototype.end;
2747SampleSink.prototype.error = Pipe.prototype.error;
2748
2749function hasValue (hold) {
2750 return hold.hasValue
2751}
2752
2753function getValue (hold) {
2754 return hold.value
2755}
2756
2757/** @license MIT License (c) copyright 2010-2016 original author or authors */
2758/** @author Brian Cavalier */
2759/** @author John Hann */
2760
2761// Based on https://github.com/petkaantonov/deque
2762
2763function Queue (capPow2) {
2764 this._capacity = capPow2 || 32;
2765 this._length = 0;
2766 this._head = 0;
2767}
2768
2769Queue.prototype.push = function (x) {
2770 var len = this._length;
2771 this._checkCapacity(len + 1);
2772
2773 var i = (this._head + len) & (this._capacity - 1);
2774 this[i] = x;
2775 this._length = len + 1;
2776};
2777
2778Queue.prototype.shift = function () {
2779 var head = this._head;
2780 var x = this[head];
2781
2782 this[head] = void 0;
2783 this._head = (head + 1) & (this._capacity - 1);
2784 this._length--;
2785 return x
2786};
2787
2788Queue.prototype.isEmpty = function () {
2789 return this._length === 0
2790};
2791
2792Queue.prototype.length = function () {
2793 return this._length
2794};
2795
2796Queue.prototype._checkCapacity = function (size) {
2797 if (this._capacity < size) {
2798 this._ensureCapacity(this._capacity << 1);
2799 }
2800};
2801
2802Queue.prototype._ensureCapacity = function (capacity) {
2803 var oldCapacity = this._capacity;
2804 this._capacity = capacity;
2805
2806 var last = this._head + this._length;
2807
2808 if (last > oldCapacity) {
2809 copy$2(this, 0, this, oldCapacity, last & (oldCapacity - 1));
2810 }
2811};
2812
2813function copy$2 (src, srcIndex, dst, dstIndex, len) {
2814 for (var j = 0; j < len; ++j) {
2815 dst[j + dstIndex] = src[j + srcIndex];
2816 src[j + srcIndex] = void 0;
2817 }
2818}
2819
2820/** @license MIT License (c) copyright 2010-2016 original author or authors */
2821/** @author Brian Cavalier */
2822/** @author John Hann */
2823
2824var map$4 = map;
2825var tail$2 = tail;
2826
2827/**
2828 * Combine streams pairwise (or tuple-wise) by index by applying f to values
2829 * at corresponding indices. The returned stream ends when any of the input
2830 * streams ends.
2831 * @param {function} f function to combine values
2832 * @returns {Stream} new stream with items at corresponding indices combined
2833 * using f
2834 */
2835function zip (f /*, ...streams */) {
2836 return zipArray(f, tail$2(arguments))
2837}
2838
2839/**
2840* Combine streams pairwise (or tuple-wise) by index by applying f to values
2841* at corresponding indices. The returned stream ends when any of the input
2842* streams ends.
2843* @param {function} f function to combine values
2844* @param {[Stream]} streams streams to zip using f
2845* @returns {Stream} new stream with items at corresponding indices combined
2846* using f
2847*/
2848function zipArray (f, streams) {
2849 return streams.length === 0 ? empty()
2850: streams.length === 1 ? map$2(f, streams[0])
2851: new Stream(new Zip(f, map$4(getSource$2, streams)))
2852}
2853
2854function getSource$2 (stream) {
2855 return stream.source
2856}
2857
2858function Zip (f, sources) {
2859 this.f = f;
2860 this.sources = sources;
2861}
2862
2863Zip.prototype.run = function (sink, scheduler) {
2864 var this$1 = this;
2865
2866 var l = this.sources.length;
2867 var disposables = new Array(l);
2868 var sinks = new Array(l);
2869 var buffers = new Array(l);
2870
2871 var zipSink = new ZipSink(this.f, buffers, sinks, sink);
2872
2873 for (var indexSink, i = 0; i < l; ++i) {
2874 buffers[i] = new Queue();
2875 indexSink = sinks[i] = new IndexSink(i, zipSink);
2876 disposables[i] = this$1.sources[i].run(indexSink, scheduler);
2877 }
2878
2879 return all(disposables)
2880};
2881
2882function ZipSink (f, buffers, sinks, sink) {
2883 this.f = f;
2884 this.sinks = sinks;
2885 this.sink = sink;
2886 this.buffers = buffers;
2887}
2888
2889ZipSink.prototype.event = function (t, indexedValue) { // eslint-disable-line complexity
2890 var buffers = this.buffers;
2891 var buffer = buffers[indexedValue.index];
2892
2893 buffer.push(indexedValue.value);
2894
2895 if (buffer.length() === 1) {
2896 if (!ready(this.buffers)) {
2897 return
2898 }
2899
2900 emitZipped(this.f, t, buffers, this.sink);
2901
2902 if (ended(this.buffers, this.sinks)) {
2903 this.sink.end(t, void 0);
2904 }
2905 }
2906};
2907
2908ZipSink.prototype.end = function (t, indexedValue) {
2909 var buffer = this.buffers[indexedValue.index];
2910 if (buffer.isEmpty()) {
2911 this.sink.end(t, indexedValue.value);
2912 }
2913};
2914
2915ZipSink.prototype.error = Pipe.prototype.error;
2916
2917function emitZipped (f, t, buffers, sink) {
2918 sink.event(t, invoke(f, map$4(head, buffers)));
2919}
2920
2921function head (buffer) {
2922 return buffer.shift()
2923}
2924
2925function ended (buffers, sinks) {
2926 for (var i = 0, l = buffers.length; i < l; ++i) {
2927 if (buffers[i].isEmpty() && !sinks[i].active) {
2928 return true
2929 }
2930 }
2931 return false
2932}
2933
2934function ready (buffers) {
2935 for (var i = 0, l = buffers.length; i < l; ++i) {
2936 if (buffers[i].isEmpty()) {
2937 return false
2938 }
2939 }
2940 return true
2941}
2942
2943/** @license MIT License (c) copyright 2010-2016 original author or authors */
2944/** @author Brian Cavalier */
2945/** @author John Hann */
2946
2947/**
2948 * Given a stream of streams, return a new stream that adopts the behavior
2949 * of the most recent inner stream.
2950 * @param {Stream} stream of streams on which to switch
2951 * @returns {Stream} switching stream
2952 */
2953function switchLatest (stream) {
2954 return new Stream(new Switch(stream.source))
2955}
2956
2957function Switch (source) {
2958 this.source = source;
2959}
2960
2961Switch.prototype.run = function (sink, scheduler) {
2962 var switchSink = new SwitchSink(sink, scheduler);
2963 return all([switchSink, this.source.run(switchSink, scheduler)])
2964};
2965
2966function SwitchSink (sink, scheduler) {
2967 this.sink = sink;
2968 this.scheduler = scheduler;
2969 this.current = null;
2970 this.ended = false;
2971}
2972
2973SwitchSink.prototype.event = function (t, stream) {
2974 this._disposeCurrent(t); // TODO: capture the result of this dispose
2975 this.current = new Segment(t, Infinity, this, this.sink);
2976 this.current.disposable = stream.source.run(this.current, this.scheduler);
2977};
2978
2979SwitchSink.prototype.end = function (t, x) {
2980 this.ended = true;
2981 this._checkEnd(t, x);
2982};
2983
2984SwitchSink.prototype.error = function (t, e) {
2985 this.ended = true;
2986 this.sink.error(t, e);
2987};
2988
2989SwitchSink.prototype.dispose = function () {
2990 return this._disposeCurrent(this.scheduler.now())
2991};
2992
2993SwitchSink.prototype._disposeCurrent = function (t) {
2994 if (this.current !== null) {
2995 return this.current._dispose(t)
2996 }
2997};
2998
2999SwitchSink.prototype._disposeInner = function (t, inner) {
3000 inner._dispose(t); // TODO: capture the result of this dispose
3001 if (inner === this.current) {
3002 this.current = null;
3003 }
3004};
3005
3006SwitchSink.prototype._checkEnd = function (t, x) {
3007 if (this.ended && this.current === null) {
3008 this.sink.end(t, x);
3009 }
3010};
3011
3012SwitchSink.prototype._endInner = function (t, x, inner) {
3013 this._disposeInner(t, inner);
3014 this._checkEnd(t, x);
3015};
3016
3017SwitchSink.prototype._errorInner = function (t, e, inner) {
3018 this._disposeInner(t, inner);
3019 this.sink.error(t, e);
3020};
3021
3022function Segment (min, max, outer, sink) {
3023 this.min = min;
3024 this.max = max;
3025 this.outer = outer;
3026 this.sink = sink;
3027 this.disposable = empty$1();
3028}
3029
3030Segment.prototype.event = function (t, x) {
3031 if (t < this.max) {
3032 this.sink.event(Math.max(t, this.min), x);
3033 }
3034};
3035
3036Segment.prototype.end = function (t, x) {
3037 this.outer._endInner(Math.max(t, this.min), x, this);
3038};
3039
3040Segment.prototype.error = function (t, e) {
3041 this.outer._errorInner(Math.max(t, this.min), e, this);
3042};
3043
3044Segment.prototype._dispose = function (t) {
3045 this.max = t;
3046 tryDispose(t, this.disposable, this.sink);
3047};
3048
3049/** @license MIT License (c) copyright 2010-2016 original author or authors */
3050/** @author Brian Cavalier */
3051/** @author John Hann */
3052
3053/**
3054 * Retain only items matching a predicate
3055 * @param {function(x:*):boolean} p filtering predicate called for each item
3056 * @param {Stream} stream stream to filter
3057 * @returns {Stream} stream containing only items for which predicate returns truthy
3058 */
3059function filter (p, stream) {
3060 return new Stream(Filter.create(p, stream.source))
3061}
3062
3063/**
3064 * Skip repeated events, using === to detect duplicates
3065 * @param {Stream} stream stream from which to omit repeated events
3066 * @returns {Stream} stream without repeated events
3067 */
3068function skipRepeats (stream) {
3069 return skipRepeatsWith(same, stream)
3070}
3071
3072/**
3073 * Skip repeated events using the provided equals function to detect duplicates
3074 * @param {function(a:*, b:*):boolean} equals optional function to compare items
3075 * @param {Stream} stream stream from which to omit repeated events
3076 * @returns {Stream} stream without repeated events
3077 */
3078function skipRepeatsWith (equals, stream) {
3079 return new Stream(new SkipRepeats(equals, stream.source))
3080}
3081
3082function SkipRepeats (equals, source) {
3083 this.equals = equals;
3084 this.source = source;
3085}
3086
3087SkipRepeats.prototype.run = function (sink, scheduler) {
3088 return this.source.run(new SkipRepeatsSink(this.equals, sink), scheduler)
3089};
3090
3091function SkipRepeatsSink (equals, sink) {
3092 this.equals = equals;
3093 this.sink = sink;
3094 this.value = void 0;
3095 this.init = true;
3096}
3097
3098SkipRepeatsSink.prototype.end = Pipe.prototype.end;
3099SkipRepeatsSink.prototype.error = Pipe.prototype.error;
3100
3101SkipRepeatsSink.prototype.event = function (t, x) {
3102 if (this.init) {
3103 this.init = false;
3104 this.value = x;
3105 this.sink.event(t, x);
3106 } else if (!this.equals(this.value, x)) {
3107 this.value = x;
3108 this.sink.event(t, x);
3109 }
3110};
3111
3112function same (a, b) {
3113 return a === b
3114}
3115
3116/** @license MIT License (c) copyright 2010-2016 original author or authors */
3117/** @author Brian Cavalier */
3118/** @author John Hann */
3119
3120/**
3121 * @param {number} n
3122 * @param {Stream} stream
3123 * @returns {Stream} new stream containing only up to the first n items from stream
3124 */
3125function take (n, stream) {
3126 return slice(0, n, stream)
3127}
3128
3129/**
3130 * @param {number} n
3131 * @param {Stream} stream
3132 * @returns {Stream} new stream with the first n items removed
3133 */
3134function skip (n, stream) {
3135 return slice(n, Infinity, stream)
3136}
3137
3138/**
3139 * Slice a stream by index. Negative start/end indexes are not supported
3140 * @param {number} start
3141 * @param {number} end
3142 * @param {Stream} stream
3143 * @returns {Stream} stream containing items where start <= index < end
3144 */
3145function slice (start, end, stream) {
3146 return end <= start ? empty()
3147 : new Stream(sliceSource(start, end, stream.source))
3148}
3149
3150function sliceSource (start, end, source) {
3151 return source instanceof Map ? commuteMapSlice(start, end, source)
3152 : source instanceof Slice ? fuseSlice(start, end, source)
3153 : new Slice(start, end, source)
3154}
3155
3156function commuteMapSlice (start, end, source) {
3157 return Map.create(source.f, sliceSource(start, end, source.source))
3158}
3159
3160function fuseSlice (start, end, source) {
3161 start += source.min;
3162 end = Math.min(end + source.min, source.max);
3163 return new Slice(start, end, source.source)
3164}
3165
3166function Slice (min, max, source) {
3167 this.source = source;
3168 this.min = min;
3169 this.max = max;
3170}
3171
3172Slice.prototype.run = function (sink, scheduler) {
3173 var disposable = settable();
3174 var sliceSink = new SliceSink(this.min, this.max - this.min, sink, disposable);
3175
3176 disposable.setDisposable(this.source.run(sliceSink, scheduler));
3177 return disposable
3178};
3179
3180function SliceSink (skip, take, sink, disposable) {
3181 this.sink = sink;
3182 this.skip = skip;
3183 this.take = take;
3184 this.disposable = disposable;
3185}
3186
3187SliceSink.prototype.end = Pipe.prototype.end;
3188SliceSink.prototype.error = Pipe.prototype.error;
3189
3190SliceSink.prototype.event = function (t, x) {
3191 /* eslint complexity: [1, 4] */
3192 if (this.skip > 0) {
3193 this.skip -= 1;
3194 return
3195 }
3196
3197 if (this.take === 0) {
3198 return
3199 }
3200
3201 this.take -= 1;
3202 this.sink.event(t, x);
3203 if (this.take === 0) {
3204 this.disposable.dispose();
3205 this.sink.end(t, x);
3206 }
3207};
3208
3209function takeWhile (p, stream) {
3210 return new Stream(new TakeWhile(p, stream.source))
3211}
3212
3213function TakeWhile (p, source) {
3214 this.p = p;
3215 this.source = source;
3216}
3217
3218TakeWhile.prototype.run = function (sink, scheduler) {
3219 var disposable = settable();
3220 var takeWhileSink = new TakeWhileSink(this.p, sink, disposable);
3221
3222 disposable.setDisposable(this.source.run(takeWhileSink, scheduler));
3223 return disposable
3224};
3225
3226function TakeWhileSink (p, sink, disposable) {
3227 this.p = p;
3228 this.sink = sink;
3229 this.active = true;
3230 this.disposable = disposable;
3231}
3232
3233TakeWhileSink.prototype.end = Pipe.prototype.end;
3234TakeWhileSink.prototype.error = Pipe.prototype.error;
3235
3236TakeWhileSink.prototype.event = function (t, x) {
3237 if (!this.active) {
3238 return
3239 }
3240
3241 var p = this.p;
3242 this.active = p(x);
3243 if (this.active) {
3244 this.sink.event(t, x);
3245 } else {
3246 this.disposable.dispose();
3247 this.sink.end(t, x);
3248 }
3249};
3250
3251function skipWhile (p, stream) {
3252 return new Stream(new SkipWhile(p, stream.source))
3253}
3254
3255function SkipWhile (p, source) {
3256 this.p = p;
3257 this.source = source;
3258}
3259
3260SkipWhile.prototype.run = function (sink, scheduler) {
3261 return this.source.run(new SkipWhileSink(this.p, sink), scheduler)
3262};
3263
3264function SkipWhileSink (p, sink) {
3265 this.p = p;
3266 this.sink = sink;
3267 this.skipping = true;
3268}
3269
3270SkipWhileSink.prototype.end = Pipe.prototype.end;
3271SkipWhileSink.prototype.error = Pipe.prototype.error;
3272
3273SkipWhileSink.prototype.event = function (t, x) {
3274 if (this.skipping) {
3275 var p = this.p;
3276 this.skipping = p(x);
3277 if (this.skipping) {
3278 return
3279 }
3280 }
3281
3282 this.sink.event(t, x);
3283};
3284
3285function skipAfter (p, stream) {
3286 return new Stream(new SkipAfter(p, stream.source))
3287}
3288
3289function SkipAfter (p, source) {
3290 this.p = p;
3291 this.source = source;
3292}
3293
3294SkipAfter.prototype.run = function run (sink, scheduler) {
3295 return this.source.run(new SkipAfterSink(this.p, sink), scheduler)
3296};
3297
3298function SkipAfterSink (p, sink) {
3299 this.p = p;
3300 this.sink = sink;
3301 this.skipping = false;
3302}
3303
3304SkipAfterSink.prototype.event = function event (t, x) {
3305 if (this.skipping) {
3306 return
3307 }
3308
3309 var p = this.p;
3310 this.skipping = p(x);
3311 this.sink.event(t, x);
3312
3313 if (this.skipping) {
3314 this.sink.end(t, x);
3315 }
3316};
3317
3318SkipAfterSink.prototype.end = Pipe.prototype.end;
3319SkipAfterSink.prototype.error = Pipe.prototype.error;
3320
3321/** @license MIT License (c) copyright 2010-2016 original author or authors */
3322/** @author Brian Cavalier */
3323/** @author John Hann */
3324
3325function takeUntil (signal, stream) {
3326 return new Stream(new Until(signal.source, stream.source))
3327}
3328
3329function skipUntil (signal, stream) {
3330 return new Stream(new Since(signal.source, stream.source))
3331}
3332
3333function during (timeWindow, stream) {
3334 return takeUntil(join(timeWindow), skipUntil(timeWindow, stream))
3335}
3336
3337function Until (maxSignal, source) {
3338 this.maxSignal = maxSignal;
3339 this.source = source;
3340}
3341
3342Until.prototype.run = function (sink, scheduler) {
3343 var min = new Bound(-Infinity, sink);
3344 var max = new UpperBound(this.maxSignal, sink, scheduler);
3345 var disposable = this.source.run(new TimeWindowSink(min, max, sink), scheduler);
3346
3347 return all([min, max, disposable])
3348};
3349
3350function Since (minSignal, source) {
3351 this.minSignal = minSignal;
3352 this.source = source;
3353}
3354
3355Since.prototype.run = function (sink, scheduler) {
3356 var min = new LowerBound(this.minSignal, sink, scheduler);
3357 var max = new Bound(Infinity, sink);
3358 var disposable = this.source.run(new TimeWindowSink(min, max, sink), scheduler);
3359
3360 return all([min, max, disposable])
3361};
3362
3363function Bound (value, sink) {
3364 this.value = value;
3365 this.sink = sink;
3366}
3367
3368Bound.prototype.error = Pipe.prototype.error;
3369Bound.prototype.event = noop;
3370Bound.prototype.end = noop;
3371Bound.prototype.dispose = noop;
3372
3373function TimeWindowSink (min, max, sink) {
3374 this.min = min;
3375 this.max = max;
3376 this.sink = sink;
3377}
3378
3379TimeWindowSink.prototype.event = function (t, x) {
3380 if (t >= this.min.value && t < this.max.value) {
3381 this.sink.event(t, x);
3382 }
3383};
3384
3385TimeWindowSink.prototype.error = Pipe.prototype.error;
3386TimeWindowSink.prototype.end = Pipe.prototype.end;
3387
3388function LowerBound (signal, sink, scheduler) {
3389 this.value = Infinity;
3390 this.sink = sink;
3391 this.disposable = signal.run(this, scheduler);
3392}
3393
3394LowerBound.prototype.event = function (t /*, x */) {
3395 if (t < this.value) {
3396 this.value = t;
3397 }
3398};
3399
3400LowerBound.prototype.end = noop;
3401LowerBound.prototype.error = Pipe.prototype.error;
3402
3403LowerBound.prototype.dispose = function () {
3404 return this.disposable.dispose()
3405};
3406
3407function UpperBound (signal, sink, scheduler) {
3408 this.value = Infinity;
3409 this.sink = sink;
3410 this.disposable = signal.run(this, scheduler);
3411}
3412
3413UpperBound.prototype.event = function (t, x) {
3414 if (t < this.value) {
3415 this.value = t;
3416 this.sink.end(t, x);
3417 }
3418};
3419
3420UpperBound.prototype.end = noop;
3421UpperBound.prototype.error = Pipe.prototype.error;
3422
3423UpperBound.prototype.dispose = function () {
3424 return this.disposable.dispose()
3425};
3426
3427function noop () {}
3428
3429/** @license MIT License (c) copyright 2010-2016 original author or authors */
3430/** @author Brian Cavalier */
3431/** @author John Hann */
3432
3433/**
3434 * @param {Number} delayTime milliseconds to delay each item
3435 * @param {Stream} stream
3436 * @returns {Stream} new stream containing the same items, but delayed by ms
3437 */
3438function delay (delayTime, stream) {
3439 return delayTime <= 0 ? stream
3440 : new Stream(new Delay(delayTime, stream.source))
3441}
3442
3443function Delay (dt, source) {
3444 this.dt = dt;
3445 this.source = source;
3446}
3447
3448Delay.prototype.run = function (sink, scheduler) {
3449 var delaySink = new DelaySink(this.dt, sink, scheduler);
3450 return all([delaySink, this.source.run(delaySink, scheduler)])
3451};
3452
3453function DelaySink (dt, sink, scheduler) {
3454 this.dt = dt;
3455 this.sink = sink;
3456 this.scheduler = scheduler;
3457}
3458
3459DelaySink.prototype.dispose = function () {
3460 var self = this;
3461 this.scheduler.cancelAll(function (task) {
3462 return task.sink === self.sink
3463 });
3464};
3465
3466DelaySink.prototype.event = function (t, x) {
3467 this.scheduler.delay(this.dt, PropagateTask.event(x, this.sink));
3468};
3469
3470DelaySink.prototype.end = function (t, x) {
3471 this.scheduler.delay(this.dt, PropagateTask.end(x, this.sink));
3472};
3473
3474DelaySink.prototype.error = Pipe.prototype.error;
3475
3476/** @license MIT License (c) copyright 2010-2016 original author or authors */
3477/** @author Brian Cavalier */
3478/** @author John Hann */
3479
3480function timestamp (stream) {
3481 return new Stream(new Timestamp(stream.source))
3482}
3483
3484function Timestamp (source) {
3485 this.source = source;
3486}
3487
3488Timestamp.prototype.run = function (sink, scheduler) {
3489 return this.source.run(new TimestampSink(sink), scheduler)
3490};
3491
3492function TimestampSink (sink) {
3493 this.sink = sink;
3494}
3495
3496TimestampSink.prototype.end = Pipe.prototype.end;
3497TimestampSink.prototype.error = Pipe.prototype.error;
3498
3499TimestampSink.prototype.event = function (t, x) {
3500 this.sink.event(t, { time: t, value: x });
3501};
3502
3503/** @license MIT License (c) copyright 2010-2016 original author or authors */
3504/** @author Brian Cavalier */
3505/** @author John Hann */
3506
3507/**
3508 * Limit the rate of events by suppressing events that occur too often
3509 * @param {Number} period time to suppress events
3510 * @param {Stream} stream
3511 * @returns {Stream}
3512 */
3513function throttle (period, stream) {
3514 return new Stream(throttleSource(period, stream.source))
3515}
3516
3517function throttleSource (period, source) {
3518 return source instanceof Map ? commuteMapThrottle(period, source)
3519 : source instanceof Throttle ? fuseThrottle(period, source)
3520 : new Throttle(period, source)
3521}
3522
3523function commuteMapThrottle (period, source) {
3524 return Map.create(source.f, throttleSource(period, source.source))
3525}
3526
3527function fuseThrottle (period, source) {
3528 return new Throttle(Math.max(period, source.period), source.source)
3529}
3530
3531function Throttle (period, source) {
3532 this.period = period;
3533 this.source = source;
3534}
3535
3536Throttle.prototype.run = function (sink, scheduler) {
3537 return this.source.run(new ThrottleSink(this.period, sink), scheduler)
3538};
3539
3540function ThrottleSink (period, sink) {
3541 this.time = 0;
3542 this.period = period;
3543 this.sink = sink;
3544}
3545
3546ThrottleSink.prototype.event = function (t, x) {
3547 if (t >= this.time) {
3548 this.time = t + this.period;
3549 this.sink.event(t, x);
3550 }
3551};
3552
3553ThrottleSink.prototype.end = Pipe.prototype.end;
3554
3555ThrottleSink.prototype.error = Pipe.prototype.error;
3556
3557/**
3558 * Wait for a burst of events to subside and emit only the last event in the burst
3559 * @param {Number} period events occuring more frequently than this
3560 * will be suppressed
3561 * @param {Stream} stream stream to debounce
3562 * @returns {Stream} new debounced stream
3563 */
3564function debounce (period, stream) {
3565 return new Stream(new Debounce(period, stream.source))
3566}
3567
3568function Debounce (dt, source) {
3569 this.dt = dt;
3570 this.source = source;
3571}
3572
3573Debounce.prototype.run = function (sink, scheduler) {
3574 return new DebounceSink(this.dt, this.source, sink, scheduler)
3575};
3576
3577function DebounceSink (dt, source, sink, scheduler) {
3578 this.dt = dt;
3579 this.sink = sink;
3580 this.scheduler = scheduler;
3581 this.value = void 0;
3582 this.timer = null;
3583 this.disposable = source.run(this, scheduler);
3584}
3585
3586DebounceSink.prototype.event = function (t, x) {
3587 this._clearTimer();
3588 this.value = x;
3589 this.timer = this.scheduler.delay(this.dt, PropagateTask.event(x, this.sink));
3590};
3591
3592DebounceSink.prototype.end = function (t, x) {
3593 if (this._clearTimer()) {
3594 this.sink.event(t, this.value);
3595 this.value = void 0;
3596 }
3597 this.sink.end(t, x);
3598};
3599
3600DebounceSink.prototype.error = function (t, x) {
3601 this._clearTimer();
3602 this.sink.error(t, x);
3603};
3604
3605DebounceSink.prototype.dispose = function () {
3606 this._clearTimer();
3607 return this.disposable.dispose()
3608};
3609
3610DebounceSink.prototype._clearTimer = function () {
3611 if (this.timer === null) {
3612 return false
3613 }
3614 this.timer.dispose();
3615 this.timer = null;
3616 return true
3617};
3618
3619/** @license MIT License (c) copyright 2010-2016 original author or authors */
3620/** @author Brian Cavalier */
3621/** @author John Hann */
3622
3623/**
3624 * Create a stream containing only the promise's fulfillment
3625 * value at the time it fulfills.
3626 * @param {Promise<T>} p promise
3627 * @return {Stream<T>} stream containing promise's fulfillment value.
3628 * If the promise rejects, the stream will error
3629 */
3630function fromPromise (p) {
3631 return awaitPromises(of(p))
3632}
3633
3634/**
3635 * Turn a Stream<Promise<T>> into Stream<T> by awaiting each promise.
3636 * Event order is preserved.
3637 * @param {Stream<Promise<T>>} stream
3638 * @return {Stream<T>} stream of fulfillment values. The stream will
3639 * error if any promise rejects.
3640 */
3641function awaitPromises (stream) {
3642 return new Stream(new Await(stream.source))
3643}
3644
3645function Await (source) {
3646 this.source = source;
3647}
3648
3649Await.prototype.run = function (sink, scheduler) {
3650 return this.source.run(new AwaitSink(sink, scheduler), scheduler)
3651};
3652
3653function AwaitSink (sink, scheduler) {
3654 this.sink = sink;
3655 this.scheduler = scheduler;
3656 this.queue = Promise.resolve();
3657 var self = this;
3658
3659 // Pre-create closures, to avoid creating them per event
3660 this._eventBound = function (x) {
3661 self.sink.event(self.scheduler.now(), x);
3662 };
3663
3664 this._endBound = function (x) {
3665 self.sink.end(self.scheduler.now(), x);
3666 };
3667
3668 this._errorBound = function (e) {
3669 self.sink.error(self.scheduler.now(), e);
3670 };
3671}
3672
3673AwaitSink.prototype.event = function (t, promise) {
3674 var self = this;
3675 this.queue = this.queue.then(function () {
3676 return self._event(promise)
3677 }).catch(this._errorBound);
3678};
3679
3680AwaitSink.prototype.end = function (t, x) {
3681 var self = this;
3682 this.queue = this.queue.then(function () {
3683 return self._end(x)
3684 }).catch(this._errorBound);
3685};
3686
3687AwaitSink.prototype.error = function (t, e) {
3688 var self = this;
3689 // Don't resolve error values, propagate directly
3690 this.queue = this.queue.then(function () {
3691 return self._errorBound(e)
3692 }).catch(fatalError);
3693};
3694
3695AwaitSink.prototype._event = function (promise) {
3696 return promise.then(this._eventBound)
3697};
3698
3699AwaitSink.prototype._end = function (x) {
3700 return Promise.resolve(x).then(this._endBound)
3701};
3702
3703/** @license MIT License (c) copyright 2010-2016 original author or authors */
3704/** @author Brian Cavalier */
3705/** @author John Hann */
3706
3707function SafeSink (sink) {
3708 this.sink = sink;
3709 this.active = true;
3710}
3711
3712SafeSink.prototype.event = function (t, x) {
3713 if (!this.active) {
3714 return
3715 }
3716 this.sink.event(t, x);
3717};
3718
3719SafeSink.prototype.end = function (t, x) {
3720 if (!this.active) {
3721 return
3722 }
3723 this.disable();
3724 this.sink.end(t, x);
3725};
3726
3727SafeSink.prototype.error = function (t, e) {
3728 this.disable();
3729 this.sink.error(t, e);
3730};
3731
3732SafeSink.prototype.disable = function () {
3733 this.active = false;
3734 return this.sink
3735};
3736
3737/** @license MIT License (c) copyright 2010-2016 original author or authors */
3738/** @author Brian Cavalier */
3739/** @author John Hann */
3740
3741/**
3742 * If stream encounters an error, recover and continue with items from stream
3743 * returned by f.
3744 * @param {function(error:*):Stream} f function which returns a new stream
3745 * @param {Stream} stream
3746 * @returns {Stream} new stream which will recover from an error by calling f
3747 */
3748function recoverWith (f, stream) {
3749 return new Stream(new RecoverWith(f, stream.source))
3750}
3751
3752var flatMapError = recoverWith;
3753
3754/**
3755 * Create a stream containing only an error
3756 * @param {*} e error value, preferably an Error or Error subtype
3757 * @returns {Stream} new stream containing only an error
3758 */
3759function throwError$1 (e) {
3760 return new Stream(new ErrorSource(e))
3761}
3762
3763function ErrorSource (e) {
3764 this.value = e;
3765}
3766
3767ErrorSource.prototype.run = function (sink, scheduler) {
3768 return scheduler.asap(new PropagateTask(runError, this.value, sink))
3769};
3770
3771function runError (t, e, sink) {
3772 sink.error(t, e);
3773}
3774
3775function RecoverWith (f, source) {
3776 this.f = f;
3777 this.source = source;
3778}
3779
3780RecoverWith.prototype.run = function (sink, scheduler) {
3781 return new RecoverWithSink(this.f, this.source, sink, scheduler)
3782};
3783
3784function RecoverWithSink (f, source, sink, scheduler) {
3785 this.f = f;
3786 this.sink = new SafeSink(sink);
3787 this.scheduler = scheduler;
3788 this.disposable = source.run(this, scheduler);
3789}
3790
3791RecoverWithSink.prototype.event = function (t, x) {
3792 tryEvent(t, x, this.sink);
3793};
3794
3795RecoverWithSink.prototype.end = function (t, x) {
3796 tryEnd(t, x, this.sink);
3797};
3798
3799RecoverWithSink.prototype.error = function (t, e) {
3800 var nextSink = this.sink.disable();
3801
3802 tryDispose(t, this.disposable, this.sink);
3803 this._startNext(t, e, nextSink);
3804};
3805
3806RecoverWithSink.prototype._startNext = function (t, x, sink) {
3807 try {
3808 this.disposable = this._continue(this.f, x, sink);
3809 } catch (e) {
3810 sink.error(t, e);
3811 }
3812};
3813
3814RecoverWithSink.prototype._continue = function (f, x, sink) {
3815 var stream = f(x);
3816 return stream.source.run(sink, this.scheduler)
3817};
3818
3819RecoverWithSink.prototype.dispose = function () {
3820 return this.disposable.dispose()
3821};
3822
3823var MulticastDisposable = function MulticastDisposable (source, sink) {
3824 this.source = source;
3825 this.sink = sink;
3826 this.disposed = false;
3827};
3828
3829MulticastDisposable.prototype.dispose = function dispose () {
3830 if (this.disposed) {
3831 return
3832 }
3833 this.disposed = true;
3834 var remaining = this.source.remove(this.sink);
3835 return remaining === 0 && this.source._dispose()
3836};
3837
3838function tryEvent$1 (t, x, sink) {
3839 try {
3840 sink.event(t, x);
3841 } catch (e) {
3842 sink.error(t, e);
3843 }
3844}
3845
3846function tryEnd$1 (t, x, sink) {
3847 try {
3848 sink.end(t, x);
3849 } catch (e) {
3850 sink.error(t, e);
3851 }
3852}
3853
3854var dispose = function (disposable) { return disposable.dispose(); };
3855
3856var emptyDisposable = {
3857 dispose: function dispose$1 () {}
3858};
3859
3860var MulticastSource = function MulticastSource (source) {
3861 this.source = source;
3862 this.sinks = [];
3863 this._disposable = emptyDisposable;
3864};
3865
3866MulticastSource.prototype.run = function run (sink, scheduler) {
3867 var n = this.add(sink);
3868 if (n === 1) {
3869 this._disposable = this.source.run(this, scheduler);
3870 }
3871 return new MulticastDisposable(this, sink)
3872};
3873
3874MulticastSource.prototype._dispose = function _dispose () {
3875 var disposable = this._disposable;
3876 this._disposable = emptyDisposable;
3877 return Promise.resolve(disposable).then(dispose)
3878};
3879
3880MulticastSource.prototype.add = function add (sink) {
3881 this.sinks = append(sink, this.sinks);
3882 return this.sinks.length
3883};
3884
3885MulticastSource.prototype.remove = function remove$1 (sink) {
3886 var i = findIndex(sink, this.sinks);
3887 // istanbul ignore next
3888 if (i >= 0) {
3889 this.sinks = remove(i, this.sinks);
3890 }
3891
3892 return this.sinks.length
3893};
3894
3895MulticastSource.prototype.event = function event (time, value) {
3896 var s = this.sinks;
3897 if (s.length === 1) {
3898 return s[0].event(time, value)
3899 }
3900 for (var i = 0; i < s.length; ++i) {
3901 tryEvent$1(time, value, s[i]);
3902 }
3903};
3904
3905MulticastSource.prototype.end = function end (time, value) {
3906 var s = this.sinks;
3907 for (var i = 0; i < s.length; ++i) {
3908 tryEnd$1(time, value, s[i]);
3909 }
3910};
3911
3912MulticastSource.prototype.error = function error (time, err) {
3913 var s = this.sinks;
3914 for (var i = 0; i < s.length; ++i) {
3915 s[i].error(time, err);
3916 }
3917};
3918
3919function multicast (stream) {
3920 var source = stream.source;
3921 return source instanceof MulticastSource
3922 ? stream
3923 : new stream.constructor(new MulticastSource(source))
3924}
3925
3926/** @license MIT License (c) copyright 2010-2016 original author or authors */
3927/** @author Brian Cavalier */
3928/** @author John Hann */
3929
3930// Add of and empty to constructor for fantasy-land compat
3931Stream.of = of;
3932Stream.empty = empty;
3933// Add from to constructor for ES Observable compat
3934Stream.from = from;
3935// -----------------------------------------------------------------------
3936// Draft ES Observable proposal interop
3937// https://github.com/zenparsing/es-observable
3938
3939Stream.prototype.subscribe = function (subscriber) {
3940 return subscribe(subscriber, this)
3941};
3942
3943Stream.prototype[result] = function () {
3944 return this
3945};
3946
3947// -----------------------------------------------------------------------
3948// Fluent adapter
3949
3950/**
3951 * Adapt a functional stream transform to fluent style.
3952 * It applies f to the this stream object
3953 * @param {function(s: Stream): Stream} f function that
3954 * receives the stream itself and must return a new stream
3955 * @return {Stream}
3956 */
3957Stream.prototype.thru = function (f) {
3958 return thru(f, this)
3959};
3960
3961// -----------------------------------------------------------------------
3962// Observing
3963
3964/**
3965 * Process all the events in the stream
3966 * @returns {Promise} promise that fulfills when the stream ends, or rejects
3967 * if the stream fails with an unhandled error.
3968 */
3969Stream.prototype.observe = Stream.prototype.forEach = function (f) {
3970 return observe(f, this)
3971};
3972
3973/**
3974 * Consume all events in the stream, without providing a function to process each.
3975 * This causes a stream to become active and begin emitting events, and is useful
3976 * in cases where all processing has been setup upstream via other combinators, and
3977 * there is no need to process the terminal events.
3978 * @returns {Promise} promise that fulfills when the stream ends, or rejects
3979 * if the stream fails with an unhandled error.
3980 */
3981Stream.prototype.drain = function () {
3982 return drain(this)
3983};
3984
3985// -------------------------------------------------------
3986
3987/**
3988 * Generalized feedback loop. Call a stepper function for each event. The stepper
3989 * will be called with 2 params: the current seed and the an event value. It must
3990 * return a new { seed, value } pair. The `seed` will be fed back into the next
3991 * invocation of stepper, and the `value` will be propagated as the event value.
3992 * @param {function(seed:*, value:*):{seed:*, value:*}} stepper loop step function
3993 * @param {*} seed initial seed value passed to first stepper call
3994 * @returns {Stream} new stream whose values are the `value` field of the objects
3995 * returned by the stepper
3996 */
3997Stream.prototype.loop = function (stepper, seed) {
3998 return loop(stepper, seed, this)
3999};
4000
4001// -------------------------------------------------------
4002
4003/**
4004 * Create a stream containing successive reduce results of applying f to
4005 * the previous reduce result and the current stream item.
4006 * @param {function(result:*, x:*):*} f reducer function
4007 * @param {*} initial initial value
4008 * @returns {Stream} new stream containing successive reduce results
4009 */
4010Stream.prototype.scan = function (f, initial) {
4011 return scan(f, initial, this)
4012};
4013
4014/**
4015 * Reduce the stream to produce a single result. Note that reducing an infinite
4016 * stream will return a Promise that never fulfills, but that may reject if an error
4017 * occurs.
4018 * @param {function(result:*, x:*):*} f reducer function
4019 * @param {*} initial optional initial value
4020 * @returns {Promise} promise for the file result of the reduce
4021 */
4022Stream.prototype.reduce = function (f, initial) {
4023 return reduce$1(f, initial, this)
4024};
4025
4026/**
4027 * @param {Stream} tail
4028 * @returns {Stream} new stream containing all items in this followed by
4029 * all items in tail
4030 */
4031Stream.prototype.concat = function (tail$$1) {
4032 return concat(this, tail$$1)
4033};
4034
4035/**
4036 * @param {*} x value to prepend
4037 * @returns {Stream} a new stream with x prepended
4038 */
4039Stream.prototype.startWith = function (x) {
4040 return cons$1(x, this)
4041};
4042
4043// -----------------------------------------------------------------------
4044// Transforming
4045
4046/**
4047 * Transform each value in the stream by applying f to each
4048 * @param {function(*):*} f mapping function
4049 * @returns {Stream} stream containing items transformed by f
4050 */
4051Stream.prototype.map = function (f) {
4052 return map$2(f, this)
4053};
4054
4055/**
4056 * Assume this stream contains functions, and apply each function to each item
4057 * in the provided stream. This generates, in effect, a cross product.
4058 * @param {Stream} xs stream of items to which
4059 * @returns {Stream} stream containing the cross product of items
4060 */
4061Stream.prototype.ap = function (xs) {
4062 return ap(this, xs)
4063};
4064
4065/**
4066 * Replace each value in the stream with x
4067 * @param {*} x
4068 * @returns {Stream} stream containing items replaced with x
4069 */
4070Stream.prototype.constant = function (x) {
4071 return constant(x, this)
4072};
4073
4074/**
4075 * Perform a side effect for each item in the stream
4076 * @param {function(x:*):*} f side effect to execute for each item. The
4077 * return value will be discarded.
4078 * @returns {Stream} new stream containing the same items as this stream
4079 */
4080Stream.prototype.tap = function (f) {
4081 return tap(f, this)
4082};
4083
4084// -----------------------------------------------------------------------
4085// Transducer support
4086
4087/**
4088 * Transform this stream by passing its events through a transducer.
4089 * @param {function} transducer transducer function
4090 * @return {Stream} stream of events transformed by the transducer
4091 */
4092Stream.prototype.transduce = function (transducer) {
4093 return transduce(transducer, this)
4094};
4095
4096// -----------------------------------------------------------------------
4097// FlatMapping
4098
4099/**
4100 * Map each value in the stream to a new stream, and merge it into the
4101 * returned outer stream. Event arrival times are preserved.
4102 * @param {function(x:*):Stream} f chaining function, must return a Stream
4103 * @returns {Stream} new stream containing all events from each stream returned by f
4104 */
4105Stream.prototype.chain = function (f) {
4106 return flatMap(f, this)
4107};
4108
4109// @deprecated use chain instead
4110Stream.prototype.flatMap = Stream.prototype.chain;
4111
4112 /**
4113 * Monadic join. Flatten a Stream<Stream<X>> to Stream<X> by merging inner
4114 * streams to the outer. Event arrival times are preserved.
4115 * @returns {Stream<X>} new stream containing all events of all inner streams
4116 */
4117Stream.prototype.join = function () {
4118 return join(this)
4119};
4120
4121/**
4122 * Map the end event to a new stream, and begin emitting its values.
4123 * @param {function(x:*):Stream} f function that receives the end event value,
4124 * and *must* return a new Stream to continue with.
4125 * @returns {Stream} new stream that emits all events from the original stream,
4126 * followed by all events from the stream returned by f.
4127 */
4128Stream.prototype.continueWith = function (f) {
4129 return continueWith(f, this)
4130};
4131
4132// @deprecated use continueWith instead
4133Stream.prototype.flatMapEnd = Stream.prototype.continueWith;
4134
4135Stream.prototype.concatMap = function (f) {
4136 return concatMap(f, this)
4137};
4138
4139// -----------------------------------------------------------------------
4140// Concurrent merging
4141
4142/**
4143 * Flatten a Stream<Stream<X>> to Stream<X> by merging inner
4144 * streams to the outer, limiting the number of inner streams that may
4145 * be active concurrently.
4146 * @param {number} concurrency at most this many inner streams will be
4147 * allowed to be active concurrently.
4148 * @return {Stream<X>} new stream containing all events of all inner
4149 * streams, with limited concurrency.
4150 */
4151Stream.prototype.mergeConcurrently = function (concurrency) {
4152 return mergeConcurrently(concurrency, this)
4153};
4154
4155// -----------------------------------------------------------------------
4156// Merging
4157
4158/**
4159 * Merge this stream and all the provided streams
4160 * @returns {Stream} stream containing items from this stream and s in time
4161 * order. If two events are simultaneous they will be merged in
4162 * arbitrary order.
4163 */
4164Stream.prototype.merge = function (/* ...streams*/) {
4165 return mergeArray(cons(this, arguments))
4166};
4167
4168// -----------------------------------------------------------------------
4169// Combining
4170
4171/**
4172 * Combine latest events from all input streams
4173 * @param {function(...events):*} f function to combine most recent events
4174 * @returns {Stream} stream containing the result of applying f to the most recent
4175 * event of each input stream, whenever a new event arrives on any stream.
4176 */
4177Stream.prototype.combine = function (f /*, ...streams*/) {
4178 return combineArray(f, replace(this, 0, arguments))
4179};
4180
4181// -----------------------------------------------------------------------
4182// Sampling
4183
4184/**
4185 * When an event arrives on sampler, emit the latest event value from stream.
4186 * @param {Stream} sampler stream of events at whose arrival time
4187 * signal's latest value will be propagated
4188 * @returns {Stream} sampled stream of values
4189 */
4190Stream.prototype.sampleWith = function (sampler) {
4191 return sampleWith(sampler, this)
4192};
4193
4194/**
4195 * When an event arrives on this stream, emit the result of calling f with the latest
4196 * values of all streams being sampled
4197 * @param {function(...values):*} f function to apply to each set of sampled values
4198 * @returns {Stream} stream of sampled and transformed values
4199 */
4200Stream.prototype.sample = function (f /* ...streams */) {
4201 return sampleArray(f, this, tail(arguments))
4202};
4203
4204// -----------------------------------------------------------------------
4205// Zipping
4206
4207/**
4208 * Pair-wise combine items with those in s. Given 2 streams:
4209 * [1,2,3] zipWith f [4,5,6] -> [f(1,4),f(2,5),f(3,6)]
4210 * Note: zip causes fast streams to buffer and wait for slow streams.
4211 * @param {function(a:Stream, b:Stream, ...):*} f function to combine items
4212 * @returns {Stream} new stream containing pairs
4213 */
4214Stream.prototype.zip = function (f /*, ...streams*/) {
4215 return zipArray(f, replace(this, 0, arguments))
4216};
4217
4218// -----------------------------------------------------------------------
4219// Switching
4220
4221/**
4222 * Given a stream of streams, return a new stream that adopts the behavior
4223 * of the most recent inner stream.
4224 * @returns {Stream} switching stream
4225 */
4226Stream.prototype.switchLatest = function () {
4227 return switchLatest(this)
4228};
4229
4230// @deprecated use switchLatest instead
4231Stream.prototype.switch = Stream.prototype.switchLatest;
4232
4233// -----------------------------------------------------------------------
4234// Filtering
4235
4236/**
4237 * Retain only items matching a predicate
4238 * stream: -12345678-
4239 * filter(x => x % 2 === 0, stream): --2-4-6-8-
4240 * @param {function(x:*):boolean} p filtering predicate called for each item
4241 * @returns {Stream} stream containing only items for which predicate returns truthy
4242 */
4243Stream.prototype.filter = function (p) {
4244 return filter(p, this)
4245};
4246
4247/**
4248 * Skip repeated events, using === to compare items
4249 * stream: -abbcd-
4250 * distinct(stream): -ab-cd-
4251 * @returns {Stream} stream with no repeated events
4252 */
4253Stream.prototype.skipRepeats = function () {
4254 return skipRepeats(this)
4255};
4256
4257/**
4258 * Skip repeated events, using supplied equals function to compare items
4259 * @param {function(a:*, b:*):boolean} equals function to compare items
4260 * @returns {Stream} stream with no repeated events
4261 */
4262Stream.prototype.skipRepeatsWith = function (equals) {
4263 return skipRepeatsWith(equals, this)
4264};
4265
4266// -----------------------------------------------------------------------
4267// Slicing
4268
4269/**
4270 * stream: -abcd-
4271 * take(2, stream): -ab|
4272 * @param {Number} n take up to this many events
4273 * @returns {Stream} stream containing at most the first n items from this stream
4274 */
4275Stream.prototype.take = function (n) {
4276 return take(n, this)
4277};
4278
4279/**
4280 * stream: -abcd->
4281 * skip(2, stream): ---cd->
4282 * @param {Number} n skip this many events
4283 * @returns {Stream} stream not containing the first n events
4284 */
4285Stream.prototype.skip = function (n) {
4286 return skip(n, this)
4287};
4288
4289/**
4290 * Slice a stream by event index. Equivalent to, but more efficient than
4291 * stream.take(end).skip(start);
4292 * NOTE: Negative start and end are not supported
4293 * @param {Number} start skip all events before the start index
4294 * @param {Number} end allow all events from the start index to the end index
4295 * @returns {Stream} stream containing items where start <= index < end
4296 */
4297Stream.prototype.slice = function (start, end) {
4298 return slice(start, end, this)
4299};
4300
4301/**
4302 * stream: -123451234->
4303 * takeWhile(x => x < 5, stream): -1234|
4304 * @param {function(x:*):boolean} p predicate
4305 * @returns {Stream} stream containing items up to, but not including, the
4306 * first item for which p returns falsy.
4307 */
4308Stream.prototype.takeWhile = function (p) {
4309 return takeWhile(p, this)
4310};
4311
4312/**
4313 * stream: -123451234->
4314 * skipWhile(x => x < 5, stream): -----51234->
4315 * @param {function(x:*):boolean} p predicate
4316 * @returns {Stream} stream containing items following *and including* the
4317 * first item for which p returns falsy.
4318 */
4319Stream.prototype.skipWhile = function (p) {
4320 return skipWhile(p, this)
4321};
4322
4323/**
4324 * stream: -123456789->
4325 * skipAfter(x => x === 5, stream):-12345|
4326 * @param {function(x:*):boolean} p predicate
4327 * @returns {Stream} stream containing items up to, *and including*, the
4328 * first item for which p returns truthy.
4329 */
4330Stream.prototype.skipAfter = function (p) {
4331 return skipAfter(p, this)
4332};
4333
4334// -----------------------------------------------------------------------
4335// Time slicing
4336
4337/**
4338 * stream: -a-b-c-d-e-f-g->
4339 * signal: -------x
4340 * takeUntil(signal, stream): -a-b-c-|
4341 * @param {Stream} signal retain only events in stream before the first
4342 * event in signal
4343 * @returns {Stream} new stream containing only events that occur before
4344 * the first event in signal.
4345 */
4346Stream.prototype.until = function (signal) {
4347 return takeUntil(signal, this)
4348};
4349
4350// @deprecated use until instead
4351Stream.prototype.takeUntil = Stream.prototype.until;
4352
4353 /**
4354 * stream: -a-b-c-d-e-f-g->
4355 * signal: -------x
4356 * takeUntil(signal, stream): -------d-e-f-g->
4357 * @param {Stream} signal retain only events in stream at or after the first
4358 * event in signal
4359 * @returns {Stream} new stream containing only events that occur after
4360 * the first event in signal.
4361 */
4362Stream.prototype.since = function (signal) {
4363 return skipUntil(signal, this)
4364};
4365
4366// @deprecated use since instead
4367Stream.prototype.skipUntil = Stream.prototype.since;
4368
4369 /**
4370 * stream: -a-b-c-d-e-f-g->
4371 * timeWindow: -----s
4372 * s: -----t
4373 * stream.during(timeWindow): -----c-d-e-|
4374 * @param {Stream<Stream>} timeWindow a stream whose first event (s) represents
4375 * the window start time. That event (s) is itself a stream whose first event (t)
4376 * represents the window end time
4377 * @returns {Stream} new stream containing only events within the provided timespan
4378 */
4379Stream.prototype.during = function (timeWindow) {
4380 return during(timeWindow, this)
4381};
4382
4383// -----------------------------------------------------------------------
4384// Delaying
4385
4386/**
4387 * @param {Number} delayTime milliseconds to delay each item
4388 * @returns {Stream} new stream containing the same items, but delayed by ms
4389 */
4390Stream.prototype.delay = function (delayTime) {
4391 return delay(delayTime, this)
4392};
4393
4394// -----------------------------------------------------------------------
4395// Getting event timestamp
4396
4397/**
4398 * Expose event timestamps into the stream. Turns a Stream<X> into
4399 * Stream<{time:t, value:X}>
4400 * @returns {Stream<{time:number, value:*}>}
4401 */
4402Stream.prototype.timestamp = function () {
4403 return timestamp(this)
4404};
4405
4406// -----------------------------------------------------------------------
4407// Rate limiting
4408
4409/**
4410 * Limit the rate of events
4411 * stream: abcd----abcd----
4412 * throttle(2, stream): a-c-----a-c-----
4413 * @param {Number} period time to suppress events
4414 * @returns {Stream} new stream that skips events for throttle period
4415 */
4416Stream.prototype.throttle = function (period) {
4417 return throttle(period, this)
4418};
4419
4420/**
4421 * Wait for a burst of events to subside and emit only the last event in the burst
4422 * stream: abcd----abcd----
4423 * debounce(2, stream): -----d-------d--
4424 * @param {Number} period events occuring more frequently than this
4425 * on the provided scheduler will be suppressed
4426 * @returns {Stream} new debounced stream
4427 */
4428Stream.prototype.debounce = function (period) {
4429 return debounce(period, this)
4430};
4431
4432// -----------------------------------------------------------------------
4433// Awaiting Promises
4434
4435/**
4436 * Await promises, turning a Stream<Promise<X>> into Stream<X>. Preserves
4437 * event order, but timeshifts events based on promise resolution time.
4438 * @returns {Stream<X>} stream containing non-promise values
4439 */
4440Stream.prototype.awaitPromises = function () {
4441 return awaitPromises(this)
4442};
4443
4444// @deprecated use awaitPromises instead
4445Stream.prototype.await = Stream.prototype.awaitPromises;
4446
4447// -----------------------------------------------------------------------
4448// Error handling
4449
4450/**
4451 * If this stream encounters an error, recover and continue with items from stream
4452 * returned by f.
4453 * stream: -a-b-c-X-
4454 * f(X): d-e-f-g-
4455 * flatMapError(f, stream): -a-b-c-d-e-f-g-
4456 * @param {function(error:*):Stream} f function which returns a new stream
4457 * @returns {Stream} new stream which will recover from an error by calling f
4458 */
4459Stream.prototype.recoverWith = function (f) {
4460 return flatMapError(f, this)
4461};
4462
4463// @deprecated use recoverWith instead
4464Stream.prototype.flatMapError = Stream.prototype.recoverWith;
4465
4466// -----------------------------------------------------------------------
4467// Multicasting
4468
4469/**
4470 * Transform the stream into multicast stream. That means that many subscribers
4471 * to the stream will not cause multiple invocations of the internal machinery.
4472 * @returns {Stream} new stream which will multicast events to all observers.
4473 */
4474Stream.prototype.multicast = function () {
4475 return multicast(this)
4476};
4477
4478// export the instance of the defaultScheduler for third-party libraries
4479// export an implementation of Task used internally for third-party libraries
4480
4481exports.Stream = Stream;
4482exports.of = of;
4483exports.just = of;
4484exports.empty = empty;
4485exports.never = never;
4486exports.from = from;
4487exports.periodic = periodic;
4488exports.observe = observe;
4489exports.forEach = observe;
4490exports.drain = drain;
4491exports.loop = loop;
4492exports.scan = scan;
4493exports.reduce = reduce$1;
4494exports.concat = concat;
4495exports.startWith = cons$1;
4496exports.map = map$2;
4497exports.constant = constant;
4498exports.tap = tap;
4499exports.ap = ap;
4500exports.transduce = transduce;
4501exports.flatMap = flatMap;
4502exports.chain = flatMap;
4503exports.join = join;
4504exports.continueWith = continueWith;
4505exports.flatMapEnd = continueWith;
4506exports.concatMap = concatMap;
4507exports.mergeConcurrently = mergeConcurrently;
4508exports.merge = merge;
4509exports.mergeArray = mergeArray;
4510exports.combine = combine;
4511exports.combineArray = combineArray;
4512exports.sample = sample;
4513exports.sampleArray = sampleArray;
4514exports.sampleWith = sampleWith;
4515exports.zip = zip;
4516exports.zipArray = zipArray;
4517exports.switchLatest = switchLatest;
4518exports.switch = switchLatest;
4519exports.filter = filter;
4520exports.skipRepeats = skipRepeats;
4521exports.distinct = skipRepeats;
4522exports.skipRepeatsWith = skipRepeatsWith;
4523exports.distinctBy = skipRepeatsWith;
4524exports.take = take;
4525exports.skip = skip;
4526exports.slice = slice;
4527exports.takeWhile = takeWhile;
4528exports.skipWhile = skipWhile;
4529exports.skipAfter = skipAfter;
4530exports.takeUntil = takeUntil;
4531exports.until = takeUntil;
4532exports.skipUntil = skipUntil;
4533exports.since = skipUntil;
4534exports.during = during;
4535exports.delay = delay;
4536exports.timestamp = timestamp;
4537exports.throttle = throttle;
4538exports.debounce = debounce;
4539exports.fromPromise = fromPromise;
4540exports.awaitPromises = awaitPromises;
4541exports.await = awaitPromises;
4542exports.recoverWith = recoverWith;
4543exports.flatMapError = flatMapError;
4544exports.throwError = throwError$1;
4545exports.multicast = multicast;
4546exports.defaultScheduler = defaultScheduler;
4547exports.PropagateTask = PropagateTask;
4548exports.fromEvent = fromEvent;
4549exports.unfold = unfold;
4550exports.iterate = iterate;
4551exports.generate = generate;
4552
4553Object.defineProperty(exports, '__esModule', { value: true });
4554
4555})));
4556//# sourceMappingURL=most.js.map