diff --git a/ajax/libs/rxjs/2.3.9/rx.aggregates.js b/ajax/libs/rxjs/2.3.9/rx.aggregates.js new file mode 100644 index 000000000..cd9225857 --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.aggregates.js @@ -0,0 +1,790 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // References + var Observable = Rx.Observable, + observableProto = Observable.prototype, + CompositeDisposable = Rx.CompositeDisposable, + AnonymousObservable = Rx.AnonymousObservable, + isEqual = Rx.internals.isEqual, + helpers = Rx.helpers, + not = helpers.not, + defaultComparer = helpers.defaultComparer, + identity = helpers.identity, + defaultSubComparer = helpers.defaultSubComparer, + isPromise = helpers.isPromise, + observableFromPromise = Observable.fromPromise; + + // Defaults + var argumentOutOfRange = 'Argument out of range', + sequenceContainsNoElements = "Sequence contains no elements."; + + observableProto.finalValue = function () { + var source = this; + return new AnonymousObservable(function (observer) { + var hasValue = false, value; + return source.subscribe(function (x) { + hasValue = true; + value = x; + }, observer.onError.bind(observer), function () { + if (!hasValue) { + observer.onError(new Error(sequenceContainsNoElements)); + } else { + observer.onNext(value); + observer.onCompleted(); + } + }); + }); + }; + + function extremaBy(source, keySelector, comparer) { + return new AnonymousObservable(function (observer) { + var hasValue = false, lastKey = null, list = []; + return source.subscribe(function (x) { + var comparison, key; + try { + key = keySelector(x); + } catch (ex) { + observer.onError(ex); + return; + } + comparison = 0; + if (!hasValue) { + hasValue = true; + lastKey = key; + } else { + try { + comparison = comparer(key, lastKey); + } catch (ex1) { + observer.onError(ex1); + return; + } + } + if (comparison > 0) { + lastKey = key; + list = []; + } + if (comparison >= 0) { + list.push(x); + } + }, observer.onError.bind(observer), function () { + observer.onNext(list); + observer.onCompleted(); + }); + }); + } + + function firstOnly(x) { + if (x.length === 0) { + throw new Error(sequenceContainsNoElements); + } + return x[0]; + } + + /** + * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. + * For aggregation behavior with incremental intermediate results, see Observable.scan. + * @example + * 1 - res = source.aggregate(function (acc, x) { return acc + x; }); + * 2 - res = source.aggregate(0, function (acc, x) { return acc + x; }); + * @param {Mixed} [seed] The initial accumulator value. + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @returns {Observable} An observable sequence containing a single element with the final accumulator value. + */ + observableProto.aggregate = function () { + var seed, hasSeed, accumulator; + if (arguments.length === 2) { + seed = arguments[0]; + hasSeed = true; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); + }; + + /** + * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. + * For aggregation behavior with incremental intermediate results, see Observable.scan. + * @example + * 1 - res = source.reduce(function (acc, x) { return acc + x; }); + * 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0); + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @param {Any} [seed] The initial accumulator value. + * @returns {Observable} An observable sequence containing a single element with the final accumulator value. + */ + observableProto.reduce = function (accumulator) { + var seed, hasSeed; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[1]; + } + return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); + }; + + /** + * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. + * @example + * var result = source.any(); + * var result = source.any(function (x) { return x > 3; }); + * @param {Function} [predicate] A function to test each element for a condition. + * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. + */ + observableProto.some = observableProto.any = function (predicate, thisArg) { + var source = this; + return predicate ? + source.where(predicate, thisArg).any() : + new AnonymousObservable(function (observer) { + return source.subscribe(function () { + observer.onNext(true); + observer.onCompleted(); + }, observer.onError.bind(observer), function () { + observer.onNext(false); + observer.onCompleted(); + }); + }); + }; + + /** + * Determines whether an observable sequence is empty. + * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. + */ + observableProto.isEmpty = function () { + return this.any().map(not); + }; + + /** + * Determines whether all elements of an observable sequence satisfy a condition. + * + * 1 - res = source.all(function (value) { return value.length > 3; }); + * @memberOf Observable# + * @param {Function} [predicate] A function to test each element for a condition. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. + */ + observableProto.every = observableProto.all = function (predicate, thisArg) { + return this.where(function (v) { + return !predicate(v); + }, thisArg).any().select(function (b) { + return !b; + }); + }; + + /** + * Determines whether an observable sequence contains a specified element with an optional equality comparer. + * @example + * 1 - res = source.contains(42); + * 2 - res = source.contains({ value: 42 }, function (x, y) { return x.value === y.value; }); + * @param value The value to locate in the source sequence. + * @param {Function} [comparer] An equality comparer to compare elements. + * @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value. + */ + observableProto.contains = function (value, comparer) { + comparer || (comparer = defaultComparer); + return this.where(function (v) { + return comparer(v, value); + }).any(); + }; + + /** + * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. + * @example + * res = source.count(); + * res = source.count(function (x) { return x > 3; }); + * @param {Function} [predicate]A function to test each element for a condition. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. + */ + observableProto.count = function (predicate, thisArg) { + return predicate ? + this.where(predicate, thisArg).count() : + this.aggregate(0, function (count) { + return count + 1; + }); + }; + + /** + * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. + * @example + * var res = source.sum(); + * var res = source.sum(function (x) { return x.value; }); + * @param {Function} [selector] A transform function to apply to each element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. + */ + observableProto.sum = function (keySelector, thisArg) { + return keySelector ? + this.select(keySelector, thisArg).sum() : + this.aggregate(0, function (prev, curr) { + return prev + curr; + }); + }; + + /** + * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. + * @example + * var res = source.minBy(function (x) { return x.value; }); + * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); + * @param {Function} keySelector Key selector function. + * @param {Function} [comparer] Comparer used to compare key values. + * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. + */ + observableProto.minBy = function (keySelector, comparer) { + comparer || (comparer = defaultSubComparer); + return extremaBy(this, keySelector, function (x, y) { + return comparer(x, y) * -1; + }); + }; + + /** + * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. + * @example + * var res = source.min(); + * var res = source.min(function (x, y) { return x.value - y.value; }); + * @param {Function} [comparer] Comparer used to compare elements. + * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. + */ + observableProto.min = function (comparer) { + return this.minBy(identity, comparer).select(function (x) { + return firstOnly(x); + }); + }; + + /** + * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. + * @example + * var res = source.maxBy(function (x) { return x.value; }); + * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); + * @param {Function} keySelector Key selector function. + * @param {Function} [comparer] Comparer used to compare key values. + * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. + */ + observableProto.maxBy = function (keySelector, comparer) { + comparer || (comparer = defaultSubComparer); + return extremaBy(this, keySelector, comparer); + }; + + /** + * Returns the maximum value in an observable sequence according to the specified comparer. + * @example + * var res = source.max(); + * var res = source.max(function (x, y) { return x.value - y.value; }); + * @param {Function} [comparer] Comparer used to compare elements. + * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. + */ + observableProto.max = function (comparer) { + return this.maxBy(identity, comparer).select(function (x) { + return firstOnly(x); + }); + }; + + /** + * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. + * @example + * var res = res = source.average(); + * var res = res = source.average(function (x) { return x.value; }); + * @param {Function} [selector] A transform function to apply to each element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. + */ + observableProto.average = function (keySelector, thisArg) { + return keySelector ? + this.select(keySelector, thisArg).average() : + this.scan({ + sum: 0, + count: 0 + }, function (prev, cur) { + return { + sum: prev.sum + cur, + count: prev.count + 1 + }; + }).finalValue().select(function (s) { + if (s.count === 0) { + throw new Error('The input sequence was empty'); + } + return s.sum / s.count; + }); + }; + + function sequenceEqualArray(first, second, comparer) { + return new AnonymousObservable(function (observer) { + var count = 0, len = second.length; + return first.subscribe(function (value) { + var equal = false; + try { + if (count < len) { + equal = comparer(value, second[count++]); + } + } catch (e) { + observer.onError(e); + return; + } + if (!equal) { + observer.onNext(false); + observer.onCompleted(); + } + }, observer.onError.bind(observer), function () { + observer.onNext(count === len); + observer.onCompleted(); + }); + }); + } + + /** + * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. + * + * @example + * var res = res = source.sequenceEqual([1,2,3]); + * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); + * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); + * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); + * @param {Observable} second Second observable sequence or array to compare. + * @param {Function} [comparer] Comparer used to compare elements of both sequences. + * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. + */ + observableProto.sequenceEqual = function (second, comparer) { + var first = this; + comparer || (comparer = defaultComparer); + if (Array.isArray(second)) { + return sequenceEqualArray(first, second, comparer); + } + return new AnonymousObservable(function (observer) { + var donel = false, doner = false, ql = [], qr = []; + var subscription1 = first.subscribe(function (x) { + var equal, v; + if (qr.length > 0) { + v = qr.shift(); + try { + equal = comparer(v, x); + } catch (e) { + observer.onError(e); + return; + } + if (!equal) { + observer.onNext(false); + observer.onCompleted(); + } + } else if (doner) { + observer.onNext(false); + observer.onCompleted(); + } else { + ql.push(x); + } + }, observer.onError.bind(observer), function () { + donel = true; + if (ql.length === 0) { + if (qr.length > 0) { + observer.onNext(false); + observer.onCompleted(); + } else if (doner) { + observer.onNext(true); + observer.onCompleted(); + } + } + }); + + isPromise(second) && (second = observableFromPromise(second)); + var subscription2 = second.subscribe(function (x) { + var equal, v; + if (ql.length > 0) { + v = ql.shift(); + try { + equal = comparer(v, x); + } catch (exception) { + observer.onError(exception); + return; + } + if (!equal) { + observer.onNext(false); + observer.onCompleted(); + } + } else if (donel) { + observer.onNext(false); + observer.onCompleted(); + } else { + qr.push(x); + } + }, observer.onError.bind(observer), function () { + doner = true; + if (qr.length === 0) { + if (ql.length > 0) { + observer.onNext(false); + observer.onCompleted(); + } else if (donel) { + observer.onNext(true); + observer.onCompleted(); + } + } + }); + return new CompositeDisposable(subscription1, subscription2); + }); + }; + + function elementAtOrDefault(source, index, hasDefault, defaultValue) { + if (index < 0) { + throw new Error(argumentOutOfRange); + } + return new AnonymousObservable(function (observer) { + var i = index; + return source.subscribe(function (x) { + if (i === 0) { + observer.onNext(x); + observer.onCompleted(); + } + i--; + }, observer.onError.bind(observer), function () { + if (!hasDefault) { + observer.onError(new Error(argumentOutOfRange)); + } else { + observer.onNext(defaultValue); + observer.onCompleted(); + } + }); + }); + } + + /** + * Returns the element at a specified index in a sequence. + * @example + * var res = source.elementAt(5); + * @param {Number} index The zero-based index of the element to retrieve. + * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. + */ + observableProto.elementAt = function (index) { + return elementAtOrDefault(this, index, false); + }; + + /** + * Returns the element at a specified index in a sequence or a default value if the index is out of range. + * @example + * var res = source.elementAtOrDefault(5); + * var res = source.elementAtOrDefault(5, 0); + * @param {Number} index The zero-based index of the element to retrieve. + * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. + * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. + */ + observableProto.elementAtOrDefault = function (index, defaultValue) { + return elementAtOrDefault(this, index, true, defaultValue); + }; + + function singleOrDefaultAsync(source, hasDefault, defaultValue) { + return new AnonymousObservable(function (observer) { + var value = defaultValue, seenValue = false; + return source.subscribe(function (x) { + if (seenValue) { + observer.onError(new Error('Sequence contains more than one element')); + } else { + value = x; + seenValue = true; + } + }, observer.onError.bind(observer), function () { + if (!seenValue && !hasDefault) { + observer.onError(new Error(sequenceContainsNoElements)); + } else { + observer.onNext(value); + observer.onCompleted(); + } + }); + }); + } + + /** + * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. + * @example + * var res = res = source.single(); + * var res = res = source.single(function (x) { return x === 42; }); + * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. + */ + observableProto.single = function (predicate, thisArg) { + return predicate ? + this.where(predicate, thisArg).single() : + singleOrDefaultAsync(this, false); + }; + + /** + * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. + * @example + * var res = res = source.singleOrDefault(); + * var res = res = source.singleOrDefault(function (x) { return x === 42; }); + * res = source.singleOrDefault(function (x) { return x === 42; }, 0); + * res = source.singleOrDefault(null, 0); + * @memberOf Observable# + * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. + * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. + */ + observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { + return predicate? + this.where(predicate, thisArg).singleOrDefault(null, defaultValue) : + singleOrDefaultAsync(this, true, defaultValue) + }; + function firstOrDefaultAsync(source, hasDefault, defaultValue) { + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + observer.onNext(x); + observer.onCompleted(); + }, observer.onError.bind(observer), function () { + if (!hasDefault) { + observer.onError(new Error(sequenceContainsNoElements)); + } else { + observer.onNext(defaultValue); + observer.onCompleted(); + } + }); + }); + } + + /** + * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. + * @example + * var res = res = source.first(); + * var res = res = source.first(function (x) { return x > 3; }); + * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. + */ + observableProto.first = function (predicate, thisArg) { + return predicate ? + this.where(predicate, thisArg).first() : + firstOrDefaultAsync(this, false); + }; + + /** + * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. + * @example + * var res = res = source.firstOrDefault(); + * var res = res = source.firstOrDefault(function (x) { return x > 3; }); + * var res = source.firstOrDefault(function (x) { return x > 3; }, 0); + * var res = source.firstOrDefault(null, 0); + * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. + * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. + */ + observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { + return predicate ? + this.where(predicate).firstOrDefault(null, defaultValue) : + firstOrDefaultAsync(this, true, defaultValue); + }; + + function lastOrDefaultAsync(source, hasDefault, defaultValue) { + return new AnonymousObservable(function (observer) { + var value = defaultValue, seenValue = false; + return source.subscribe(function (x) { + value = x; + seenValue = true; + }, observer.onError.bind(observer), function () { + if (!seenValue && !hasDefault) { + observer.onError(new Error(sequenceContainsNoElements)); + } else { + observer.onNext(value); + observer.onCompleted(); + } + }); + }); + } + + /** + * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. + * @example + * var res = source.last(); + * var res = source.last(function (x) { return x > 3; }); + * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. + */ + observableProto.last = function (predicate, thisArg) { + return predicate ? + this.where(predicate, thisArg).last() : + lastOrDefaultAsync(this, false); + }; + + /** + * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. + * @example + * var res = source.lastOrDefault(); + * var res = source.lastOrDefault(function (x) { return x > 3; }); + * var res = source.lastOrDefault(function (x) { return x > 3; }, 0); + * var res = source.lastOrDefault(null, 0); + * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. + * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. + */ + observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { + return predicate ? + this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : + lastOrDefaultAsync(this, true, defaultValue); + }; + + function findValue (source, predicate, thisArg, yieldIndex) { + return new AnonymousObservable(function (observer) { + var i = 0; + return source.subscribe(function (x) { + var shouldRun; + try { + shouldRun = predicate.call(thisArg, x, i, source); + } catch(e) { + observer.onError(e); + return; + } + if (shouldRun) { + observer.onNext(yieldIndex ? i : x); + observer.onCompleted(); + } else { + i++; + } + }, observer.onError.bind(observer), function () { + observer.onNext(yieldIndex ? -1 : undefined); + observer.onCompleted(); + }); + }); + } + + /** + * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. + * @param {Function} predicate The predicate that defines the conditions of the element to search for. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. + */ + observableProto.find = function (predicate, thisArg) { + return findValue(this, predicate, thisArg, false); + }; + + /** + * Searches for an element that matches the conditions defined by the specified predicate, and returns + * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. + * @param {Function} predicate The predicate that defines the conditions of the element to search for. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. + */ + observableProto.findIndex = function (predicate, thisArg) { + return findValue(this, predicate, thisArg, true); + }; + + function toSet(source, type) { + return new AnonymousObservable(function (observer) { + var s = new type(); + return source.subscribe( + s.add.bind(s), + observer.onError.bind(observer), + function () { + observer.onNext(s); + observer.onCompleted(); + }); + }); + } + if (!!root.Set) { + /** + * Converts the observable sequence to a Set if it exists. + * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence. + */ + observableProto.toSet = function () { + return toSet(this, root.Set); + }; + } + + if (!!root.WeakSet) { + /** + * Converts the observable sequence to a WeakSet if it exists. + * @returns {Observable} An observable sequence with a single value of a WeakSet containing the values from the observable sequence. + */ + observableProto.toWeakSet = function () { + return toSet(this, root.WeakSet); + }; + } + + function toMap(source, type, keySelector, elementSelector) { + return new AnonymousObservable(function (observer) { + var m = new type(); + return source.subscribe( + function (x) { + var key; + try { + key = keySelector(x); + } catch (e) { + observer.onError(e); + return; + } + + var element = x; + if (elementSelector) { + try { + element = elementSelector(x); + } catch (e) { + observer.onError(e); + return; + } + } + + m.set(key, element); + }, + observer.onError.bind(observer), + function () { + observer.onNext(m); + observer.onCompleted(); + }); + }); + } + + if (!!root.Map) { + /** + * Converts the observable sequence to a Map if it exists. + * @param {Function} keySelector A function which produces the key for the Map. + * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence. + * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence. + */ + observableProto.toMap = function (keySelector, elementSelector) { + return toMap(this, root.Map, keySelector, elementSelector); + }; + } + + if (!!root.WeakMap) { + /** + * Converts the observable sequence to a WeakMap if it exists. + * @param {Function} keySelector A function which produces the key for the WeakMap + * @param {Function} [elementSelector] An optional function which produces the element for the WeakMap. If not present, defaults to the value from the observable sequence. + * @returns {Observable} An observable sequence with a single value of a WeakMap containing the values from the observable sequence. + */ + observableProto.toWeakMap = function (keySelector, elementSelector) { + return toMap(this, root.WeakMap, keySelector, elementSelector); + }; + } + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.aggregates.min.js b/ajax/libs/rxjs/2.3.9/rx.aggregates.min.js new file mode 100644 index 000000000..4c1bb4dff --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.aggregates.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c,d){function e(a,b,c){return new r(function(d){var e=!1,f=null,g=[];return a.subscribe(function(a){var h,i;try{i=b(a)}catch(j){return void d.onError(j)}if(h=0,e)try{h=c(i,f)}catch(k){return void d.onError(k)}else e=!0,f=i;h>0&&(f=i,g=[]),h>=0&&g.push(a)},d.onError.bind(d),function(){d.onNext(g),d.onCompleted()})})}function f(a){if(0===a.length)throw new Error(A);return a[0]}function g(a,b,c){return new r(function(d){var e=0,f=b.length;return a.subscribe(function(a){var g=!1;try{f>e&&(g=c(a,b[e++]))}catch(h){return void d.onError(h)}g||(d.onNext(!1),d.onCompleted())},d.onError.bind(d),function(){d.onNext(e===f),d.onCompleted()})})}function h(a,b,c,d){if(0>b)throw new Error(z);return new r(function(e){var f=b;return a.subscribe(function(a){0===f&&(e.onNext(a),e.onCompleted()),f--},e.onError.bind(e),function(){c?(e.onNext(d),e.onCompleted()):e.onError(new Error(z))})})}function i(a,b,c){return new r(function(d){var e=c,f=!1;return a.subscribe(function(a){f?d.onError(new Error("Sequence contains more than one element")):(e=a,f=!0)},d.onError.bind(d),function(){f||b?(d.onNext(e),d.onCompleted()):d.onError(new Error(A))})})}function j(a,b,c){return new r(function(d){return a.subscribe(function(a){d.onNext(a),d.onCompleted()},d.onError.bind(d),function(){b?(d.onNext(c),d.onCompleted()):d.onError(new Error(A))})})}function k(a,b,c){return new r(function(d){var e=c,f=!1;return a.subscribe(function(a){e=a,f=!0},d.onError.bind(d),function(){f||b?(d.onNext(e),d.onCompleted()):d.onError(new Error(A))})})}function l(a,b,c,e){return new r(function(f){var g=0;return a.subscribe(function(d){var h;try{h=b.call(c,d,g,a)}catch(i){return void f.onError(i)}h?(f.onNext(e?g:d),f.onCompleted()):g++},f.onError.bind(f),function(){f.onNext(e?-1:d),f.onCompleted()})})}function m(a,b){return new r(function(c){var d=new b;return a.subscribe(d.add.bind(d),c.onError.bind(c),function(){c.onNext(d),c.onCompleted()})})}function n(a,b,c,d){return new r(function(e){var f=new b;return a.subscribe(function(a){var b;try{b=c(a)}catch(g){return void e.onError(g)}var h=a;if(d)try{h=d(a)}catch(g){return void e.onError(g)}f.set(b,h)},e.onError.bind(e),function(){e.onNext(f),e.onCompleted()})})}var o=c.Observable,p=o.prototype,q=c.CompositeDisposable,r=c.AnonymousObservable,s=(c.internals.isEqual,c.helpers),t=s.not,u=s.defaultComparer,v=s.identity,w=s.defaultSubComparer,x=s.isPromise,y=o.fromPromise,z="Argument out of range",A="Sequence contains no elements.";return p.finalValue=function(){var a=this;return new r(function(b){var c,d=!1;return a.subscribe(function(a){d=!0,c=a},b.onError.bind(b),function(){d?(b.onNext(c),b.onCompleted()):b.onError(new Error(A))})})},p.aggregate=function(){var a,b,c;return 2===arguments.length?(a=arguments[0],b=!0,c=arguments[1]):c=arguments[0],b?this.scan(a,c).startWith(a).finalValue():this.scan(c).finalValue()},p.reduce=function(a){var b,c;return 2===arguments.length&&(c=!0,b=arguments[1]),c?this.scan(b,a).startWith(b).finalValue():this.scan(a).finalValue()},p.some=p.any=function(a,b){var c=this;return a?c.where(a,b).any():new r(function(a){return c.subscribe(function(){a.onNext(!0),a.onCompleted()},a.onError.bind(a),function(){a.onNext(!1),a.onCompleted()})})},p.isEmpty=function(){return this.any().map(t)},p.every=p.all=function(a,b){return this.where(function(b){return!a(b)},b).any().select(function(a){return!a})},p.contains=function(a,b){return b||(b=u),this.where(function(c){return b(c,a)}).any()},p.count=function(a,b){return a?this.where(a,b).count():this.aggregate(0,function(a){return a+1})},p.sum=function(a,b){return a?this.select(a,b).sum():this.aggregate(0,function(a,b){return a+b})},p.minBy=function(a,b){return b||(b=w),e(this,a,function(a,c){return-1*b(a,c)})},p.min=function(a){return this.minBy(v,a).select(function(a){return f(a)})},p.maxBy=function(a,b){return b||(b=w),e(this,a,b)},p.max=function(a){return this.maxBy(v,a).select(function(a){return f(a)})},p.average=function(a,b){return a?this.select(a,b).average():this.scan({sum:0,count:0},function(a,b){return{sum:a.sum+b,count:a.count+1}}).finalValue().select(function(a){if(0===a.count)throw new Error("The input sequence was empty");return a.sum/a.count})},p.sequenceEqual=function(a,b){var c=this;return b||(b=u),Array.isArray(a)?g(c,a,b):new r(function(d){var e=!1,f=!1,g=[],h=[],i=c.subscribe(function(a){var c,e;if(h.length>0){e=h.shift();try{c=b(e,a)}catch(i){return void d.onError(i)}c||(d.onNext(!1),d.onCompleted())}else f?(d.onNext(!1),d.onCompleted()):g.push(a)},d.onError.bind(d),function(){e=!0,0===g.length&&(h.length>0?(d.onNext(!1),d.onCompleted()):f&&(d.onNext(!0),d.onCompleted()))});x(a)&&(a=y(a));var j=a.subscribe(function(a){var c,f;if(g.length>0){f=g.shift();try{c=b(f,a)}catch(i){return void d.onError(i)}c||(d.onNext(!1),d.onCompleted())}else e?(d.onNext(!1),d.onCompleted()):h.push(a)},d.onError.bind(d),function(){f=!0,0===h.length&&(g.length>0?(d.onNext(!1),d.onCompleted()):e&&(d.onNext(!0),d.onCompleted()))});return new q(i,j)})},p.elementAt=function(a){return h(this,a,!1)},p.elementAtOrDefault=function(a,b){return h(this,a,!0,b)},p.single=function(a,b){return a?this.where(a,b).single():i(this,!1)},p.singleOrDefault=function(a,b,c){return a?this.where(a,c).singleOrDefault(null,b):i(this,!0,b)},p.first=function(a,b){return a?this.where(a,b).first():j(this,!1)},p.firstOrDefault=function(a,b){return a?this.where(a).firstOrDefault(null,b):j(this,!0,b)},p.last=function(a,b){return a?this.where(a,b).last():k(this,!1)},p.lastOrDefault=function(a,b,c){return a?this.where(a,c).lastOrDefault(null,b):k(this,!0,b)},p.find=function(a,b){return l(this,a,b,!1)},p.findIndex=function(a,b){return l(this,a,b,!0)},a.Set&&(p.toSet=function(){return m(this,a.Set)}),a.WeakSet&&(p.toWeakSet=function(){return m(this,a.WeakSet)}),a.Map&&(p.toMap=function(b,c){return n(this,a.Map,b,c)}),a.WeakMap&&(p.toWeakMap=function(b,c){return n(this,a.WeakMap,b,c)}),c}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.all.compat.js b/ajax/libs/rxjs/2.3.9/rx.all.compat.js new file mode 100644 index 000000000..5d3543efe --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.all.compat.js @@ -0,0 +1,9443 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { + + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, + isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || + '_es6shim_iterator_'; + // Bug for mozilla version + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Utilities + if (!Function.prototype.bind) { + Function.prototype.bind = function (that) { + var target = this, + args = slice.call(arguments, 1); + var bound = function () { + if (this instanceof bound) { + function F() { } + F.prototype = target.prototype; + var self = new F(); + var result = target.apply(self, args.concat(slice.call(arguments))); + if (Object(result) === result) { + return result; + } + return self; + } else { + return target.apply(that, args.concat(slice.call(arguments))); + } + }; + + return bound; + }; + } + +if (!Array.prototype.forEach) { + + Array.prototype.forEach = function (callback, thisArg) { + var T, k; + + if (this == null) { + throw new TypeError(" this is null or not defined"); + } + + var O = Object(this); + var len = O.length >>> 0; + + if (typeof callback !== "function") { + throw new TypeError(callback + " is not a function"); + } + + if (arguments.length > 1) { + T = thisArg; + } + + k = 0; + while (k < len) { + var kValue; + if (k in O) { + kValue = O[k]; + callback.call(T, kValue, k, O); + } + k++; + } + }; +} + + var boxedString = Object("a"), + splitString = boxedString[0] != "a" || !(0 in boxedString); + if (!Array.prototype.every) { + Array.prototype.every = function every(fun /*, thisp */) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self && !fun.call(thisp, self[i], i, object)) { + return false; + } + } + return true; + }; + } + + if (!Array.prototype.map) { + Array.prototype.map = function map(fun /*, thisp*/) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + result = Array(length), + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self) { + result[i] = fun.call(thisp, self[i], i, object); + } + } + return result; + }; + } + + if (!Array.prototype.filter) { + Array.prototype.filter = function (predicate) { + var results = [], item, t = new Object(this); + for (var i = 0, len = t.length >>> 0; i < len; i++) { + item = t[i]; + if (i in t && predicate.call(arguments[1], item, i, t)) { + results.push(item); + } + } + return results; + }; + } + + if (!Array.isArray) { + Array.isArray = function (arg) { + return {}.toString.call(arg) == arrayClass; + }; + } + + if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function indexOf(searchElement) { + var t = Object(this); + var len = t.length >>> 0; + if (len === 0) { + return -1; + } + var n = 0; + if (arguments.length > 1) { + n = Number(arguments[1]); + if (n !== n) { + n = 0; + } else if (n !== 0 && n != Infinity && n !== -Infinity) { + n = (n > 0 || -1) * Math.floor(Math.abs(n)); + } + } + if (n >= len) { + return -1; + } + var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); + for (; k < len; k++) { + if (k in t && t[k] === searchElement) { + return k; + } + } + return -1; + }; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { + return; + } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { + return; + } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = + SerialDisposable = Rx.SerialDisposable = (function () { + function BooleanDisposable () { + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + old && old.dispose(); + shouldDispose && value && value.dispose(); + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + old && old.dispose(); + }; + + return BooleanDisposable; + }()); + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + timeSpan < 0 && (timeSpan = 0); + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + (function (schedulerProto) { + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function scheduleInnerRecursive(action, self) { + action(function(dt) { self(action, dt); }); + } + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { self(_action); }); }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + }(Scheduler.prototype)); + + (function (schedulerProto) { + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, action); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var s = state; + + var id = setInterval(function () { + s = action(s); + }, period); + + return disposableCreate(function () { + clearInterval(id); + }); + }; + }(Scheduler.prototype)); + + (function (schedulerProto) { + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchError = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + }(Scheduler.prototype)); + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt); + + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + + currentScheduler.scheduleRequired = function () { return !queue; }; + currentScheduler.ensureTrampoline = function (action) { + if (!queue) { this.schedule(action); } else { action(); } + }; + + return currentScheduler; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, + dt = Scheduler.normalize(dueTime); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** @private */ + var CatchScheduler = (function (_super) { + + function localNow() { + return this._scheduler.now(); + } + + function scheduleNow(state, action) { + return this._scheduler.scheduleWithState(state, this._wrap(action)); + } + + function scheduleRelative(state, dueTime, action) { + return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); + } + + function scheduleAbsolute(state, dueTime, action) { + return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); + } + + inherits(CatchScheduler, _super); + + /** @private */ + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + /** @private */ + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + /** @private */ + CatchScheduler.prototype._wrap = function (action) { + var parent = this; + return function (self, state) { + try { + return action(parent._getRecursiveWrapper(self), state); + } catch (e) { + if (!parent._handler(e)) { throw e; } + return disposableEmpty; + } + }; + }; + + /** @private */ + CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { + if (this._recursiveOriginal !== scheduler) { + this._recursiveOriginal = scheduler; + var wrapper = this._clone(scheduler); + wrapper._recursiveOriginal = scheduler; + wrapper._recursiveWrapper = wrapper; + this._recursiveWrapper = wrapper; + } + return this._recursiveWrapper; + }; + + /** @private */ + CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var self = this, failed = false, d = new SingleAssignmentDisposable(); + + d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { + if (failed) { return null; } + try { + return action(state1); + } catch (e) { + failed = true; + if (!self._handler(e)) { throw e; } + d.dispose(); + return null; + } + })); + + return d; + }; + + return CatchScheduler; + }(Scheduler)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { + return observerOrOnNext && typeof observerOrOnNext === 'object' ? + this._acceptObservable(observerOrOnNext) : + this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notifications + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + Notification.prototype.toObservable = function (scheduler) { + var notification = this; + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + notification.kind === 'N' && observer.onCompleted(); + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + + function _accept (onNext) { return onNext(this.value); } + function _acceptObservable(observer) { return observer.onNext(this.value); } + function toString () { return 'OnNext(' + this.value + ')'; } + + return function (value) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + + function _accept (onNext, onError) { return onError(this.exception); } + function _acceptObservable(observer) { return observer.onError(this.exception); } + function toString () { return 'OnError(' + this.exception + ')'; } + + return function (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { return onCompleted(); } + function _acceptObservable(observer) { return observer.onCompleted(); } + function toString () { return 'OnCompleted()'; } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var CheckedObserver = (function (_super) { + inherits(CheckedObserver, _super); + + function CheckedObserver(observer) { + _super.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + try { + this._observer.onNext(value); + } catch (e) { + throw e; + } finally { + this._state = 0; + } + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + try { + this._observer.onError(err); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + try { + this._observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { + inherits(ScheduledObserver, _super); + + function ScheduledObserver(scheduler, observer) { + _super.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + /** @private */ + var ObserveOnObserver = (function (_super) { + inherits(ObserveOnObserver, _super); + + /** @private */ + function ObserveOnObserver() { + _super.apply(this, arguments); + } + + /** @private */ + ObserveOnObserver.prototype.next = function (value) { + _super.prototype.next.call(this, value); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.error = function (e) { + _super.prototype.error.call(this, e); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.completed = function () { + _super.prototype.completed.call(this); + this.ensureActive(); + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber = typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted); + + return this._subscribe(subscriber); + }; + + return Observable; + })(); + + /** + * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + * + * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects + * that require to be run on a scheduler, use subscribeOn. + * + * @param {Scheduler} scheduler Scheduler to notify observers on. + * @returns {Observable} The source sequence whose observations happen on the specified scheduler. + */ + observableProto.observeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(new ObserveOnObserver(scheduler, observer)); + }); + }; + + /** + * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; + * see the remarks section for more information on the distinction between subscribeOn and observeOn. + + * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer + * callbacks on a scheduler, use observeOn. + + * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. + * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); + d.setDisposable(m); + m.setDisposable(scheduler.schedule(function () { + d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); + })); + return d; + }); + }; + + /** + * Converts a Promise to an Observable sequence + * @param {Promise} An ES6 Compliant promise. + * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. + */ + var observableFromPromise = Observable.fromPromise = function (promise) { + return observableDefer(function () { + var subject = new Rx.AsyncSubject(); + + promise.then( + function (value) { + if (!subject.isDisposed) { + subject.onNext(value); + subject.onCompleted(); + } + }, + subject.onError.bind(subject)); + + return subject; + }); + }; + /* + * Converts an existing observable sequence to an ES6 Compatible Promise + * @example + * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); + * + * // With config + * Rx.config.Promise = RSVP.Promise; + * var promise = Rx.Observable.return(42).toPromise(); + * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. + * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. + */ + observableProto.toPromise = function (promiseCtor) { + promiseCtor || (promiseCtor = Rx.config.Promise); + if (!promiseCtor) { + throw new Error('Promise type not provided nor in Rx.config.Promise'); + } + var source = this; + return new promiseCtor(function (resolve, reject) { + // No cancellation can be done + var value, hasValue = false; + source.subscribe(function (v) { + value = v; + hasValue = true; + }, function (err) { + reject(err); + }, function () { + if (hasValue) { + resolve(value); + } + }); + }); + }; + /** + * Creates a list from an observable sequence. + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + var self = this; + return new AnonymousObservable(function(observer) { + var arr = []; + return self.subscribe( + arr.push.bind(arr), + observer.onError.bind(observer), + function () { + observer.onNext(arr); + observer.onCompleted(); + }); + }); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.create = Observable.createWithDisposable = function (subscribe) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + var maxSafeInteger = Math.pow(2, 53) - 1; + + function numberIsFinite(value) { + return typeof value === 'number' && root.isFinite(value); + } + + function isNan(n) { + return n !== n; + } + + function isIterable(o) { + return o[$iterator$] !== undefined; + } + + function sign(value) { + var number = +value; + if (number === 0) { return number; } + if (isNaN(number)) { return number; } + return number < 0 ? -1 : 1; + } + + function toLength(o) { + var len = +o.length; + if (isNaN(len)) { return 0; } + if (len === 0 || !numberIsFinite(len)) { return len; } + len = sign(len) * Math.floor(Math.abs(len)); + if (len <= 0) { return 0; } + if (len > maxSafeInteger) { return maxSafeInteger; } + return len; + } + + function isCallable(f) { + return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; + } + + /** + * This method creates a new Observable sequence from an array-like or iterable object. + * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. + * @param {Function} [mapFn] Map function to call on every element of the array. + * @param {Any} [thisArg] The context to use calling the mapFn if provided. + * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + Observable.from = function (iterable, mapFn, thisArg, scheduler) { + if (iterable == null) { + throw new Error('iterable cannot be null.') + } + if (mapFn && !isCallable(mapFn)) { + throw new Error('mapFn when provided must be a function'); + } + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var list = Object(iterable), + objIsIterable = isIterable(list), + len = objIsIterable ? 0 : toLength(list), + it = objIsIterable ? list[$iterator$]() : null, + i = 0; + return scheduler.scheduleRecursive(function (self) { + if (i < len || objIsIterable) { + var result; + if (objIsIterable) { + var next = it.next(); + if (next.done) { + observer.onCompleted(); + return; + } + + result = next.value; + } else { + result = list[i]; + } + + if (mapFn && isCallable(mapFn)) { + try { + result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); + } catch (e) { + observer.onError(e); + return; + } + } + + observer.onNext(result); + i++; + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * var res = Rx.Observable.fromArray([1,2,3]); + * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0, len = array.length; + return scheduler.scheduleRecursive(function (self) { + if (count < len) { + observer.onNext(array[count++]); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. + * @returns {Observable} The generated sequence. + */ + Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var first = true, state = initialState; + return scheduler.scheduleRecursive(function (self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + } + } catch (exception) { + observer.onError(exception); + return; + } + if (hasResult) { + observer.onNext(result); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.of = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return observableFromArray(args); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + var observableOf = Observable.ofWithScheduler = function (scheduler) { + var len = arguments.length - 1, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } + return observableFromArray(args, scheduler); + }; + + /** + * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). + * @returns {Observable} An observable sequence whose observers will never get called. + */ + var observableNever = Observable.never = function () { + return new AnonymousObservable(function () { + return disposableEmpty; + }); + }; + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.range(0, 10); + * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleRecursiveWithState(0, function (i, self) { + if (i < count) { + observer.onNext(start + i); + self(i + 1); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.repeat(42); + * var res = Rx.Observable.repeat(42, 4); + * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'just', and 'returnValue' for browsers 0) { + subscribe(q.shift()); + } else { + activeCount--; + isStopped && activeCount === 0 && observer.onCompleted(); + } + })); + } + group.add(sources.subscribe(function (innerSource) { + if (activeCount < maxConcurrentOrOther) { + activeCount++; + subscribe(innerSource); + } else { + q.push(innerSource); + } + }, observer.onError.bind(observer), function () { + isStopped = true; + activeCount === 0 && observer.onCompleted(); + })); + return group; + }); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * + * @example + * 1 - merged = Rx.Observable.merge(xs, ys, zs); + * 2 - merged = Rx.Observable.merge([xs, ys, zs]); + * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); + * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources; + if (!arguments[0]) { + scheduler = immediateScheduler; + sources = slice.call(arguments, 1); + } else if (arguments[0].now) { + scheduler = arguments[0]; + sources = slice.call(arguments, 1); + } else { + scheduler = immediateScheduler; + sources = slice.call(arguments, 0); + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableFromArray(sources, scheduler).mergeObservable(); + }; + + /** + * Merges an observable sequence of observable sequences into an observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.mergeObservable = observableProto.mergeAll =function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + isStopped = false, + m = new SingleAssignmentDisposable(); + + group.add(m); + m.setDisposable(sources.subscribe(function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + innerSubscription.setDisposable(innerSource.subscribe(function (x) { + observer.onNext(x); + }, observer.onError.bind(observer), function () { + group.remove(innerSubscription); + if (isStopped && group.length === 1) { observer.onCompleted(); } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (group.length === 1) { observer.onCompleted(); } + })); + return group; + }); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. + * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. + */ + observableProto.onErrorResumeNext = function (second) { + if (!second) { + throw new Error('Second observable is required'); + } + return onErrorResumeNext([this, second]); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * + * @example + * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); + * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); + * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. + */ + var onErrorResumeNext = Observable.onErrorResumeNext = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var pos = 0, subscription = new SerialDisposable(), + cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, d; + if (pos < sources.length) { + current = sources[pos++]; + isPromise(current) && (current = observableFromPromise(current)); + d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { + self(); + }, function () { + self(); + })); + } else { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + isOpen && observer.onNext(left); + }, observer.onError.bind(observer), function () { + isOpen && observer.onCompleted(); + })); + + isPromise(other) && (other = observableFromPromise(other)); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, observer.onError.bind(observer), function () { + rightSubscription.dispose(); + })); + + return disposables; + }); + }; + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasLatest = false, + innerSubscription = new SerialDisposable(), + isStopped = false, + latest = 0, + subscription = sources.subscribe(function (innerSource) { + var d = new SingleAssignmentDisposable(), id = ++latest; + hasLatest = true; + innerSubscription.setDisposable(d); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + d.setDisposable(innerSource.subscribe(function (x) { + if (latest === id) { + observer.onNext(x); + } + }, function (e) { + if (latest === id) { + observer.onError(e); + } + }, function () { + if (latest === id) { + hasLatest = false; + if (isStopped) { + observer.onCompleted(); + } + } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (!hasLatest) { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, innerSubscription); + }); + }; + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + isPromise(other) && (other = observableFromPromise(other)); + return new CompositeDisposable( + source.subscribe(observer), + other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) + ); + }); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], result; + try { + result = resultSelector(left, right); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + } else { + observer.onCompleted(); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. + * + * @example + * 1 - res = obs1.zip(obs2, fn); + * 1 - res = x1.zip([1,2,3], fn); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { + return zipArray.apply(this, arguments); + } + var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); + sources.unshift(parent); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + var res, queuedValues; + if (queues.every(function (x) { return x.length > 0; })) { + try { + queuedValues = queues.map(function (x) { return x.shift(); }); + res = resultSelector.apply(parent, queuedValues); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(function (x) { return x; })) { + observer.onCompleted(); + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = sources[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + * @param arguments Observable sources. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var args = slice.call(arguments, 0), + first = args.shift(); + return first.zip.apply(first, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + return; + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(identity)) { + observer.onCompleted(); + return; + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + })(idx); + } + + var compositeDisposable = new CompositeDisposable(subscriptions); + compositeDisposable.add(disposableCreate(function () { + for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { + queues[qIdx] = []; + } + })); + return compositeDisposable; + }); + }; + + /** + * Hides the identity of an observable sequence. + * @returns {Observable} An observable sequence that hides the identity of the source sequence. + */ + observableProto.asObservable = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(observer); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. + * + * @example + * var res = xs.bufferWithCount(10); + * var res = xs.bufferWithCount(10, 1); + * @param {Number} count Length of each buffer. + * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithCount = function (count, skip) { + if (typeof skip !== 'number') { + skip = count; + } + return this.windowWithCount(count, skip).selectMany(function (x) { + return x.toArray(); + }).where(function (x) { + return x.length > 0; + }); + }; + + /** + * Dematerializes the explicit notification values of an observable sequence as implicit notifications. + * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + return x.accept(observer); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + * + * var obs = observable.distinctUntilChanged(); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. + * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. + * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + observableProto.distinctUntilChanged = function (keySelector, comparer) { + var source = this; + keySelector || (keySelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var comparerEquals = false, key; + try { + key = keySelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + if (hasCurrentKey) { + try { + comparerEquals = comparer(currentKey, key); + } catch (exception) { + observer.onError(exception); + return; + } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + observer.onNext(value); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * + * @example + * var res = observable.do(observer); + * var res = observable.do(onNext); + * var res = observable.do(onNext, onError); + * var res = observable.do(onNext, onError, onCompleted); + * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { + var source = this, onNextFunc; + if (typeof observerOrOnNext === 'function') { + onNextFunc = observerOrOnNext; + } else { + onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); + onError = observerOrOnNext.onError.bind(observerOrOnNext); + onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); + } + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + try { + onNextFunc(x); + } catch (e) { + observer.onError(e); + } + observer.onNext(x); + }, function (err) { + if (!onError) { + observer.onError(err); + } else { + try { + onError(err); + } catch (e) { + observer.onError(e); + } + observer.onError(err); + } + }, function () { + if (!onCompleted) { + observer.onCompleted(); + } else { + try { + onCompleted(); + } catch (e) { + observer.onError(e); + } + observer.onCompleted(); + } + }); + }); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * + * @example + * var res = observable.finallyAction(function () { console.log('sequence ended'; }); + * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. + * @returns {Observable} Source sequence with the action-invoking termination behavior applied. + */ + observableProto['finally'] = observableProto.finallyAction = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription; + try { + subscription = source.subscribe(observer); + } catch (e) { + action(); + throw e; + } + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Materializes the implicit notifications of an observable sequence as explicit notification values. + * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. + */ + observableProto.materialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (value) { + observer.onNext(notificationCreateOnNext(value)); + }, function (e) { + observer.onNext(notificationCreateOnError(e)); + observer.onCompleted(); + }, function () { + observer.onNext(notificationCreateOnCompleted()); + observer.onCompleted(); + }); + }); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * + * @example + * var res = repeated = source.repeat(); + * var res = repeated = source.repeat(42); + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + observableProto.repeat = function (repeatCount) { + return enumerableRepeat(this, repeatCount).concat(); + }; + + /** + * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. + * Note if you encounter an error and want it to retry once, then you must use .retry(2); + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(2); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchException(); + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @example + * var res = source.scan(function (acc, x) { return acc + x; }); + * var res = source.scan(0, function (acc, x) { return acc + x; }); + * @param {Mixed} [seed] The initial accumulator value. + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @returns {Observable} An observable sequence containing the accumulated values. + */ + observableProto.scan = function () { + var hasSeed = false, seed, accumulator, source = this; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[0]; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return new AnonymousObservable(function (observer) { + var hasAccumulation, accumulation, hasValue; + return source.subscribe ( + function (x) { + try { + if (!hasValue) { + hasValue = true; + } + + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(accumulation); + }, + observer.onError.bind(observer), + function () { + if (!hasValue && hasSeed) { + observer.onNext(seed); + } + observer.onCompleted(); + } + ); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + observer.onNext(q.shift()); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * + * @memberOf Observable# + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && 'now' in Object(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + values = slice.call(arguments, start); + return enumerableFor([observableFromArray(values, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence. + * + * @example + * var res = source.takeLast(5); + * + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, observer.onError.bind(observer), function () { + while(q.length > 0) { observer.onNext(q.shift()); } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, observer.onError.bind(observer), function () { + observer.onNext(q); + observer.onCompleted(); + }); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. + * + * var res = xs.windowWithCount(10); + * var res = xs.windowWithCount(10, 1); + * @param {Number} count Length of each window. + * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithCount = function (count, skip) { + var source = this; + if (count <= 0) { + throw new Error(argumentOutOfRange); + } + if (arguments.length === 1) { + skip = count; + } + if (skip <= 0) { + throw new Error(argumentOutOfRange); + } + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), + refCountDisposable = new RefCountDisposable(m), + n = 0, + q = [], + createWindow = function () { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + }; + createWindow(); + m.setDisposable(source.subscribe(function (x) { + var s; + for (var i = 0, len = q.length; i < len; i++) { + q[i].onNext(x); + } + var c = n - count + 1; + if (c >= 0 && c % skip === 0) { + s = q.shift(); + s.onCompleted(); + } + n++; + if (n % skip === 0) { + createWindow(); + } + }, function (exception) { + while (q.length > 0) { + q.shift().onError(exception); + } + observer.onError(exception); + }, function () { + while (q.length > 0) { + q.shift().onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + function concatMap(source, selector, thisArg) { + return source.map(function (x, i) { + var result = selector.call(thisArg, x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).concatAll(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { + if (resultSelector) { + return this.concatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }); + } + return typeof selector === 'function' ? + concatMap(this, selector, thisArg) : + concatMap(this, function () { return selector; }); + }; + + /** + * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. + * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. + * @param {Function} onError A transform function to apply when an error occurs in the source sequence. + * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. + * @param {Any} [thisArg] An optional "this" to use to invoke each transform. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. + */ + observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + var result; + try { + result = onNext.call(thisArg, x, index++); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + }, + function (err) { + var result; + try { + result = onError.call(thisArg, err); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }, + function () { + var result; + try { + result = onCompleted.call(thisArg); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }); + }).concatAll(); + }; + /** + * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * var res = obs = xs.defaultIfEmpty(); + * 2 - obs = xs.defaultIfEmpty(false); + * + * @memberOf Observable# + * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. + * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. + */ + observableProto.defaultIfEmpty = function (defaultValue) { + var source = this; + if (defaultValue === undefined) { + defaultValue = null; + } + return new AnonymousObservable(function (observer) { + var found = false; + return source.subscribe(function (x) { + found = true; + observer.onNext(x); + }, observer.onError.bind(observer), function () { + if (!found) { + observer.onNext(defaultValue); + } + observer.onCompleted(); + }); + }); + }; + + // Swap out for Array.findIndex + function arrayIndexOfComparer(array, item, comparer) { + for (var i = 0, len = array.length; i < len; i++) { + if (comparer(array[i], item)) { return i; } + } + return -1; + } + + function HashSet(comparer) { + this.comparer = comparer; + this.set = []; + } + HashSet.prototype.push = function(value) { + var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; + retValue && this.set.push(value); + return retValue; + }; + + /** + * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. + * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. + * + * @example + * var res = obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [comparer] Used to compare items in the collection. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, comparer) { + var source = this; + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hashSet = new HashSet(comparer); + return source.subscribe(function (x) { + var key = x; + + if (keySelector) { + try { + key = keySelector(x); + } catch (e) { + observer.onError(e); + return; + } + } + hashSet.push(key) && observer.onNext(x); + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer)); + }); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. + * + * @example + * var res = observable.groupBy(function (x) { return x.id; }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. + * @param {Function} [comparer] Used to determine whether the objects are equal. + * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + observableProto.groupBy = function (keySelector, elementSelector, comparer) { + return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function. + * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same + * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. + * + * @example + * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} durationSelector A function to signal the expiration of a group. + * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. + * @returns {Observable} + * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. + * + */ + observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { + var source = this; + elementSelector || (elementSelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + function handleError(e) { return function (item) { item.onError(e); }; } + var map = new Dictionary(0, comparer), + groupDisposable = new CompositeDisposable(), + refCountDisposable = new RefCountDisposable(groupDisposable); + + groupDisposable.add(source.subscribe(function (x) { + var key; + try { + key = keySelector(x); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + var fireNewMapEntry = false, + writer = map.tryGetValue(key); + if (!writer) { + writer = new Subject(); + map.set(key, writer); + fireNewMapEntry = true; + } + + if (fireNewMapEntry) { + var group = new GroupedObservable(key, writer, refCountDisposable), + durationGroup = new GroupedObservable(key, writer); + try { + duration = durationSelector(durationGroup); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + observer.onNext(group); + + var md = new SingleAssignmentDisposable(); + groupDisposable.add(md); + + var expire = function () { + map.remove(key) && writer.onCompleted(); + groupDisposable.remove(md); + }; + + md.setDisposable(duration.take(1).subscribe( + noop, + function (exn) { + map.getValues().forEach(handleError(exn)); + observer.onError(exn); + }, + expire) + ); + } + + var element; + try { + element = elementSelector(x); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + writer.onNext(element); + }, function (ex) { + map.getValues().forEach(handleError(ex)); + observer.onError(ex); + }, function () { + map.getValues().forEach(function (item) { item.onCompleted(); }); + observer.onCompleted(); + })); + + return refCountDisposable; + }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + observableProto.select = observableProto.map = function (selector, thisArg) { + var parent = this; + return new AnonymousObservable(function (observer) { + var count = 0; + return parent.subscribe(function (value) { + var result; + try { + result = selector.call(thisArg, value, count++, parent); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Retrieves the value of a specified property from all elements in the Observable sequence. + * @param {String} property The property to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function (property) { + return this.select(function (x) { return x[property]; }); + }; + + function flatMap(source, selector, thisArg) { + return source.map(function (x, i) { + var result = selector.call(thisArg, x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).mergeObservable(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { + if (resultSelector) { + return this.flatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }, thisArg); + } + return typeof selector === 'function' ? + flatMap(this, selector, thisArg) : + flatMap(this, function () { return selector; }); + }; + + /** + * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. + * @param {Function} onError A transform function to apply when an error occurs in the source sequence. + * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. + * @param {Any} [thisArg] An optional "this" to use to invoke each transform. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. + */ + observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + var result; + try { + result = onNext.call(thisArg, x, index++); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + }, + function (err) { + var result; + try { + result = onError.call(thisArg, err); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }, + function () { + var result; + try { + result = onCompleted.call(thisArg); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }); + }).mergeAll(); + }; + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { + throw new Error(argumentOutOfRange); + } + var observable = this; + return new AnonymousObservable(function (observer) { + var remaining = count; + return observable.subscribe(function (x) { + if (remaining <= 0) { + observer.onNext(x); + } else { + remaining--; + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + * The element's index is used in the logic of the predicate function. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !predicate.call(thisArg, x, i++, source); + } catch (e) { + observer.onError(e); + return; + } + } + if (running) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.exception = null; + } + }); + + return BehaviorSubject; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. + */ + var ReplaySubject = Rx.ReplaySubject = (function (_super) { + + function RemovableDisposable (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + RemovableDisposable.prototype.dispose = function () { + this.observer.dispose(); + if (!this.subject.isDisposed) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + } + }; + + function subscribe(observer) { + var so = new ScheduledObserver(this.scheduler, observer), + subscription = new RemovableDisposable(this, so); + checkDisposed.call(this); + this._trim(this.scheduler.now()); + this.observers.push(so); + + var n = this.q.length; + + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } + + if (this.hasError) { + n++; + so.onError(this.error); + } else if (this.isStopped) { + n++; + so.onCompleted(); + } + + so.ensureActive(n); + return subscription; + } + + inherits(ReplaySubject, _super); + + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; + this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + _super.call(this, subscribe); + } + + addProperties(ReplaySubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /* @private */ + _trim: function (now) { + while (this.q.length > this.bufferSize) { + this.q.shift(); + } + while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { + this.q.shift(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); + + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onNext(value); + observer.ensureActive(); + } + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { + inherits(ConnectableObservable, __super__); + + function ConnectableObservable(source, subject) { + var hasSubscription = false, + subscription, + sourceObservable = source.asObservable(); + + this.connect = function () { + if (!hasSubscription) { + hasSubscription = true; + subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { + hasSubscription = false; + })); + } + return subscription; + }; + + __super__.call(this, subject.subscribe.bind(subject)); + } + + ConnectableObservable.prototype.refCount = function () { + var connectableSubscription, count = 0, source = this; + return new AnonymousObservable(function (observer) { + var shouldConnect = ++count === 1, + subscription = source.subscribe(observer); + shouldConnect && (connectableSubscription = source.connect()); + return function () { + subscription.dispose(); + --count === 0 && connectableSubscription.dispose(); + }; + }); + }; + + return ConnectableObservable; + }(Observable)); + + var Dictionary = (function () { + + var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], + noSuchkey = "no such key", + duplicatekey = "duplicate key"; + + function isPrime(candidate) { + if (candidate & 1 === 0) { return candidate === 2; } + var num1 = Math.sqrt(candidate), + num2 = 3; + while (num2 <= num1) { + if (candidate % num2 === 0) { return false; } + num2 += 2; + } + return true; + } + + function getPrime(min) { + var index, num, candidate; + for (index = 0; index < primes.length; ++index) { + num = primes[index]; + if (num >= min) { return num; } + } + candidate = min | 1; + while (candidate < primes[primes.length - 1]) { + if (isPrime(candidate)) { return candidate; } + candidate += 2; + } + return min; + } + + function stringHashFn(str) { + var hash = 757602046; + if (!str.length) { return hash; } + for (var i = 0, len = str.length; i < len; i++) { + var character = str.charCodeAt(i); + hash = ((hash<<5)-hash)+character; + hash = hash & hash; + } + return hash; + } + + function numberHashFn(key) { + var c2 = 0x27d4eb2d; + key = (key ^ 61) ^ (key >>> 16); + key = key + (key << 3); + key = key ^ (key >>> 4); + key = key * c2; + key = key ^ (key >>> 15); + return key; + } + + var getHashCode = (function () { + var uniqueIdCounter = 0; + + return function (obj) { + if (obj == null) { throw new Error(noSuchkey); } + + // Check for built-ins before tacking on our own for any object + if (typeof obj === 'string') { return stringHashFn(obj); } + if (typeof obj === 'number') { return numberHashFn(obj); } + if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } + if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } + if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } + if (typeof obj.valueOf === 'function') { + // Hack check for valueOf + var valueOf = obj.valueOf(); + if (typeof valueOf === 'number') { return numberHashFn(valueOf); } + if (typeof obj === 'string') { return stringHashFn(valueOf); } + } + if (obj.getHashCode) { return obj.getHashCode(); } + + var id = 17 * uniqueIdCounter++; + obj.getHashCode = function () { return id; }; + return id; + }; + }()); + + function newEntry() { + return { key: null, value: null, next: 0, hashCode: 0 }; + } + + function Dictionary(capacity, comparer) { + if (capacity < 0) { throw new Error('out of range'); } + if (capacity > 0) { this._initialize(capacity); } + + this.comparer = comparer || defaultComparer; + this.freeCount = 0; + this.size = 0; + this.freeList = -1; + } + + var dictionaryProto = Dictionary.prototype; + + dictionaryProto._initialize = function (capacity) { + var prime = getPrime(capacity), i; + this.buckets = new Array(prime); + this.entries = new Array(prime); + for (i = 0; i < prime; i++) { + this.buckets[i] = -1; + this.entries[i] = newEntry(); + } + this.freeList = -1; + }; + + dictionaryProto.add = function (key, value) { + return this._insert(key, value, true); + }; + + dictionaryProto._insert = function (key, value, add) { + if (!this.buckets) { this._initialize(0); } + var index3, + num = getHashCode(key) & 2147483647, + index1 = num % this.buckets.length; + for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { + if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { + if (add) { throw new Error(duplicatekey); } + this.entries[index2].value = value; + return; + } + } + if (this.freeCount > 0) { + index3 = this.freeList; + this.freeList = this.entries[index3].next; + --this.freeCount; + } else { + if (this.size === this.entries.length) { + this._resize(); + index1 = num % this.buckets.length; + } + index3 = this.size; + ++this.size; + } + this.entries[index3].hashCode = num; + this.entries[index3].next = this.buckets[index1]; + this.entries[index3].key = key; + this.entries[index3].value = value; + this.buckets[index1] = index3; + }; + + dictionaryProto._resize = function () { + var prime = getPrime(this.size * 2), + numArray = new Array(prime); + for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } + var entryArray = new Array(prime); + for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } + for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } + for (var index1 = 0; index1 < this.size; ++index1) { + var index2 = entryArray[index1].hashCode % prime; + entryArray[index1].next = numArray[index2]; + numArray[index2] = index1; + } + this.buckets = numArray; + this.entries = entryArray; + }; + + dictionaryProto.remove = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647, + index1 = num % this.buckets.length, + index2 = -1; + for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { + if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { + if (index2 < 0) { + this.buckets[index1] = this.entries[index3].next; + } else { + this.entries[index2].next = this.entries[index3].next; + } + this.entries[index3].hashCode = -1; + this.entries[index3].next = this.freeList; + this.entries[index3].key = null; + this.entries[index3].value = null; + this.freeList = index3; + ++this.freeCount; + return true; + } else { + index2 = index3; + } + } + } + return false; + }; + + dictionaryProto.clear = function () { + var index, len; + if (this.size <= 0) { return; } + for (index = 0, len = this.buckets.length; index < len; ++index) { + this.buckets[index] = -1; + } + for (index = 0; index < this.size; ++index) { + this.entries[index] = newEntry(); + } + this.freeList = -1; + this.size = 0; + }; + + dictionaryProto._findEntry = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647; + for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { + if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { + return index; + } + } + } + return -1; + }; + + dictionaryProto.count = function () { + return this.size - this.freeCount; + }; + + dictionaryProto.tryGetValue = function (key) { + var entry = this._findEntry(key); + return entry >= 0 ? + this.entries[entry].value : + undefined; + }; + + dictionaryProto.getValues = function () { + var index = 0, results = []; + if (this.entries) { + for (var index1 = 0; index1 < this.size; index1++) { + if (this.entries[index1].hashCode >= 0) { + results[index++] = this.entries[index1].value; + } + } + } + return results; + }; + + dictionaryProto.get = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { return this.entries[entry].value; } + throw new Error(noSuchkey); + }; + + dictionaryProto.set = function (key, value) { + this._insert(key, value, false); + }; + + dictionaryProto.containskey = function (key) { + return this._findEntry(key) >= 0; + }; + + return Dictionary; + }()); + + /** + * Correlates the elements of two sequences based on overlapping durations. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(); + var leftDone = false, rightDone = false; + var leftId = 0, rightId = 0; + var leftMap = new Dictionary(), rightMap = new Dictionary(); + + group.add(left.subscribe( + function (value) { + var id = leftId++; + var md = new SingleAssignmentDisposable(); + + leftMap.add(id, value); + group.add(md); + + var expire = function () { + leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); + + rightMap.getValues().forEach(function (v) { + var result; + try { + result = resultSelector(value, v); + } catch (exn) { + observer.onError(exn); + return; + } + + observer.onNext(result); + }); + }, + observer.onError.bind(observer), + function () { + leftDone = true; + (rightDone || leftMap.count() === 0) && observer.onCompleted(); + }) + ); + + group.add(right.subscribe( + function (value) { + var id = rightId++; + var md = new SingleAssignmentDisposable(); + + rightMap.add(id, value); + group.add(md); + + var expire = function () { + rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = rightDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); + + leftMap.getValues().forEach(function (v) { + var result; + try { + result = resultSelector(v, value); + } catch(exn) { + observer.onError(exn); + return; + } + + observer.onNext(result); + }); + }, + observer.onError.bind(observer), + function () { + rightDone = true; + (leftDone || rightMap.count() === 0) && observer.onCompleted(); + }) + ); + return group; + }); + }; + + /** + * Correlates the elements of two sequences based on overlapping durations, and groups the results. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(); + var r = new RefCountDisposable(group); + var leftMap = new Dictionary(), rightMap = new Dictionary(); + var leftId = 0, rightId = 0; + + function handleError(e) { return function (v) { v.onError(e); }; }; + + group.add(left.subscribe( + function (value) { + var s = new Subject(); + var id = leftId++; + leftMap.add(id, s); + + var result; + try { + result = resultSelector(value, addRef(s, r)); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + observer.onNext(result); + + rightMap.getValues().forEach(function (v) { s.onNext(v); }); + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + leftMap.remove(id) && s.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe( + noop, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + expire) + ); + }, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + observer.onCompleted.bind(observer)) + ); + + group.add(right.subscribe( + function (value) { + var id = rightId++; + rightMap.add(id, value); + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + rightMap.remove(id); + group.remove(md); + }; + + var duration; + try { + duration = rightDurationSelector(value); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + md.setDisposable(duration.take(1).subscribe( + noop, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + expire) + ); + + leftMap.getValues().forEach(function (v) { v.onNext(value); }); + }, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }) + ); + + return r; + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers. + * + * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { + return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows. + * + * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { + if (arguments.length === 1 && typeof arguments[0] !== 'function') { + return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector); + } + return typeof windowOpeningsOrClosingSelector === 'function' ? + observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : + observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); + }; + + function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { + return windowOpenings.groupJoin(this, windowClosingSelector, function () { + return observableEmpty(); + }, function (_, window) { + return window; + }); + } + + function observableWindowWithBounaries(windowBoundaries) { + var source = this; + return new AnonymousObservable(function (observer) { + var window = new Subject(), + d = new CompositeDisposable(), + r = new RefCountDisposable(d); + + observer.onNext(addRef(window, r)); + + d.add(source.subscribe(function (x) { + window.onNext(x); + }, function (err) { + window.onError(err); + observer.onError(err); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + + d.add(windowBoundaries.subscribe(function (w) { + window.onCompleted(); + window = new Subject(); + observer.onNext(addRef(window, r)); + }, function (err) { + window.onError(err); + observer.onError(err); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + + return r; + }); + } + + function observableWindowWithClosingSelector(windowClosingSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var createWindowClose, + m = new SerialDisposable(), + d = new CompositeDisposable(m), + r = new RefCountDisposable(d), + window = new Subject(); + observer.onNext(addRef(window, r)); + d.add(source.subscribe(function (x) { + window.onNext(x); + }, function (ex) { + window.onError(ex); + observer.onError(ex); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + createWindowClose = function () { + var m1, windowClose; + try { + windowClose = windowClosingSelector(); + } catch (exception) { + observer.onError(exception); + return; + } + m1 = new SingleAssignmentDisposable(); + m.setDisposable(m1); + m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) { + window.onError(ex); + observer.onError(ex); + }, function () { + window.onCompleted(); + window = new Subject(); + observer.onNext(addRef(window, r)); + createWindowClose(); + })); + }; + createWindowClose(); + return r; + }); + } + + /** + * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. + * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. + * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. + * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. + */ + observableProto.pairwise = function () { + var source = this; + return new AnonymousObservable(function (observer) { + var previous, hasPrevious = false; + return source.subscribe( + function (x) { + if (hasPrevious) { + observer.onNext([previous, x]); + } else { + hasPrevious = true; + } + previous = x; + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer)); + }); + }; + /** + * Returns two observables which partition the observations of the source by the given function. + * The first will trigger observations for those values for which the predicate returns true. + * The second will trigger observations for those values where the predicate returns false. + * The predicate is executed once for each subscribed observer. + * Both also propagate all error observations arising from the source and each completes + * when the source completes. + * @param {Function} predicate + * The function to determine which output Observable will trigger a particular observation. + * @returns {Array} + * An array of observables. The first triggers when the predicate returns true, + * and the second triggers when the predicate returns false. + */ + observableProto.partition = function(predicate, thisArg) { + var published = this.publish().refCount(); + return [ + published.filter(predicate, thisArg), + published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) + ]; + }; + + function enumerableWhile(condition, source) { + return new Enumerable(function () { + return new Enumerator(function () { + return condition() ? + { done: false, value: source } : + { done: true, value: undefined }; + }); + }); + } + + /** + * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. + * This operator allows for a fluent style of writing queries that use the same sequence multiple times. + * + * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + observableProto.letBind = observableProto['let'] = function (func) { + return func(this); + }; + + /** + * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers 0) { + isOwner = !isAcquired; + isAcquired = true; + } + if (isOwner) { + m.setDisposable(scheduler.scheduleRecursive(function (self) { + var work; + if (q.length > 0) { + work = q.shift(); + } else { + isAcquired = false; + return; + } + var m1 = new SingleAssignmentDisposable(); + d.add(m1); + m1.setDisposable(work.subscribe(function (x) { + observer.onNext(x); + var result = null; + try { + result = selector(x); + } catch (e) { + observer.onError(e); + } + q.push(result); + activeCount++; + ensureActive(); + }, observer.onError.bind(observer), function () { + d.remove(m1); + activeCount--; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + self(); + })); + } + }; + + q.push(source); + activeCount++; + ensureActive(); + return d; + }); + }; + + /** + * Runs all observable sequences in parallel and collect their last elements. + * + * @example + * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); + * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); + * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. + */ + Observable.forkJoin = function () { + var allSources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (subscriber) { + var count = allSources.length; + if (count === 0) { + subscriber.onCompleted(); + return disposableEmpty; + } + var group = new CompositeDisposable(), + finished = false, + hasResults = new Array(count), + hasCompleted = new Array(count), + results = new Array(count); + + for (var idx = 0; idx < count; idx++) { + (function (i) { + var source = allSources[i]; + isPromise(source) && (source = observableFromPromise(source)); + group.add( + source.subscribe( + function (value) { + if (!finished) { + hasResults[i] = true; + results[i] = value; + } + }, + function (e) { + finished = true; + subscriber.onError(e); + group.dispose(); + }, + function () { + if (!finished) { + if (!hasResults[i]) { + subscriber.onCompleted(); + return; + } + hasCompleted[i] = true; + for (var ix = 0; ix < count; ix++) { + if (!hasCompleted[ix]) { return; } + } + finished = true; + subscriber.onNext(results); + subscriber.onCompleted(); + } + })); + })(idx); + } + + return group; + }); + }; + + /** + * Runs two observable sequences in parallel and combines their last elemenets. + * + * @param {Observable} second Second observable sequence. + * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. + * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. + */ + observableProto.forkJoin = function (second, resultSelector) { + var first = this; + + return new AnonymousObservable(function (observer) { + var leftStopped = false, rightStopped = false, + hasLeft = false, hasRight = false, + lastLeft, lastRight, + leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); + + isPromise(second) && (second = observableFromPromise(second)); + + leftSubscription.setDisposable( + first.subscribe(function (left) { + hasLeft = true; + lastLeft = left; + }, function (err) { + rightSubscription.dispose(); + observer.onError(err); + }, function () { + leftStopped = true; + if (rightStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + rightSubscription.setDisposable( + second.subscribe(function (right) { + hasRight = true; + lastRight = right; + }, function (err) { + leftSubscription.dispose(); + observer.onError(err); + }, function () { + rightStopped = true; + if (leftStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + return new CompositeDisposable(leftSubscription, rightSubscription); + }); + }; + + /** + * Comonadic bind operator. + * @param {Function} selector A transform function to apply to each element. + * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. + * @returns {Observable} An observable sequence which results from the comonadic bind operation. + */ + observableProto.manySelect = function (selector, scheduler) { + isScheduler(scheduler) || (scheduler = immediateScheduler); + var source = this; + return observableDefer(function () { + var chain; + + return source + .map(function (x) { + var curr = new ChainObservable(x); + + chain && chain.onNext(x); + chain = curr; + + return curr; + }) + .tap( + noop, + function (e) { chain && chain.onError(e); }, + function () { chain && chain.onCompleted(); } + ) + .observeOn(scheduler) + .map(selector); + }); + }; + + var ChainObservable = (function (__super__) { + + function subscribe (observer) { + var self = this, g = new CompositeDisposable(); + g.add(currentThreadScheduler.schedule(function () { + observer.onNext(self.head); + g.add(self.tail.mergeObservable().subscribe(observer)); + })); + + return g; + } + + inherits(ChainObservable, __super__); + + function ChainObservable(head) { + __super__.call(this, subscribe); + this.head = head; + this.tail = new AsyncSubject(); + } + + addProperties(ChainObservable.prototype, Observer, { + onCompleted: function () { + this.onNext(Observable.empty()); + }, + onError: function (e) { + this.onNext(Observable.throwException(e)); + }, + onNext: function (v) { + this.tail.onNext(v); + this.tail.onCompleted(); + } + }); + + return ChainObservable; + + }(Observable)); + + /** @private */ + var Map = (function () { + + /** + * @constructor + * @private + */ + function Map() { + this.keys = []; + this.values = []; + } + + /** + * @private + * @memberOf Map# + */ + Map.prototype['delete'] = function (key) { + var i = this.keys.indexOf(key); + if (i !== -1) { + this.keys.splice(i, 1); + this.values.splice(i, 1); + } + return i !== -1; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.get = function (key, fallback) { + var i = this.keys.indexOf(key); + return i !== -1 ? this.values[i] : fallback; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.set = function (key, value) { + var i = this.keys.indexOf(key); + if (i !== -1) { + this.values[i] = value; + } + this.values[this.keys.push(key) - 1] = value; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.size = function () { return this.keys.length; }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.has = function (key) { + return this.keys.indexOf(key) !== -1; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.getKeys = function () { return this.keys.slice(0); }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.getValues = function () { return this.values.slice(0); }; + + return Map; + }()); + + /** + * @constructor + * Represents a join pattern over observable sequences. + */ + function Pattern(patterns) { + this.patterns = patterns; + } + + /** + * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. + * + * @param other Observable sequence to match in addition to the current pattern. + * @return Pattern object that matches when all observable sequences in the pattern have an available value. + */ + Pattern.prototype.and = function (other) { + var patterns = this.patterns.slice(0); + patterns.push(other); + return new Pattern(patterns); + }; + + /** + * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. + * + * @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. + * @return Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + Pattern.prototype.thenDo = function (selector) { + return new Plan(this, selector); + }; + + function Plan(expression, selector) { + this.expression = expression; + this.selector = selector; + } + + Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { + var self = this; + var joinObservers = []; + for (var i = 0, len = this.expression.patterns.length; i < len; i++) { + joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); + } + var activePlan = new ActivePlan(joinObservers, function () { + var result; + try { + result = self.selector.apply(self, arguments); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, function () { + for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { + joinObservers[j].removeActivePlan(activePlan); + } + deactivate(activePlan); + }); + for (i = 0, len = joinObservers.length; i < len; i++) { + joinObservers[i].addActivePlan(activePlan); + } + return activePlan; + }; + + function planCreateObserver(externalSubscriptions, observable, onError) { + var entry = externalSubscriptions.get(observable); + if (!entry) { + var observer = new JoinObserver(observable, onError); + externalSubscriptions.set(observable, observer); + return observer; + } + return entry; + } + + // Active Plan + function ActivePlan(joinObserverArray, onNext, onCompleted) { + var i, joinObserver; + this.joinObserverArray = joinObserverArray; + this.onNext = onNext; + this.onCompleted = onCompleted; + this.joinObservers = new Map(); + for (i = 0; i < this.joinObserverArray.length; i++) { + joinObserver = this.joinObserverArray[i]; + this.joinObservers.set(joinObserver, joinObserver); + } + } + + ActivePlan.prototype.dequeue = function () { + var values = this.joinObservers.getValues(); + for (var i = 0, len = values.length; i < len; i++) { + values[i].queue.shift(); + } + }; + ActivePlan.prototype.match = function () { + var firstValues, i, len, isCompleted, values, hasValues = true; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + if (this.joinObserverArray[i].queue.length === 0) { + hasValues = false; + break; + } + } + if (hasValues) { + firstValues = []; + isCompleted = false; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + firstValues.push(this.joinObserverArray[i].queue[0]); + if (this.joinObserverArray[i].queue[0].kind === 'C') { + isCompleted = true; + } + } + if (isCompleted) { + this.onCompleted(); + } else { + this.dequeue(); + values = []; + for (i = 0; i < firstValues.length; i++) { + values.push(firstValues[i].value); + } + this.onNext.apply(this, values); + } + } + }; + + /** @private */ + var JoinObserver = (function (_super) { + + inherits(JoinObserver, _super); + + /** + * @constructor + * @private + */ + function JoinObserver(source, onError) { + _super.call(this); + this.source = source; + this.onError = onError; + this.queue = []; + this.activePlans = []; + this.subscription = new SingleAssignmentDisposable(); + this.isDisposed = false; + } + + var JoinObserverPrototype = JoinObserver.prototype; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.next = function (notification) { + if (!this.isDisposed) { + if (notification.kind === 'E') { + this.onError(notification.exception); + return; + } + this.queue.push(notification); + var activePlans = this.activePlans.slice(0); + for (var i = 0, len = activePlans.length; i < len; i++) { + activePlans[i].match(); + } + } + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.error = noop; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.completed = noop; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.addActivePlan = function (activePlan) { + this.activePlans.push(activePlan); + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.subscribe = function () { + this.subscription.setDisposable(this.source.materialize().subscribe(this)); + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.removeActivePlan = function (activePlan) { + var idx = this.activePlans.indexOf(activePlan); + this.activePlans.splice(idx, 1); + if (this.activePlans.length === 0) { + this.dispose(); + } + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + if (!this.isDisposed) { + this.isDisposed = true; + this.subscription.dispose(); + } + }; + + return JoinObserver; + } (AbstractObserver)); + + /** + * Creates a pattern that matches when both observable sequences have an available value. + * + * @param right Observable sequence to match with the current sequence. + * @return {Pattern} Pattern object that matches when both observable sequences have an available value. + */ + observableProto.and = function (right) { + return new Pattern([this, right]); + }; + + /** + * Matches when the observable sequence has an available value and projects the value. + * + * @param selector Selector that will be invoked for values in the source sequence. + * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + observableProto.thenDo = function (selector) { + return new Pattern([this]).thenDo(selector); + }; + + /** + * Joins together the results from several patterns. + * + * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. + * @returns {Observable} Observable sequence with the results form matching several patterns. + */ + Observable.when = function () { + var plans = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var activePlans = [], + externalSubscriptions = new Map(), + group, + i, len, + joinObserver, + joinValues, + outObserver; + outObserver = observerCreate(observer.onNext.bind(observer), function (exception) { + var values = externalSubscriptions.getValues(); + for (var j = 0, jlen = values.length; j < jlen; j++) { + values[j].onError(exception); + } + observer.onError(exception); + }, observer.onCompleted.bind(observer)); + try { + for (i = 0, len = plans.length; i < len; i++) { + activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { + var idx = activePlans.indexOf(activePlan); + activePlans.splice(idx, 1); + if (activePlans.length === 0) { + outObserver.onCompleted(); + } + })); + } + } catch (e) { + observableThrow(e).subscribe(observer); + } + group = new CompositeDisposable(); + joinValues = externalSubscriptions.getValues(); + for (i = 0, len = joinValues.length; i < len; i++) { + joinObserver = joinValues[i]; + joinObserver.subscribe(); + group.add(joinObserver); + } + return group; + }); + }; + + function observableTimerDate(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithAbsolute(dueTime, function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerDateAndPeriod(dueTime, period, scheduler) { + return new AnonymousObservable(function (observer) { + var count = 0, d = dueTime, p = normalizeTime(period); + return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { + if (p > 0) { + var now = scheduler.now(); + d = d + p; + d <= now && (d = now + p); + } + observer.onNext(count++); + self(d); + }); + }); + } + + function observableTimerTimeSpan(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { + return dueTime === period ? + new AnonymousObservable(function (observer) { + return scheduler.schedulePeriodicWithState(0, period, function (count) { + observer.onNext(count); + return count + 1; + }); + }) : + observableDefer(function () { + return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); + }); + } + + /** + * Returns an observable sequence that produces a value after each period. + * + * @example + * 1 - res = Rx.Observable.interval(1000); + * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); + * + * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. + * @returns {Observable} An observable sequence that produces a value after each period. + */ + var observableinterval = Observable.interval = function (period, scheduler) { + return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); + }; + + /** + * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. + * + * @example + * 1 - res = Rx.Observable.timer(new Date()); + * 2 - res = Rx.Observable.timer(new Date(), 1000); + * 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout); + * + * 5 - res = Rx.Observable.timer(5000); + * 6 - res = Rx.Observable.timer(5000, 1000); + * 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); + * 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. + * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. + */ + var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { + var period; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { + period = periodOrScheduler; + } else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') { + scheduler = periodOrScheduler; + } + if (dueTime instanceof Date && period === undefined) { + return observableTimerDate(dueTime.getTime(), scheduler); + } + if (dueTime instanceof Date && period !== undefined) { + period = periodOrScheduler; + return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); + } + return period === undefined ? + observableTimerTimeSpan(dueTime, scheduler) : + observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); + }; + + function observableDelayTimeSpan(source, dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + var active = false, + cancelable = new SerialDisposable(), + exception = null, + q = [], + running = false, + subscription; + subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { + var d, shouldRun; + if (notification.value.kind === 'E') { + q = []; + q.push(notification); + exception = notification.value.exception; + shouldRun = !running; + } else { + q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); + shouldRun = !active; + active = true; + } + if (shouldRun) { + if (exception !== null) { + observer.onError(exception); + } else { + d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { + var e, recurseDueTime, result, shouldRecurse; + if (exception !== null) { + return; + } + running = true; + do { + result = null; + if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { + result = q.shift().value; + } + if (result !== null) { + result.accept(observer); + } + } while (result !== null); + shouldRecurse = false; + recurseDueTime = 0; + if (q.length > 0) { + shouldRecurse = true; + recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); + } else { + active = false; + } + e = exception; + running = false; + if (e !== null) { + observer.onError(e); + } else if (shouldRecurse) { + self(recurseDueTime); + } + })); + } + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + } + + function observableDelayDate(source, dueTime, scheduler) { + return observableDefer(function () { + return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); + }); + } + + /** + * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. + * + * @example + * 1 - res = Rx.Observable.delay(new Date()); + * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); + * + * 3 - res = Rx.Observable.delay(5000); + * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); + * @memberOf Observable# + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. + * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delay = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return dueTime instanceof Date ? + observableDelayDate(this, dueTime.getTime(), scheduler) : + observableDelayTimeSpan(this, dueTime, scheduler); + }; + + /** + * Ignores values from an observable sequence which are followed by another value before dueTime. + * + * @example + * 1 - res = source.throttle(5000); // 5 seconds + * 2 - res = source.throttle(5000, scheduler); + * + * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttle = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. + * + * @example + * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second + * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds + * + * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + var source = this, timeShift; + + timeShiftOrScheduler == null && (timeShift = timeSpan); + isScheduler(scheduler) || (scheduler = timeoutScheduler); + if (typeof timeShiftOrScheduler === 'number') { + timeShift = timeShiftOrScheduler; + } else if (typeof timeShiftOrScheduler === 'object') { + timeShift = timeSpan; + scheduler = timeShiftOrScheduler; + } + return new AnonymousObservable(function (observer) { + var groupDisposable, + nextShift = timeShift, + nextSpan = timeSpan, + q = [], + refCountDisposable, + timerD = new SerialDisposable(), + totalTime = 0; + groupDisposable = new CompositeDisposable(timerD), + refCountDisposable = new RefCountDisposable(groupDisposable); + + + q.push(new Subject()); + observer.onNext(addRef(q[0], refCountDisposable)); + createTimer(); + groupDisposable.add(source.subscribe(function (x) { + var i, len; + for (i = 0, len = q.length; i < len; i++) { + q[i].onNext(x); + } + }, function (e) { + var i, len; + for (i = 0, len = q.length; i < len; i++) { + q[i].onError(e); + } + observer.onError(e); + }, function () { + var i, len; + for (i = 0, len = q.length; i < len; i++) { + q[i].onCompleted(); + } + observer.onCompleted(); + })); + + return refCountDisposable; + + function createTimer () { + var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; + timerD.setDisposable(m); + + if (nextSpan === nextShift) { + isSpan = true; + isShift = true; + } else if (nextSpan < nextShift) { + isSpan = true; + } else { + isShift = true; + } + + var newTotalTime = isSpan ? nextSpan : nextShift, + ts = newTotalTime - totalTime; + totalTime = newTotalTime; + isSpan && (nextSpan += timeShift); + isShift && (nextShift += timeShift); + + m.setDisposable(scheduler.scheduleWithRelative(ts, function () { + var s; + if (isShift) { + s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + } + if (isSpan) { + s = q.shift(); + s.onCompleted(); + } + createTimer(); + })); + } + }); + }; + + /** + * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. + * @example + * 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items + * 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items + * + * @memberOf Observable# + * @param {Number} timeSpan Maximum time length of a window. + * @param {Number} count Maximum element count of a window. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var createTimer, + groupDisposable, + n = 0, + refCountDisposable, + s = new Subject() + timerD = new SerialDisposable(), + windowId = 0; + groupDisposable = new CompositeDisposable(timerD); + refCountDisposable = new RefCountDisposable(groupDisposable); + + observer.onNext(addRef(s, refCountDisposable)); + createTimer(0); + groupDisposable.add(source.subscribe(function (x) { + var newId = 0, newWindow = false; + s.onNext(x); + n++; + if (n === count) { + newWindow = true; + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + } + newWindow && createTimer(newId); + }, function (e) { + s.onError(e); + observer.onError(e); + }, function () { + s.onCompleted(); + observer.onCompleted(); + })); + + return refCountDisposable; + + function createTimer(id) { + var m = new SingleAssignmentDisposable(); + timerD.setDisposable(m); + m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { + var newId; + if (id !== windowId) { return; } + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + createTimer(newId); + })); + } + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. + * + * @example + * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second + * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds + * + * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. + * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); + }; + + /** + * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. + * + * @example + * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array + * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array + * + * @param {Number} timeSpan Maximum time length of a buffer. + * @param {Number} count Maximum element count of a buffer. + * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { + return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { + return x.toArray(); + }); + }; + + /** + * Records the time interval between consecutive values in an observable sequence. + * + * @example + * 1 - res = source.timeInterval(); + * 2 - res = source.timeInterval(Rx.Scheduler.timeout); + * + * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with time interval information on values. + */ + observableProto.timeInterval = function (scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return observableDefer(function () { + var last = scheduler.now(); + return source.map(function (x) { + var now = scheduler.now(), span = now - last; + last = now; + return { value: x, interval: span }; + }); + }); + }; + + /** + * Records the timestamp for each value in an observable sequence. + * + * @example + * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } + * 2 - res = source.timestamp(Rx.Scheduler.timeout); + * + * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with timestamp information on values. + */ + observableProto.timestamp = function (scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return this.map(function (x) { + return { value: x, timestamp: scheduler.now() }; + }); + }; + + function sampleObservable(source, sampler) { + + return new AnonymousObservable(function (observer) { + var atEnd, value, hasValue; + + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + observer.onNext(value); + } + atEnd && observer.onCompleted(); + } + + return new CompositeDisposable( + source.subscribe(function (newValue) { + hasValue = true; + value = newValue; + }, observer.onError.bind(observer), function () { + atEnd = true; + }), + sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) + ); + }); + } + + /** + * Samples the observable sequence at each interval. + * + * @example + * 1 - res = source.sample(sampleObservable); // Sampler tick sequence + * 2 - res = source.sample(5000); // 5 seconds + * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. + * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Sampled observable sequence. + */ + observableProto.sample = function (intervalOrSampler, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return typeof intervalOrSampler === 'number' ? + sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : + sampleObservable(this, intervalOrSampler); + }; + + /** + * Returns the source observable sequence or the other observable sequence if dueTime elapses. + * + * @example + * 1 - res = source.timeout(new Date()); // As a date + * 2 - res = source.timeout(5000); // 5 seconds + * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable + * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable + * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable + * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. + * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. + * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeout = function (dueTime, other, scheduler) { + other || (other = observableThrow(new Error('Timeout'))); + isScheduler(scheduler) || (scheduler = timeoutScheduler); + + var source = this, schedulerMethod = dueTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + + return new AnonymousObservable(function (observer) { + var id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + + subscription.setDisposable(original); + + var createTimer = function () { + var myId = id; + timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { + if (id === myId) { + isPromise(other) && (other = observableFromPromise(other)); + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + createTimer(); + + original.setDisposable(source.subscribe(function (x) { + if (!switched) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + if (!switched) { + id++; + observer.onError(e); + } + }, function () { + if (!switched) { + id++; + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithAbsoluteTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return new Date(); } + * }); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { + hasResult && observer.onNext(result); + + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithRelativeTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return 500; } + * ); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithRelative(0, function (self) { + hasResult && observer.onNext(result); + + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Time shifts the observable sequence by delaying the subscription. + * + * @example + * 1 - res = source.delaySubscription(5000); // 5s + * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Number} dueTime Absolute or relative time to perform the subscription at. + * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delaySubscription = function (dueTime, scheduler) { + return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty); + }; + + /** + * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only + * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector + * + * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. + * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { + var source = this, subDelay, selector; + if (typeof subscriptionDelay === 'function') { + selector = subscriptionDelay; + } else { + subDelay = subscriptionDelay; + selector = delayDurationSelector; + } + return new AnonymousObservable(function (observer) { + var delays = new CompositeDisposable(), atEnd = false, done = function () { + if (atEnd && delays.length === 0) { + observer.onCompleted(); + } + }, subscription = new SerialDisposable(), start = function () { + subscription.setDisposable(source.subscribe(function (x) { + var delay; + try { + delay = selector(x); + } catch (error) { + observer.onError(error); + return; + } + var d = new SingleAssignmentDisposable(); + delays.add(d); + d.setDisposable(delay.subscribe(function () { + observer.onNext(x); + delays.remove(d); + done(); + }, observer.onError.bind(observer), function () { + observer.onNext(x); + delays.remove(d); + done(); + })); + }, observer.onError.bind(observer), function () { + atEnd = true; + subscription.dispose(); + done(); + })); + }; + + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(function () { + start(); + }, observer.onError.bind(observer), function () { start(); })); + } + + return new CompositeDisposable(subscription, delays); + }); + }; + + /** + * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. + * + * @example + * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); + * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); + * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); + * + * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). + * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. + * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { + if (arguments.length === 1) { + timeoutdurationSelector = firstTimeout; + var firstTimeout = observableNever(); + } + other || (other = observableThrow(new Error('Timeout'))); + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); + + subscription.setDisposable(original); + + var id = 0, switched = false, setTimer = function (timeout) { + var myId = id, timerWins = function () { + return id === myId; + }; + var d = new SingleAssignmentDisposable(); + timer.setDisposable(d); + d.setDisposable(timeout.subscribe(function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + d.dispose(); + }, function (e) { + if (timerWins()) { + observer.onError(e); + } + }, function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + setTimer(firstTimeout); + var observerWins = function () { + var res = !switched; + if (res) { + id++; + } + return res; + }; + + original.setDisposable(source.subscribe(function (x) { + if (observerWins()) { + observer.onNext(x); + var timeout; + try { + timeout = timeoutdurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + setTimer(timeout); + } + }, function (e) { + if (observerWins()) { + observer.onError(e); + } + }, function () { + if (observerWins()) { + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); + * + * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttleWithSelector = function (throttleDurationSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { + var throttle; + try { + throttle = throttleDurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + hasValue = true; + value = x; + id++; + var currentid = id, d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(throttle.subscribe(function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + }, observer.onError.bind(observer), function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + })); + }, function (e) { + cancelable.dispose(); + observer.onError(e); + hasValue = false; + id++; + }, function () { + cancelable.dispose(); + if (hasValue) { + observer.onNext(value); + } + observer.onCompleted(); + hasValue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * 1 - res = source.skipLastWithTime(5000); + * 2 - res = source.skipLastWithTime(5000, scheduler); + * + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for skipping elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. + */ + observableProto.skipLastWithTime = function (duration, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. + * + * @example + * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var q = []; + + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { + observer.onNext(next.value); + } + } + + observer.onCompleted(); + }); + }); + }; + + /** + * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastBufferWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var q = []; + + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(), res = []; + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { + res.push(next.value); + } + } + + observer.onNext(res); + observer.onCompleted(); + }); + }); + }; + + /** + * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + observableProto.takeWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), source.subscribe(observer)); + }); + }; + + /** + * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.skipWithTime(5000, [optional scheduler]); + * + * @description + * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. + * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded + * may not execute immediately, despite the zero due time. + * + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. + * @param {Number} duration Duration for skipping elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + observableProto.skipWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false; + return new CompositeDisposable( + scheduler.scheduleWithRelative(duration, function () { open = true; }), + source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); + }); + }; + + /** + * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. + * + * @examples + * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); + * 2 - res = source.skipUntilWithTime(5000, [optional scheduler]); + * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. + * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped until the specified start time. + */ + observableProto.skipUntilWithTime = function (startTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = startTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (observer) { + var open = false; + + return new CompositeDisposable( + scheduler[schedulerMethod](startTime, function () { open = true; }), + source.subscribe( + function (x) { open && observer.onNext(x); }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer))); + }); + }; + + /** + * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); + * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); + * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. + * @param {Scheduler} scheduler Scheduler to run the timer on. + * @returns {Observable} An observable sequence with the elements taken until the specified end time. + */ + observableProto.takeUntilWithTime = function (endTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = endTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { + observer.onCompleted(); + }), source.subscribe(observer)); + }); + }; + + /* + * Performs a exclusive waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @returns {Observable} A exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusive = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasCurrent = false, + isStopped = false, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + if (!hasCurrent) { + hasCurrent = true; + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + var innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + innerSubscription.setDisposable(innerSource.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (!hasCurrent && g.length === 1) { + observer.onCompleted(); + } + })); + + return g; + }); + }; + /* + * Performs a exclusive map waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @param {Function} selector Selector to invoke for every item in the current subscription. + * @param {Any} [thisArg] An optional context to invoke with the selector parameter. + * @returns {Observable} An exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusiveMap = function (selector, thisArg) { + var sources = this; + return new AnonymousObservable(function (observer) { + var index = 0, + hasCurrent = false, + isStopped = true, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + + if (!hasCurrent) { + hasCurrent = true; + + innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + innerSubscription.setDisposable(innerSource.subscribe( + function (x) { + var result; + try { + result = selector.call(thisArg, x, index++, innerSource); + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(result); + }, + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (g.length === 1 && !hasCurrent) { + observer.onCompleted(); + } + })); + return g; + }); + }; + /** Provides a set of extension methods for virtual time scheduling. */ + Rx.VirtualTimeScheduler = (function (__super__) { + + function notImplemented() { + throw new Error('Not implemented'); + } + + function localNow() { + return this.toDateTimeOffset(this.clock); + } + + function scheduleNow(state, action) { + return this.scheduleAbsoluteWithState(state, this.clock, action); + } + + function scheduleRelative(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + inherits(VirtualTimeScheduler, __super__); + + /** + * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. + * + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function VirtualTimeScheduler(initialClock, comparer) { + this.clock = initialClock; + this.comparer = comparer; + this.isEnabled = false; + this.queue = new PriorityQueue(1024); + __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + VirtualTimeSchedulerPrototype.add = notImplemented; + + /** + * Converts an absolute time to a number + * @param {Any} The absolute time. + * @returns {Number} The absolute time in ms + */ + VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + VirtualTimeSchedulerPrototype.toRelative = notImplemented; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { + var s = new SchedulePeriodicRecursive(this, state, period, action); + return s.start(); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { + var runAt = this.add(this.clock, dueTime); + return this.scheduleAbsoluteWithState(state, runAt, action); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { + return this.scheduleRelativeWithState(action, dueTime, invokeAction); + }; + + /** + * Starts the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.start = function () { + if (!this.isEnabled) { + this.isEnabled = true; + do { + var next = this.getNext(); + if (next !== null) { + this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); + next.invoke(); + } else { + this.isEnabled = false; + } + } while (this.isEnabled); + } + }; + + /** + * Stops the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.stop = function () { + this.isEnabled = false; + }; + + /** + * Advances the scheduler's clock to the specified time, running all work till that point. + * @param {Number} time Absolute time to advance the scheduler's clock to. + */ + VirtualTimeSchedulerPrototype.advanceTo = function (time) { + var dueToClock = this.comparer(this.clock, time); + if (this.comparer(this.clock, time) > 0) { + throw new Error(argumentOutOfRange); + } + if (dueToClock === 0) { + return; + } + if (!this.isEnabled) { + this.isEnabled = true; + do { + var next = this.getNext(); + if (next !== null && this.comparer(next.dueTime, time) <= 0) { + this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); + next.invoke(); + } else { + this.isEnabled = false; + } + } while (this.isEnabled); + this.clock = time; + } + }; + + /** + * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.advanceBy = function (time) { + var dt = this.add(this.clock, time), + dueToClock = this.comparer(this.clock, dt); + if (dueToClock > 0) { throw new Error(argumentOutOfRange); } + if (dueToClock === 0) { return; } + + this.advanceTo(dt); + }; + + /** + * Advances the scheduler's clock by the specified relative time. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.sleep = function (time) { + var dt = this.add(this.clock, time); + if (this.comparer(this.clock, dt) >= 0) { throw new Error(argumentOutOfRange); } + + this.clock = dt; + }; + + /** + * Gets the next scheduled item to be executed. + * @returns {ScheduledItem} The next scheduled item. + */ + VirtualTimeSchedulerPrototype.getNext = function () { + while (this.queue.length > 0) { + var next = this.queue.peek(); + if (next.isCancelled()) { + this.queue.dequeue(); + } else { + return next; + } + } + return null; + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Scheduler} scheduler Scheduler to execute the action on. + * @param {Number} dueTime Absolute time at which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { + return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Absolute time at which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { + var self = this; + + function run(scheduler, state1) { + self.queue.remove(si); + return action(scheduler, state1); + } + + var si = new ScheduledItem(this, state, run, dueTime, this.comparer); + this.queue.enqueue(si); + + return si.disposable; + }; + + return VirtualTimeScheduler; + }(Scheduler)); + + /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ + Rx.HistoricalScheduler = (function (__super__) { + inherits(HistoricalScheduler, __super__); + + /** + * Creates a new historical scheduler with the specified initial clock value. + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function HistoricalScheduler(initialClock, comparer) { + var clock = initialClock == null ? 0 : initialClock; + var cmp = comparer || defaultSubComparer; + __super__.call(this, clock, cmp); + } + + var HistoricalSchedulerProto = HistoricalScheduler.prototype; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + HistoricalSchedulerProto.add = function (absolute, relative) { + return absolute + relative; + }; + + HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { + return new Date(absolute).getTime(); + }; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * @memberOf HistoricalScheduler + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + HistoricalSchedulerProto.toRelative = function (timeSpan) { + return timeSpan; + }; + + return HistoricalScheduler; + }(Rx.VirtualTimeScheduler)); + var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { + inherits(AnonymousObservable, __super__); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } + + return typeof subscriber === 'function' ? + disposableCreate(subscriber) : + disposableEmpty; + } + + function AnonymousObservable(subscribe) { + if (!(this instanceof AnonymousObservable)) { + return new AnonymousObservable(subscribe); + } + + function s(observer) { + var setDisposable = function () { + try { + autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); + } catch (e) { + if (!autoDetachObserver.fail(e)) { + throw e; + } + } + }; + + var autoDetachObserver = new AutoDetachObserver(observer); + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.schedule(setDisposable); + } else { + setDisposable(); + } + + return autoDetachObserver; + } + + __super__.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + /** @private */ + var AutoDetachObserver = (function (_super) { + inherits(AutoDetachObserver, _super); + + function AutoDetachObserver(observer) { + _super.call(this); + this.observer = observer; + this.m = new SingleAssignmentDisposable(); + } + + var AutoDetachObserverPrototype = AutoDetachObserver.prototype; + + AutoDetachObserverPrototype.next = function (value) { + var noError = false; + try { + this.observer.onNext(value); + noError = true; + } catch (e) { + throw e; + } finally { + if (!noError) { + this.dispose(); + } + } + }; + + AutoDetachObserverPrototype.error = function (exn) { + try { + this.observer.onError(exn); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.completed = function () { + try { + this.observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; + /* @private */ + AutoDetachObserverPrototype.disposable = function (value) { + return arguments.length ? this.getDisposable() : setDisposable(value); + }; + + AutoDetachObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + /** @private */ + var GroupedObservable = (function (_super) { + inherits(GroupedObservable, _super); + + function subscribe(observer) { + return this.underlyingObservable.subscribe(observer); + } + + /** + * @constructor + * @private + */ + function GroupedObservable(key, underlyingObservable, mergedDisposable) { + _super.call(this, subscribe); + this.key = key; + this.underlyingObservable = !mergedDisposable ? + underlyingObservable : + new AnonymousObservable(function (observer) { + return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); + }); + } + + return GroupedObservable; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.exception) { + observer.onError(this.exception); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, _super); + + /** + * Creates a subject. + * @constructor + */ + function Subject() { + _super.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + } + + addProperties(Subject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (__super__) { + + function subscribe(observer) { + checkDisposed.call(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + var ex = this.exception, + hv = this.hasValue, + v = this.value; + + if (ex) { + observer.onError(ex); + } else if (hv) { + observer.onNext(v); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, __super__); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + __super__.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.value = null; + this.hasValue = false; + this.observers = []; + this.exception = null; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed.call(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var o, i, len; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var os = this.observers.slice(0), + v = this.value, + hv = this.hasValue; + + if (hv) { + for (i = 0, len = os.length; i < len; i++) { + o = os[i]; + o.onNext(v); + o.onCompleted(); + } + } else { + for (i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the error. + * @param {Mixed} error The Error to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed.call(this); + if (this.isStopped) { return; } + this.value = value; + this.hasValue = true; + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { + inherits(AnonymousSubject, __super__); + + function AnonymousSubject(observer, observable) { + this.observer = observer; + this.observable = observable; + __super__.call(this, this.observable.subscribe.bind(this.observable)); + } + + addProperties(AnonymousSubject.prototype, Observer, { + onCompleted: function () { + this.observer.onCompleted(); + }, + onError: function (exception) { + this.observer.onError(exception); + }, + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } +}.call(this)); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.all.compat.min.js b/ajax/libs/rxjs/2.3.9/rx.all.compat.min.js new file mode 100644 index 000000000..87d9ba3ae --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.all.compat.min.js @@ -0,0 +1,3 @@ +(function(a){function b(){if(this.isDisposed)throw new Error(rb)}function c(a){var b=typeof a;return a&&("function"==b||"object"==b)||!1}function d(a){var b=[];if(!c(a))return b;Ob.nonEnumArgs&&a.length&&h(a)&&(a=Qb.call(a));var d=Ob.enumPrototypes&&"function"==typeof a,e=Ob.enumErrorProps&&(a===Ib||a instanceof Error);for(var f in a)d&&"prototype"==f||e&&("message"==f||"name"==f)||b.push(f);if(Ob.nonEnumShadows&&a!==Jb){var g=a.constructor,i=-1,j=Mb.length;if(a===(g&&g.prototype))var k=a===stringProto?Eb:a===Ib?zb:Fb.call(a),l=Nb[k];for(;++i-1:void 0});return c.pop(),d.pop(),result}function k(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:Qb.call(a)}function l(a,b){for(var c=new Array(a),d=0;a>d;d++)c[d]=b();return c}function m(a,b){this.scheduler=a,this.disposable=b,this.isDisposed=!1}function n(a){return"number"==typeof a&&ab.isFinite(a)}function o(b){return b[sb]!==a}function p(a){var b=+a;return 0===b?b:isNaN(b)?b:0>b?-1:1}function q(a){var b=+a.length;return isNaN(b)?0:0!==b&&n(b)?(b=p(b)*Math.floor(Math.abs(b)),0>=b?0:b>Ic?Ic:b):b}function r(a){return"[object Function]"===Object.prototype.toString.call(a)&&"function"==typeof a}function s(a,b){return new kd(function(c){var d=new cc,e=new SerialDisposable;return e.setDisposable(d),d.setDisposable(a.subscribe(c.onNext.bind(c),function(a){var d,f;try{f=b(a)}catch(g){return void c.onError(g)}nb(f)&&(f=Fc(f)),d=new cc,e.setDisposable(d),d.setDisposable(f.subscribe(c))},c.onCompleted.bind(c))),e})}function t(a,b){var c=this;return new kd(function(d){var e=0,f=a.length;return c.subscribe(function(c){if(f>e){var g,h=a[e++];try{g=b(c,h)}catch(i){return void d.onError(i)}d.onNext(g)}else d.onCompleted()},d.onError.bind(d),d.onCompleted.bind(d))})}function u(a,b,c){return a.map(function(a,d){var e=b.call(c,a,d);return nb(e)?Fc(e):e}).concatAll()}function v(a,b,c){for(var d=0,e=a.length;e>d;d++)if(c(a[d],b))return d;return-1}function w(a){this.comparer=a,this.set=[]}function x(a,b,c){return a.map(function(a,d){var e=b.call(c,a,d);return nb(e)?Fc(e):e}).mergeObservable()}function y(a,b,c){return new kd(function(d){var e=!1,f=null,g=[];return a.subscribe(function(a){var h,i;try{i=b(a)}catch(j){return void d.onError(j)}if(h=0,e)try{h=c(i,f)}catch(k){return void d.onError(k)}else e=!0,f=i;h>0&&(f=i,g=[]),h>=0&&g.push(a)},d.onError.bind(d),function(){d.onNext(g),d.onCompleted()})})}function z(a){if(0===a.length)throw new Error(pb);return a[0]}function A(a,b,c){return new kd(function(d){var e=0,f=b.length;return a.subscribe(function(a){var g=!1;try{f>e&&(g=c(a,b[e++]))}catch(h){return void d.onError(h)}g||(d.onNext(!1),d.onCompleted())},d.onError.bind(d),function(){d.onNext(e===f),d.onCompleted()})})}function B(a,b,c,d){if(0>b)throw new Error(qb);return new kd(function(e){var f=b;return a.subscribe(function(a){0===f&&(e.onNext(a),e.onCompleted()),f--},e.onError.bind(e),function(){c?(e.onNext(d),e.onCompleted()):e.onError(new Error(qb))})})}function C(a,b,c){return new kd(function(d){var e=c,f=!1;return a.subscribe(function(a){f?d.onError(new Error("Sequence contains more than one element")):(e=a,f=!0)},d.onError.bind(d),function(){f||b?(d.onNext(e),d.onCompleted()):d.onError(new Error(pb))})})}function D(a,b,c){return new kd(function(d){return a.subscribe(function(a){d.onNext(a),d.onCompleted()},d.onError.bind(d),function(){b?(d.onNext(c),d.onCompleted()):d.onError(new Error(pb))})})}function E(a,b,c){return new kd(function(d){var e=c,f=!1;return a.subscribe(function(a){e=a,f=!0},d.onError.bind(d),function(){f||b?(d.onNext(e),d.onCompleted()):d.onError(new Error(pb))})})}function F(b,c,d,e){return new kd(function(f){var g=0;return b.subscribe(function(a){var h;try{h=c.call(d,a,g,b)}catch(i){return void f.onError(i)}h?(f.onNext(e?g:a),f.onCompleted()):g++},f.onError.bind(f),function(){f.onNext(e?-1:a),f.onCompleted()})})}function G(a,b){return new kd(function(c){var d=new b;return a.subscribe(d.add.bind(d),c.onError.bind(c),function(){c.onNext(d),c.onCompleted()})})}function H(a,b,c,d){return new kd(function(e){var f=new b;return a.subscribe(function(a){var b;try{b=c(a)}catch(g){return void e.onError(g)}var h=a;if(d)try{h=d(a)}catch(g){return void e.onError(g)}f.set(b,h)},e.onError.bind(e),function(){e.onNext(f),e.onCompleted()})})}function I(a){var b=function(){this.cancelBubble=!0},c=function(){if(this.bubbledKeyCode=this.keyCode,this.ctrlKey)try{this.keyCode=0}catch(a){}this.defaultPrevented=!0,this.returnValue=!1,this.modified=!0};if(a||(a=ab.event),!a.target)switch(a.target=a.target||a.srcElement,"mouseover"==a.type&&(a.relatedTarget=a.fromElement),"mouseout"==a.type&&(a.relatedTarget=a.toElement),a.stopPropagation||(a.stopPropagation=b,a.preventDefault=c),a.type){case"keypress":var d="charCode"in a?a.charCode:a.keyCode;10==d?(d=0,a.keyCode=13):13==d||27==d?d=0:3==d&&(d=99),a.charCode=d,a.keyChar=a.charCode?String.fromCharCode(a.charCode):""}return a}function J(a,b,c){if(a.addEventListener)return a.addEventListener(b,c,!1),ac(function(){a.removeEventListener(b,c,!1)});if(a.attachEvent){var d=function(a){c(I(a))};return a.attachEvent("on"+b,d),ac(function(){a.detachEvent("on"+b,d)})}return a["on"+b]=c,ac(function(){a["on"+b]=null})}function K(a,b,c){var d=new Zb;if("[object NodeList]"===Object.prototype.toString.call(a))for(var e=0,f=a.length;f>e;e++)d.add(K(a.item(e),b,c));else a&&d.add(J(a,b,c));return d}function L(a,b,c){return new kd(function(d){function e(a,b){j[b]=a;var e;if(g[b]=!0,h||(h=g.every(ib))){try{e=c.apply(null,j)}catch(f){return void d.onError(f)}d.onNext(e)}else i&&d.onCompleted()}var f=2,g=[!1,!1],h=!1,i=!1,j=new Array(f);return new Zb(a.subscribe(function(a){e(a,0)},d.onError.bind(d),function(){i=!0,d.onCompleted()}),b.subscribe(function(a){e(a,1)},d.onError.bind(d)))})}function M(a,b){return a.groupJoin(this,b,function(){return Hc()},function(a,b){return b})}function N(a){var b=this;return new kd(function(c){var d=new nd,e=new Zb,f=new dc(e);return c.onNext(Tb(d,f)),e.add(b.subscribe(function(a){d.onNext(a)},function(a){d.onError(a),c.onError(a)},function(){d.onCompleted(),c.onCompleted()})),e.add(a.subscribe(function(){d.onCompleted(),d=new nd,c.onNext(Tb(d,f))},function(a){d.onError(a),c.onError(a)},function(){d.onCompleted(),c.onCompleted()})),f})}function O(a){var b=this;return new kd(function(c){var d,e=new SerialDisposable,f=new Zb(e),g=new dc(f),h=new nd;return c.onNext(Tb(h,g)),f.add(b.subscribe(function(a){h.onNext(a)},function(a){h.onError(a),c.onError(a)},function(){h.onCompleted(),c.onCompleted()})),d=function(){var b,f;try{f=a()}catch(i){return void c.onError(i)}b=new cc,e.setDisposable(b),b.setDisposable(f.take(1).subscribe(gb,function(a){h.onError(a),c.onError(a)},function(){h.onCompleted(),h=new nd,c.onNext(Tb(h,g)),d()}))},d(),g})}function P(b,c){return new tc(function(){return new sc(function(){return b()?{done:!1,value:c}:{done:!0,value:a}})})}function Q(a){this.patterns=a}function R(a,b){this.expression=a,this.selector=b}function S(a,b,c){var d=a.get(b);if(!d){var e=new hd(b,c);return a.set(b,e),e}return d}function T(a,b,c){var d,e;for(this.joinObserverArray=a,this.onNext=b,this.onCompleted=c,this.joinObservers=new gd,d=0;d0){var b=c.now();f+=g,b>=f&&(f=b+g)}d.onNext(e++),a(f)})})}function W(a,b){return new kd(function(c){return b.scheduleWithRelative(gc(a),function(){c.onNext(0),c.onCompleted()})})}function X(a,b,c){return a===b?new kd(function(a){return c.schedulePeriodicWithState(0,b,function(b){return a.onNext(b),b+1})}):Gc(function(){return V(c.now()+a,b,c)})}function Y(a,b,c){return new kd(function(d){var e,f=!1,g=new SerialDisposable,h=null,i=[],j=!1;return e=a.materialize().timestamp(c).subscribe(function(a){var e,k;"E"===a.value.kind?(i=[],i.push(a),h=a.value.exception,k=!j):(i.push({value:a.value,timestamp:a.timestamp+b}),k=!f,f=!0),k&&(null!==h?d.onError(h):(e=new cc,g.setDisposable(e),e.setDisposable(c.scheduleRecursiveWithRelative(b,function(a){var b,e,g,k;if(null===h){j=!0;do g=null,i.length>0&&i[0].timestamp-c.now()<=0&&(g=i.shift().value),null!==g&&g.accept(d);while(null!==g);k=!1,e=0,i.length>0?(k=!0,e=Math.max(0,i[0].timestamp-c.now())):f=!1,b=h,j=!1,null!==b?d.onError(b):k&&a(e)}}))))}),new Zb(e,g)})}function Z(a,b,c){return Gc(function(){return Y(a,b-c.now(),c)})}function $(a,b){return new kd(function(c){function d(){g&&(g=!1,c.onNext(f)),e&&c.onCompleted()}var e,f,g;return new Zb(a.subscribe(function(a){g=!0,f=a},c.onError.bind(c),function(){e=!0}),b.subscribe(d,c.onError.bind(c),d))})}var _={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},ab=_[typeof window]&&window||this,bb=_[typeof exports]&&exports&&!exports.nodeType&&exports,cb=_[typeof module]&&module&&!module.nodeType&&module,db=cb&&cb.exports===bb&&bb,eb=_[typeof global]&&global;!eb||eb.global!==eb&&eb.window!==eb||(ab=eb);var fb={internals:{},config:{Promise:ab.Promise},helpers:{}},gb=fb.helpers.noop=function(){},hb=(fb.helpers.notDefined=function(a){return"undefined"==typeof a},fb.helpers.isScheduler=function(a){return a instanceof fb.Scheduler}),ib=fb.helpers.identity=function(a){return a},jb=(fb.helpers.pluck=function(a){return function(b){return b[a]}},fb.helpers.just=function(a){return function(){return a}},fb.helpers.defaultNow=function(){return Date.now?Date.now:function(){return+new Date}}()),kb=fb.helpers.defaultComparer=function(a,b){return Pb(a,b)},lb=fb.helpers.defaultSubComparer=function(a,b){return a>b?1:b>a?-1:0},mb=(fb.helpers.defaultKeySerializer=function(a){return a.toString()},fb.helpers.defaultError=function(a){throw a}),nb=fb.helpers.isPromise=function(a){return!!a&&"function"==typeof a.then},ob=(fb.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},fb.helpers.not=function(a){return!a}),pb="Sequence contains no elements.",qb="Argument out of range",rb="Object has been disposed",sb="function"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";ab.Set&&"function"==typeof(new ab.Set)["@@iterator"]&&(sb="@@iterator");var tb,ub={done:!0,value:a},vb="[object Arguments]",wb="[object Array]",xb="[object Boolean]",yb="[object Date]",zb="[object Error]",Ab="[object Function]",Bb="[object Number]",Cb="[object Object]",Db="[object RegExp]",Eb="[object String]",Fb=Object.prototype.toString,Gb=Object.prototype.hasOwnProperty,Hb=Fb.call(arguments)==vb,Ib=Error.prototype,Jb=Object.prototype,Kb=Jb.propertyIsEnumerable;try{tb=!(Fb.call(document)==Cb&&!({toString:0}+""))}catch(Lb){tb=!0}var Mb=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Nb={};Nb[wb]=Nb[yb]=Nb[Bb]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},Nb[xb]=Nb[Eb]={constructor:!0,toString:!0,valueOf:!0},Nb[zb]=Nb[Ab]=Nb[Db]={constructor:!0,toString:!0},Nb[Cb]={constructor:!0};var Ob={};!function(){var a=function(){this.x=1},b=[];a.prototype={valueOf:1,y:1};for(var c in new a)b.push(c);for(c in arguments);Ob.enumErrorProps=Kb.call(Ib,"message")||Kb.call(Ib,"name"),Ob.enumPrototypes=Kb.call(a,"prototype"),Ob.nonEnumArgs=0!=c,Ob.nonEnumShadows=!/valueOf/.test(b)}(1),Hb||(h=function(a){return a&&"object"==typeof a?Gb.call(a,"callee"):!1}),i(/x/)&&(i=function(a){return"function"==typeof a&&Fb.call(a)==Ab});var Pb=fb.internals.isEqual=function(a,b){return j(a,b,[],[])},Qb=Array.prototype.slice,Rb=({}.hasOwnProperty,this.inherits=fb.internals.inherits=function(a,b){function c(){this.constructor=a}c.prototype=b.prototype,a.prototype=new c}),Sb=fb.internals.addProperties=function(a){for(var b=Qb.call(arguments,1),c=0,d=b.length;d>c;c++){var e=b[c];for(var f in e)a[f]=e[f]}},Tb=fb.internals.addRef=function(a,b){return new kd(function(c){return new Zb(b.getDisposable(),a.subscribe(c))})};Function.prototype.bind||(Function.prototype.bind=function(a){var b=this,c=Qb.call(arguments,1),d=function(){function e(){}if(this instanceof d){e.prototype=b.prototype;var f=new e,g=b.apply(f,c.concat(Qb.call(arguments)));return Object(g)===g?g:f}return b.apply(a,c.concat(Qb.call(arguments)))};return d}),Array.prototype.forEach||(Array.prototype.forEach=function(a,b){var c,d;if(null==this)throw new TypeError(" this is null or not defined");var e=Object(this),f=e.length>>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(arguments.length>1&&(c=b),d=0;f>d;){var g;d in e&&(g=e[d],a.call(c,g,d,e)),d++}});var Ub=Object("a"),Vb="a"!=Ub[0]||!(0 in Ub);Array.prototype.every||(Array.prototype.every=function(a){var b=Object(this),c=Vb&&{}.toString.call(this)==Eb?this.split(""):b,d=c.length>>>0,e=arguments[1];if({}.toString.call(a)!=Ab)throw new TypeError(a+" is not a function");for(var f=0;d>f;f++)if(f in c&&!a.call(e,c[f],f,b))return!1;return!0}),Array.prototype.map||(Array.prototype.map=function(a){var b=Object(this),c=Vb&&{}.toString.call(this)==Eb?this.split(""):b,d=c.length>>>0,e=Array(d),f=arguments[1];if({}.toString.call(a)!=Ab)throw new TypeError(a+" is not a function");for(var g=0;d>g;g++)g in c&&(e[g]=a.call(f,c[g],g,b));return e}),Array.prototype.filter||(Array.prototype.filter=function(a){for(var b,c=[],d=new Object(this),e=0,f=d.length>>>0;f>e;e++)b=d[e],e in d&&a.call(arguments[1],b,e,d)&&c.push(b);return c}),Array.isArray||(Array.isArray=function(a){return{}.toString.call(a)==wb}),Array.prototype.indexOf||(Array.prototype.indexOf=function(a){var b=Object(this),c=b.length>>>0;if(0===c)return-1;var d=0;if(arguments.length>1&&(d=Number(arguments[1]),d!==d?d=0:0!==d&&1/0!=d&&d!==-1/0&&(d=(d>0||-1)*Math.floor(Math.abs(d)))),d>=c)return-1;for(var e=d>=0?d:Math.max(c-Math.abs(d),0);c>e;e++)if(e in b&&b[e]===a)return e;return-1});var Wb=function(a,b){this.id=a,this.value=b};Wb.prototype.compareTo=function(a){var b=this.value.compareTo(a.value);return 0===b&&(b=this.id-a.id),b};var Xb=fb.internals.PriorityQueue=function(a){this.items=new Array(a),this.length=0},Yb=Xb.prototype;Yb.isHigherPriority=function(a,b){return this.items[a].compareTo(this.items[b])<0},Yb.percolate=function(a){if(!(a>=this.length||0>a)){var b=a-1>>1;if(!(0>b||b===a)&&this.isHigherPriority(a,b)){var c=this.items[a];this.items[a]=this.items[b],this.items[b]=c,this.percolate(b)}}},Yb.heapify=function(b){if(b===a&&(b=0),!(b>=this.length||0>b)){var c=2*b+1,d=2*b+2,e=b;if(cb;b++)a[b].dispose()}},$b.toArray=function(){return this.disposables.slice(0)};var _b=fb.Disposable=function(a){this.isDisposed=!1,this.action=a||gb};_b.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var ac=_b.create=function(a){return new _b(a)},bc=_b.empty={dispose:gb},cc=fb.SingleAssignmentDisposable=SerialDisposable=fb.SerialDisposable=function(){function a(){this.isDisposed=!1,this.current=null}var b=a.prototype;return b.getDisposable=function(){return this.current},b.setDisposable=function(a){var b,c=this.isDisposed;c||(b=this.current,this.current=a),b&&b.dispose(),c&&a&&a.dispose()},b.dispose=function(){var a;this.isDisposed||(this.isDisposed=!0,a=this.current,this.current=null),a&&a.dispose()},a}(),dc=fb.RefCountDisposable=function(){function a(a){this.disposable=a,this.disposable.count++,this.isInnerDisposed=!1}function b(a){this.underlyingDisposable=a,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return a.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},b.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},b.prototype.getDisposable=function(){return this.isDisposed?bc:new a(this)},b}();m.prototype.dispose=function(){var a=this;this.scheduler.schedule(function(){a.isDisposed||(a.isDisposed=!0,a.disposable.dispose())})};var ec=fb.internals.ScheduledItem=function(a,b,c,d,e){this.scheduler=a,this.state=b,this.action=c,this.dueTime=d,this.comparer=e||lb,this.disposable=new cc};ec.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},ec.prototype.compareTo=function(a){return this.comparer(this.dueTime,a.dueTime)},ec.prototype.isCancelled=function(){return this.disposable.isDisposed},ec.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var fc=fb.Scheduler=function(){function a(a,b,c,d){this.now=a,this._schedule=b,this._scheduleRelative=c,this._scheduleAbsolute=d}function b(a,b){return b(),bc}var c=a.prototype;return c.schedule=function(a){return this._schedule(a,b)},c.scheduleWithState=function(a,b){return this._schedule(a,b)},c.scheduleWithRelative=function(a,c){return this._scheduleRelative(c,a,b)},c.scheduleWithRelativeAndState=function(a,b,c){return this._scheduleRelative(a,b,c)},c.scheduleWithAbsolute=function(a,c){return this._scheduleAbsolute(c,a,b)},c.scheduleWithAbsoluteAndState=function(a,b,c){return this._scheduleAbsolute(a,b,c)},a.now=jb,a.normalize=function(a){return 0>a&&(a=0),a},a}(),gc=fc.normalize;!function(a){function b(a,b){var c=b.first,d=b.second,e=new Zb,f=function(b){d(b,function(b){var c=!1,d=!1,g=a.scheduleWithState(b,function(a,b){return c?e.remove(g):d=!0,f(b),bc});d||(e.add(g),c=!0)})};return f(c),e}function c(a,b,c){var d=b.first,e=b.second,f=new Zb,g=function(b){e(b,function(b,d){var e=!1,h=!1,i=a[c].call(a,b,d,function(a,b){return e?f.remove(i):h=!0,g(b),bc});h||(f.add(i),e=!0)})};return g(d),f}function d(a,b){a(function(c){b(a,c)})}a.scheduleRecursive=function(a){return this.scheduleRecursiveWithState(a,function(a,b){a(function(){b(a)})})},a.scheduleRecursiveWithState=function(a,c){return this.scheduleWithState({first:a,second:c},b)},a.scheduleRecursiveWithRelative=function(a,b){return this.scheduleRecursiveWithRelativeAndState(b,a,d)},a.scheduleRecursiveWithRelativeAndState=function(a,b,d){return this._scheduleRelative({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithRelativeAndState")})},a.scheduleRecursiveWithAbsolute=function(a,b){return this.scheduleRecursiveWithAbsoluteAndState(b,a,d)},a.scheduleRecursiveWithAbsoluteAndState=function(a,b,d){return this._scheduleAbsolute({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithAbsoluteAndState")})}}(fc.prototype),function(){fc.prototype.schedulePeriodic=function(a,b){return this.schedulePeriodicWithState(null,a,b)},fc.prototype.schedulePeriodicWithState=function(a,b,c){var d=a,e=setInterval(function(){d=c(d)},b);return ac(function(){clearInterval(e)})}}(fc.prototype),function(a){a.catchError=a["catch"]=function(a){return new nc(this,a)}}(fc.prototype);var hc,ic=fb.internals.SchedulePeriodicRecursive=function(){function a(a,b){b(0,this._period);try{this._state=this._action(this._state)}catch(c){throw this._cancel.dispose(),c}}function b(a,b,c,d){this._scheduler=a,this._state=b,this._period=c,this._action=d}return b.prototype.start=function(){var b=new cc;return this._cancel=b,b.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,a.bind(this))),b},b}(),jc=fc.immediate=function(){function a(a,b){return b(this,a)}function b(a,b,c){for(var d=gc(d);d-this.now()>0;);return c(this,a)}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new fc(jb,a,b,c)}(),kc=fc.currentThread=function(){function a(a){for(var b;a.length>0;)if(b=a.dequeue(),!b.isCancelled()){for(;b.dueTime-fc.now()>0;);b.isCancelled()||b.invoke()}}function b(a,b){return this.scheduleWithRelativeAndState(a,0,b)}function c(b,c,d){var f=this.now()+fc.normalize(c),g=new ec(this,b,d,f);if(e)e.enqueue(g);else{e=new Xb(4),e.enqueue(g);try{a(e)}catch(h){throw h}finally{e=null}}return g.disposable}function d(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}var e,f=new fc(jb,b,c,d);return f.scheduleRequired=function(){return!e},f.ensureTrampoline=function(a){e?a():this.schedule(a)},f}(),lc=gb;!function(){function a(){if(!ab.postMessage||ab.importScripts)return!1;var a=!1,b=ab.onmessage;return ab.onmessage=function(){a=!0},ab.postMessage("","*"),ab.onmessage=b,a}function b(a){if("string"==typeof a.data&&a.data.substring(0,f.length)===f){var b=a.data.substring(f.length),c=g[b];c(),delete g[b]}}var c=RegExp("^"+String(Fb).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),d="function"==typeof(d=eb&&db&&eb.setImmediate)&&!c.test(d)&&d,e="function"==typeof(e=eb&&db&&eb.clearImmediate)&&!c.test(e)&&e;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))hc=process.nextTick;else if("function"==typeof d)hc=d,lc=e;else if(a()){var f="ms.rx.schedule"+Math.random(),g={},h=0;ab.addEventListener?ab.addEventListener("message",b,!1):ab.attachEvent("onmessage",b,!1),hc=function(a){var b=h++;g[b]=a,ab.postMessage(f+b,"*")}}else if(ab.MessageChannel){var i=new ab.MessageChannel,j={},k=0;i.port1.onmessage=function(a){var b=a.data,c=j[b];c(),delete j[b]},hc=function(a){var b=k++;j[b]=a,i.port2.postMessage(b)}}else"document"in ab&&"onreadystatechange"in ab.document.createElement("script")?hc=function(a){var b=ab.document.createElement("script");b.onreadystatechange=function(){a(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},ab.document.documentElement.appendChild(b)}:(hc=function(a){return setTimeout(a,0)},lc=clearTimeout)}();var mc=fc.timeout=function(){function a(a,b){var c=this,d=new cc,e=hc(function(){d.isDisposed||d.setDisposable(b(c,a))});return new Zb(d,ac(function(){lc(e)}))}function b(a,b,c){var d=this,e=fc.normalize(b);if(0===e)return d.scheduleWithState(a,c);var f=new cc,g=setTimeout(function(){f.isDisposed||f.setDisposable(c(d,a))},e);return new Zb(f,ac(function(){clearTimeout(g)}))}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new fc(jb,a,b,c)}(),nc=function(a){function b(){return this._scheduler.now()}function c(a,b){return this._scheduler.scheduleWithState(a,this._wrap(b))}function d(a,b,c){return this._scheduler.scheduleWithRelativeAndState(a,b,this._wrap(c))}function e(a,b,c){return this._scheduler.scheduleWithAbsoluteAndState(a,b,this._wrap(c))}function f(f,g){this._scheduler=f,this._handler=g,this._recursiveOriginal=null,this._recursiveWrapper=null,a.call(this,b,c,d,e)}return Rb(f,a),f.prototype._clone=function(a){return new f(a,this._handler)},f.prototype._wrap=function(a){var b=this;return function(c,d){try{return a(b._getRecursiveWrapper(c),d)}catch(e){if(!b._handler(e))throw e;return bc}}},f.prototype._getRecursiveWrapper=function(a){if(this._recursiveOriginal!==a){this._recursiveOriginal=a;var b=this._clone(a);b._recursiveOriginal=a,b._recursiveWrapper=b,this._recursiveWrapper=b}return this._recursiveWrapper},f.prototype.schedulePeriodicWithState=function(a,b,c){var d=this,e=!1,f=new cc;return f.setDisposable(this._scheduler.schedulePeriodicWithState(a,b,function(a){if(e)return null;try{return c(a)}catch(b){if(e=!0,!d._handler(b))throw b;return f.dispose(),null}})),f},f}(fc),oc=fb.Notification=function(){function a(a,b){this.hasValue=null==b?!1:b,this.kind=a}return a.prototype.accept=function(a,b,c){return a&&"object"==typeof a?this._acceptObservable(a):this._accept(a,b,c)},a.prototype.toObservable=function(a){var b=this;return hb(a)||(a=jc),new kd(function(c){return a.schedule(function(){b._acceptObservable(c),"N"===b.kind&&c.onCompleted()})})},a}(),pc=oc.createOnNext=function(){function a(a){return a(this.value)}function b(a){return a.onNext(this.value)}function c(){return"OnNext("+this.value+")"}return function(d){var e=new oc("N",!0);return e.value=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),qc=oc.createOnError=function(){function a(a,b){return b(this.exception)}function b(a){return a.onError(this.exception)}function c(){return"OnError("+this.exception+")"}return function(d){var e=new oc("E");return e.exception=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),rc=oc.createOnCompleted=function(){function a(a,b,c){return c()}function b(a){return a.onCompleted()}function c(){return"OnCompleted()"}return function(){var d=new oc("C");return d._accept=a,d._acceptObservable=b,d.toString=c,d}}(),sc=fb.internals.Enumerator=function(a){this._next=a};sc.prototype.next=function(){return this._next()},sc.prototype[sb]=function(){return this};var tc=fb.internals.Enumerable=function(a){this._iterator=a};tc.prototype[sb]=function(){return this._iterator()},tc.prototype.concat=function(){var a=this;return new kd(function(b){var c;try{c=a[sb]()}catch(d){return void b.onError()}var e,f=new SerialDisposable,g=jc.scheduleRecursive(function(a){var d;if(!e){try{d=c.next()}catch(g){return void b.onError(g)}if(d.done)return void b.onCompleted();var h=d.value;nb(h)&&(h=Fc(h));var i=new cc;f.setDisposable(i),i.setDisposable(h.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){a()}))}});return new Zb(f,g,ac(function(){e=!0}))})},tc.prototype.catchException=function(){var a=this;return new kd(function(b){var c;try{c=a[sb]()}catch(d){return void b.onError()}var e,f,g=new SerialDisposable,h=jc.scheduleRecursive(function(a){if(!e){var d;try{d=c.next()}catch(h){return void b.onError(h)}if(d.done)return void(f?b.onError(f):b.onCompleted());var i=d.value;nb(i)&&(i=Fc(i));var j=new cc;g.setDisposable(j),j.setDisposable(i.subscribe(b.onNext.bind(b),function(b){f=b,a()},b.onCompleted.bind(b)))}});return new Zb(g,h,ac(function(){e=!0}))})};var uc=tc.repeat=function(a,b){return null==b&&(b=-1),new tc(function(){var c=b;return new sc(function(){return 0===c?ub:(c>0&&c--,{done:!1,value:a})})})},vc=tc.forEach=function(a,b,c){return b||(b=ib),new tc(function(){var d=-1;return new sc(function(){return++d0&&(a=!this.isAcquired,this.isAcquired=!0),a&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(a){var c;if(!(b.queue.length>0))return void(b.isAcquired=!1);c=b.queue.shift();try{c()}catch(d){throw b.queue=[],b.hasFaulted=!0,d}a()}))},b.prototype.dispose=function(){a.prototype.dispose.call(this),this.disposable.dispose()},b}(zc),Dc=function(a){function b(){a.apply(this,arguments)}return Rb(b,a),b.prototype.next=function(b){a.prototype.next.call(this,b),this.ensureActive()},b.prototype.error=function(b){a.prototype.error.call(this,b),this.ensureActive()},b.prototype.completed=function(){a.prototype.completed.call(this),this.ensureActive()},b}(Cc),Ec=fb.Observable=function(){function a(a){this._subscribe=a}return yc=a.prototype,yc.subscribe=yc.forEach=function(a,b,c){var d="object"==typeof a?a:xc(a,b,c);return this._subscribe(d)},a}();yc.observeOn=function(a){var b=this;return new kd(function(c){return b.subscribe(new Dc(a,c)) +})},yc.subscribeOn=function(a){var b=this;return new kd(function(c){var d=new cc,e=new SerialDisposable;return e.setDisposable(d),d.setDisposable(a.schedule(function(){e.setDisposable(new m(a,b.subscribe(c)))})),e})};var Fc=Ec.fromPromise=function(a){return Gc(function(){var b=new fb.AsyncSubject;return a.then(function(a){b.isDisposed||(b.onNext(a),b.onCompleted())},b.onError.bind(b)),b})};yc.toPromise=function(a){if(a||(a=fb.config.Promise),!a)throw new Error("Promise type not provided nor in Rx.config.Promise");var b=this;return new a(function(a,c){var d,e=!1;b.subscribe(function(a){d=a,e=!0},function(a){c(a)},function(){e&&a(d)})})},yc.toArray=function(){var a=this;return new kd(function(b){var c=[];return a.subscribe(c.push.bind(c),b.onError.bind(b),function(){b.onNext(c),b.onCompleted()})})},Ec.create=Ec.createWithDisposable=function(a){return new kd(a)};var Gc=Ec.defer=function(a){return new kd(function(b){var c;try{c=a()}catch(d){return Mc(d).subscribe(b)}return nb(c)&&(c=Fc(c)),c.subscribe(b)})},Hc=Ec.empty=function(a){return hb(a)||(a=jc),new kd(function(b){return a.schedule(function(){b.onCompleted()})})},Ic=Math.pow(2,53)-1;Ec.from=function(a,b,c,d){if(null==a)throw new Error("iterable cannot be null.");if(b&&!r(b))throw new Error("mapFn when provided must be a function");return hb(d)||(d=kc),new kd(function(e){var f=Object(a),g=o(f),h=g?0:q(f),i=g?f[sb]():null,j=0;return d.scheduleRecursive(function(a){if(h>j||g){var d;if(g){var k=i.next();if(k.done)return void e.onCompleted();d=k.value}else d=f[j];if(b&&r(b))try{d=c?b.call(c,d,j):b(d,j)}catch(l){return void e.onError(l)}e.onNext(d),j++,a()}else e.onCompleted()})})};var Jc=Ec.fromArray=function(a,b){return hb(b)||(b=kc),new kd(function(c){var d=0,e=a.length;return b.scheduleRecursive(function(b){e>d?(c.onNext(a[d++]),b()):c.onCompleted()})})};Ec.generate=function(a,b,c,d,e){return hb(e)||(e=kc),new kd(function(f){var g=!0,h=a;return e.scheduleRecursive(function(a){var e,i;try{g?g=!1:h=c(h),e=b(h),e&&(i=d(h))}catch(j){return void f.onError(j)}e?(f.onNext(i),a()):f.onCompleted()})})},Ec.of=function(){for(var a=arguments.length,b=new Array(a),c=0;a>c;c++)b[c]=arguments[c];return Jc(b)};var Kc=(Ec.ofWithScheduler=function(a){for(var b=arguments.length-1,c=new Array(b),d=0;b>d;d++)c[d]=arguments[d+1];return Jc(c,a)},Ec.never=function(){return new kd(function(){return bc})});Ec.range=function(a,b,c){return hb(c)||(c=kc),new kd(function(d){return c.scheduleRecursiveWithState(0,function(c,e){b>c?(d.onNext(a+c),e(c+1)):d.onCompleted()})})},Ec.repeat=function(a,b,c){return hb(c)||(c=kc),Lc(a,c).repeat(null==b?-1:b)};var Lc=Ec["return"]=Ec.returnValue=Ec.just=function(a,b){return hb(b)||(b=jc),new kd(function(c){return b.schedule(function(){c.onNext(a),c.onCompleted()})})},Mc=Ec["throw"]=Ec.throwException=function(a,b){return hb(b)||(b=jc),new kd(function(c){return b.schedule(function(){c.onError(a)})})};Ec.using=function(a,b){return new kd(function(c){var d,e,f=bc;try{d=a(),d&&(f=d),e=b(d)}catch(g){return new Zb(Mc(g).subscribe(c),f)}return new Zb(e.subscribe(c),f)})},yc.amb=function(a){var b=this;return new kd(function(c){function d(){f||(f=g,j.dispose())}function e(){f||(f=h,i.dispose())}var f,g="L",h="R",i=new cc,j=new cc;return nb(a)&&(a=Fc(a)),i.setDisposable(b.subscribe(function(a){d(),f===g&&c.onNext(a)},function(a){d(),f===g&&c.onError(a)},function(){d(),f===g&&c.onCompleted()})),j.setDisposable(a.subscribe(function(a){e(),f===h&&c.onNext(a)},function(a){e(),f===h&&c.onError(a)},function(){e(),f===h&&c.onCompleted()})),new Zb(i,j)})},Ec.amb=function(){function a(a,b){return a.amb(b)}for(var b=Kc(),c=k(arguments,0),d=0,e=c.length;e>d;d++)b=a(b,c[d]);return b},yc["catch"]=yc.catchException=function(a){return"function"==typeof a?s(this,a):Nc([this,a])};var Nc=Ec.catchException=Ec["catch"]=function(){var a=k(arguments,0);return vc(a).catchException()};yc.combineLatest=function(){var a=Qb.call(arguments);return Array.isArray(a[0])?a[0].unshift(this):a.unshift(this),Oc.apply(this,a)};var Oc=Ec.combineLatest=function(){var a=Qb.call(arguments),b=a.pop();return Array.isArray(a[0])&&(a=a[0]),new kd(function(c){function d(a){var d;if(h[a]=!0,i||(i=h.every(ib))){try{d=b.apply(null,k)}catch(e){return void c.onError(e)}c.onNext(d)}else j.filter(function(b,c){return c!==a}).every(ib)&&c.onCompleted()}function e(a){j[a]=!0,j.every(ib)&&c.onCompleted()}for(var f=function(){return!1},g=a.length,h=l(g,f),i=!1,j=l(g,f),k=new Array(g),m=new Array(g),n=0;g>n;n++)!function(b){var f=a[b],g=new cc;nb(f)&&(f=Fc(f)),g.setDisposable(f.subscribe(function(a){k[b]=a,d(b)},c.onError.bind(c),function(){e(b)})),m[b]=g}(n);return new Zb(m)})};yc.concat=function(){var a=Qb.call(arguments,0);return a.unshift(this),Pc.apply(this,a)};var Pc=Ec.concat=function(){var a=k(arguments,0);return vc(a).concat()};yc.concatObservable=yc.concatAll=function(){return this.merge(1)},yc.merge=function(a){if("number"!=typeof a)return Qc(this,a);var b=this;return new kd(function(c){function d(a){var b=new cc;f.add(b),nb(a)&&(a=Fc(a)),b.setDisposable(a.subscribe(c.onNext.bind(c),c.onError.bind(c),function(){f.remove(b),h.length>0?d(h.shift()):(e--,g&&0===e&&c.onCompleted())}))}var e=0,f=new Zb,g=!1,h=[];return f.add(b.subscribe(function(b){a>e?(e++,d(b)):h.push(b)},c.onError.bind(c),function(){g=!0,0===e&&c.onCompleted()})),f})};var Qc=Ec.merge=function(){var a,b;return arguments[0]?arguments[0].now?(a=arguments[0],b=Qb.call(arguments,1)):(a=jc,b=Qb.call(arguments,0)):(a=jc,b=Qb.call(arguments,1)),Array.isArray(b[0])&&(b=b[0]),Jc(b,a).mergeObservable()};yc.mergeObservable=yc.mergeAll=function(){var a=this;return new kd(function(b){var c=new Zb,d=!1,e=new cc;return c.add(e),e.setDisposable(a.subscribe(function(a){var e=new cc;c.add(e),nb(a)&&(a=Fc(a)),e.setDisposable(a.subscribe(function(a){b.onNext(a)},b.onError.bind(b),function(){c.remove(e),d&&1===c.length&&b.onCompleted()}))},b.onError.bind(b),function(){d=!0,1===c.length&&b.onCompleted()})),c})},yc.onErrorResumeNext=function(a){if(!a)throw new Error("Second observable is required");return Rc([this,a])};var Rc=Ec.onErrorResumeNext=function(){var a=k(arguments,0);return new kd(function(b){var c=0,d=new SerialDisposable,e=jc.scheduleRecursive(function(e){var f,g;c0})){try{f=h.map(function(a){return a.shift()}),e=c.apply(a,f)}catch(g){return void d.onError(g)}d.onNext(e)}else i.filter(function(a,c){return c!==b}).every(ib)&&d.onCompleted()}function f(a){i[a]=!0,i.every(function(a){return a})&&d.onCompleted()}for(var g=b.length,h=l(g,function(){return[]}),i=l(g,function(){return!1}),j=new Array(g),k=0;g>k;k++)!function(a){var c=b[a],g=new cc;nb(c)&&(c=Fc(c)),g.setDisposable(c.subscribe(function(b){h[a].push(b),e(a)},d.onError.bind(d),function(){f(a)})),j[a]=g}(k);return new Zb(j)})},Ec.zip=function(){var a=Qb.call(arguments,0),b=a.shift();return b.zip.apply(b,a)},Ec.zipArray=function(){var a=k(arguments,0);return new kd(function(b){function c(a){if(f.every(function(a){return a.length>0})){var c=f.map(function(a){return a.shift()});b.onNext(c)}else if(g.filter(function(b,c){return c!==a}).every(ib))return void b.onCompleted()}function d(a){return g[a]=!0,g.every(ib)?void b.onCompleted():void 0}for(var e=a.length,f=l(e,function(){return[]}),g=l(e,function(){return!1}),h=new Array(e),i=0;e>i;i++)!function(e){h[e]=new cc,h[e].setDisposable(a[e].subscribe(function(a){f[e].push(a),c(e)},b.onError.bind(b),function(){d(e)}))}(i);var j=new Zb(h);return j.add(ac(function(){for(var a=0,b=f.length;b>a;a++)f[a]=[]})),j})},yc.asObservable=function(){var a=this;return new kd(function(b){return a.subscribe(b)})},yc.bufferWithCount=function(a,b){return"number"!=typeof b&&(b=a),this.windowWithCount(a,b).selectMany(function(a){return a.toArray()}).where(function(a){return a.length>0})},yc.dematerialize=function(){var a=this;return new kd(function(b){return a.subscribe(function(a){return a.accept(b)},b.onError.bind(b),b.onCompleted.bind(b))})},yc.distinctUntilChanged=function(a,b){var c=this;return a||(a=ib),b||(b=kb),new kd(function(d){var e,f=!1;return c.subscribe(function(c){var g,h=!1;try{g=a(c)}catch(i){return void d.onError(i)}if(f)try{h=b(e,g)}catch(i){return void d.onError(i)}f&&h||(f=!0,e=g,d.onNext(c))},d.onError.bind(d),d.onCompleted.bind(d))})},yc["do"]=yc.doAction=yc.tap=function(a,b,c){var d,e=this;return"function"==typeof a?d=a:(d=a.onNext.bind(a),b=a.onError.bind(a),c=a.onCompleted.bind(a)),new kd(function(a){return e.subscribe(function(b){try{d(b)}catch(c){a.onError(c)}a.onNext(b)},function(c){if(b){try{b(c)}catch(d){a.onError(d)}a.onError(c)}else a.onError(c)},function(){if(c){try{c()}catch(b){a.onError(b)}a.onCompleted()}else a.onCompleted()})})},yc["finally"]=yc.finallyAction=function(a){var b=this;return new kd(function(c){var d;try{d=b.subscribe(c)}catch(e){throw a(),e}return ac(function(){try{d.dispose()}catch(b){throw b}finally{a()}})})},yc.ignoreElements=function(){var a=this;return new kd(function(b){return a.subscribe(gb,b.onError.bind(b),b.onCompleted.bind(b))})},yc.materialize=function(){var a=this;return new kd(function(b){return a.subscribe(function(a){b.onNext(pc(a))},function(a){b.onNext(qc(a)),b.onCompleted()},function(){b.onNext(rc()),b.onCompleted()})})},yc.repeat=function(a){return uc(this,a).concat()},yc.retry=function(a){return uc(this,a).catchException()},yc.scan=function(){var a,b,c=!1,d=this;return 2===arguments.length?(c=!0,a=arguments[0],b=arguments[1]):b=arguments[0],new kd(function(e){var f,g,h;return d.subscribe(function(d){try{h||(h=!0),f?g=b(g,d):(g=c?b(a,d):d,f=!0)}catch(i){return void e.onError(i)}e.onNext(g)},e.onError.bind(e),function(){!h&&c&&e.onNext(a),e.onCompleted()})})},yc.skipLast=function(a){var b=this;return new kd(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&c.onNext(d.shift())},c.onError.bind(c),c.onCompleted.bind(c))})},yc.startWith=function(){var a,b,c=0;return arguments.length&&"now"in Object(arguments[0])?(b=arguments[0],c=1):b=jc,a=Qb.call(arguments,c),vc([Jc(a,b),this]).concat()},yc.takeLast=function(a){var b=this;return new kd(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&d.shift()},c.onError.bind(c),function(){for(;d.length>0;)c.onNext(d.shift());c.onCompleted()})})},yc.takeLastBuffer=function(a){var b=this;return new kd(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&d.shift()},c.onError.bind(c),function(){c.onNext(d),c.onCompleted()})})},yc.windowWithCount=function(a,b){var c=this;if(0>=a)throw new Error(qb);if(1===arguments.length&&(b=a),0>=b)throw new Error(qb);return new kd(function(d){var e=new cc,f=new dc(e),g=0,h=[],i=function(){var a=new nd;h.push(a),d.onNext(Tb(a,f))};return i(),e.setDisposable(c.subscribe(function(c){for(var d,e=0,f=h.length;f>e;e++)h[e].onNext(c);var j=g-a+1;j>=0&&j%b===0&&(d=h.shift(),d.onCompleted()),g++,g%b===0&&i()},function(a){for(;h.length>0;)h.shift().onError(a);d.onError(a)},function(){for(;h.length>0;)h.shift().onCompleted();d.onCompleted()})),f})},yc.selectConcat=yc.concatMap=function(a,b,c){return b?this.concatMap(function(c,d){var e=a(c,d),f=nb(e)?Fc(e):e;return f.map(function(a){return b(c,a,d)})}):"function"==typeof a?u(this,a,c):u(this,function(){return a})},yc.concatMapObserver=yc.selectConcatObserver=function(a,b,c,d){var e=this;return new kd(function(f){var g=0;return e.subscribe(function(b){var c;try{c=a.call(d,b,g++)}catch(e){return void f.onError(e)}nb(c)&&(c=Fc(c)),f.onNext(c)},function(a){var c;try{c=b.call(d,a)}catch(e){return void f.onError(e)}nb(c)&&(c=Fc(c)),f.onNext(c),f.onCompleted()},function(){var a;try{a=c.call(d)}catch(b){return void f.onError(b)}nb(a)&&(a=Fc(a)),f.onNext(a),f.onCompleted()})}).concatAll()},yc.defaultIfEmpty=function(b){var c=this;return b===a&&(b=null),new kd(function(a){var d=!1;return c.subscribe(function(b){d=!0,a.onNext(b)},a.onError.bind(a),function(){d||a.onNext(b),a.onCompleted()})})},w.prototype.push=function(a){var b=-1===v(this.set,a,this.comparer);return b&&this.set.push(a),b},yc.distinct=function(a,b){var c=this;return b||(b=kb),new kd(function(d){var e=new w(b);return c.subscribe(function(b){var c=b;if(a)try{c=a(b)}catch(f){return void d.onError(f)}e.push(c)&&d.onNext(b)},d.onError.bind(d),d.onCompleted.bind(d))})},yc.groupBy=function(a,b,c){return this.groupByUntil(a,b,Kc,c)},yc.groupByUntil=function(a,b,c,d){var e=this;return b||(b=ib),d||(d=kb),new kd(function(f){function g(a){return function(b){b.onError(a)}}var h=new dd(0,d),i=new Zb,j=new dc(i);return i.add(e.subscribe(function(d){var e;try{e=a(d)}catch(k){return h.getValues().forEach(g(k)),void f.onError(k)}var l=!1,m=h.tryGetValue(e);if(m||(m=new nd,h.set(e,m),l=!0),l){var n=new md(e,m,j),o=new md(e,m);try{duration=c(o)}catch(k){return h.getValues().forEach(g(k)),void f.onError(k)}f.onNext(n);var p=new cc;i.add(p);var q=function(){h.remove(e)&&m.onCompleted(),i.remove(p)};p.setDisposable(duration.take(1).subscribe(gb,function(a){h.getValues().forEach(g(a)),f.onError(a)},q))}var r;try{r=b(d)}catch(k){return h.getValues().forEach(g(k)),void f.onError(k)}m.onNext(r)},function(a){h.getValues().forEach(g(a)),f.onError(a)},function(){h.getValues().forEach(function(a){a.onCompleted()}),f.onCompleted()})),j})},yc.select=yc.map=function(a,b){var c=this;return new kd(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},yc.pluck=function(a){return this.select(function(b){return b[a]})},yc.selectMany=yc.flatMap=function(a,b,c){return b?this.flatMap(function(c,d){var e=a(c,d),f=nb(e)?Fc(e):e;return f.map(function(a){return b(c,a,d)})},c):"function"==typeof a?x(this,a,c):x(this,function(){return a})},yc.flatMapObserver=yc.selectManyObserver=function(a,b,c,d){var e=this;return new kd(function(f){var g=0;return e.subscribe(function(b){var c;try{c=a.call(d,b,g++)}catch(e){return void f.onError(e)}nb(c)&&(c=Fc(c)),f.onNext(c)},function(a){var c;try{c=b.call(d,a)}catch(e){return void f.onError(e)}nb(c)&&(c=Fc(c)),f.onNext(c),f.onCompleted()},function(){var a;try{a=c.call(d)}catch(b){return void f.onError(b)}nb(a)&&(a=Fc(a)),f.onNext(a),f.onCompleted()})}).mergeAll()},yc.selectSwitch=yc.flatMapLatest=yc.switchMap=function(a,b){return this.select(a,b).switchLatest()},yc.skip=function(a){if(0>a)throw new Error(qb);var b=this;return new kd(function(c){var d=a;return b.subscribe(function(a){0>=d?c.onNext(a):d--},c.onError.bind(c),c.onCompleted.bind(c))})},yc.skipWhile=function(a,b){var c=this;return new kd(function(d){var e=0,f=!1;return c.subscribe(function(g){if(!f)try{f=!a.call(b,g,e++,c)}catch(h){return void d.onError(h)}f&&d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},yc.take=function(a,b){if(0>a)throw new Error(qb);if(0===a)return Hc(b);var c=this;return new kd(function(b){var d=a;return c.subscribe(function(a){d>0&&(d--,b.onNext(a),0===d&&b.onCompleted())},b.onError.bind(b),b.onCompleted.bind(b))})},yc.takeWhile=function(a,b){var c=this;return new kd(function(d){var e=0,f=!0;return c.subscribe(function(g){if(f){try{f=a.call(b,g,e++,c)}catch(h){return void d.onError(h)}f?d.onNext(g):d.onCompleted()}},d.onError.bind(d),d.onCompleted.bind(d))})},yc.where=yc.filter=function(a,b){var c=this;return new kd(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}g&&d.onNext(f)},d.onError.bind(d),d.onCompleted.bind(d))})},yc.finalValue=function(){var a=this;return new kd(function(b){var c,d=!1;return a.subscribe(function(a){d=!0,c=a},b.onError.bind(b),function(){d?(b.onNext(c),b.onCompleted()):b.onError(new Error(pb))})})},yc.aggregate=function(){var a,b,c;return 2===arguments.length?(a=arguments[0],b=!0,c=arguments[1]):c=arguments[0],b?this.scan(a,c).startWith(a).finalValue():this.scan(c).finalValue()},yc.reduce=function(a){var b,c;return 2===arguments.length&&(c=!0,b=arguments[1]),c?this.scan(b,a).startWith(b).finalValue():this.scan(a).finalValue()},yc.some=yc.any=function(a,b){var c=this;return a?c.where(a,b).any():new kd(function(a){return c.subscribe(function(){a.onNext(!0),a.onCompleted()},a.onError.bind(a),function(){a.onNext(!1),a.onCompleted()})})},yc.isEmpty=function(){return this.any().map(ob)},yc.every=yc.all=function(a,b){return this.where(function(b){return!a(b)},b).any().select(function(a){return!a})},yc.contains=function(a,b){return b||(b=kb),this.where(function(c){return b(c,a)}).any()},yc.count=function(a,b){return a?this.where(a,b).count():this.aggregate(0,function(a){return a+1})},yc.sum=function(a,b){return a?this.select(a,b).sum():this.aggregate(0,function(a,b){return a+b})},yc.minBy=function(a,b){return b||(b=lb),y(this,a,function(a,c){return-1*b(a,c)})},yc.min=function(a){return this.minBy(ib,a).select(function(a){return z(a)})},yc.maxBy=function(a,b){return b||(b=lb),y(this,a,b)},yc.max=function(a){return this.maxBy(ib,a).select(function(a){return z(a)})},yc.average=function(a,b){return a?this.select(a,b).average():this.scan({sum:0,count:0},function(a,b){return{sum:a.sum+b,count:a.count+1}}).finalValue().select(function(a){if(0===a.count)throw new Error("The input sequence was empty");return a.sum/a.count})},yc.sequenceEqual=function(a,b){var c=this;return b||(b=kb),Array.isArray(a)?A(c,a,b):new kd(function(d){var e=!1,f=!1,g=[],h=[],i=c.subscribe(function(a){var c,e;if(h.length>0){e=h.shift();try{c=b(e,a)}catch(i){return void d.onError(i)}c||(d.onNext(!1),d.onCompleted())}else f?(d.onNext(!1),d.onCompleted()):g.push(a)},d.onError.bind(d),function(){e=!0,0===g.length&&(h.length>0?(d.onNext(!1),d.onCompleted()):f&&(d.onNext(!0),d.onCompleted()))});nb(a)&&(a=Fc(a));var j=a.subscribe(function(a){var c,f;if(g.length>0){f=g.shift();try{c=b(f,a)}catch(i){return void d.onError(i)}c||(d.onNext(!1),d.onCompleted())}else e?(d.onNext(!1),d.onCompleted()):h.push(a)},d.onError.bind(d),function(){f=!0,0===h.length&&(g.length>0?(d.onNext(!1),d.onCompleted()):e&&(d.onNext(!0),d.onCompleted()))});return new Zb(i,j)})},yc.elementAt=function(a){return B(this,a,!1)},yc.elementAtOrDefault=function(a,b){return B(this,a,!0,b)},yc.single=function(a,b){return a?this.where(a,b).single():C(this,!1)},yc.singleOrDefault=function(a,b,c){return a?this.where(a,c).singleOrDefault(null,b):C(this,!0,b)},yc.first=function(a,b){return a?this.where(a,b).first():D(this,!1)},yc.firstOrDefault=function(a,b){return a?this.where(a).firstOrDefault(null,b):D(this,!0,b)},yc.last=function(a,b){return a?this.where(a,b).last():E(this,!1)},yc.lastOrDefault=function(a,b,c){return a?this.where(a,c).lastOrDefault(null,b):E(this,!0,b)},yc.find=function(a,b){return F(this,a,b,!1)},yc.findIndex=function(a,b){return F(this,a,b,!0)},ab.Set&&(yc.toSet=function(){return G(this,ab.Set)}),ab.WeakSet&&(yc.toWeakSet=function(){return G(this,ab.WeakSet)}),ab.Map&&(yc.toMap=function(a,b){return H(this,ab.Map,a,b)}),ab.WeakMap&&(yc.toWeakMap=function(a,b){return H(this,ab.WeakMap,a,b)}),Ec.start=function(a,b,c){return Sc(a,b,c)()};var Sc=Ec.toAsync=function(a,b,c){return hb(c)||(c=mc),function(){var d=arguments,e=new od;return c.schedule(function(){var c;try{c=a.apply(b,d)}catch(f){return void e.onError(f)}e.onNext(c),e.onCompleted()}),e.asObservable()}};Ec.fromCallback=function(a,b,c){return function(){var d=Qb.call(arguments,0);return new kd(function(e){function f(a){var b=a;if(c){try{b=c(arguments)}catch(d){return void e.onError(d)}e.onNext(b)}else b.length<=1?e.onNext.apply(e,b):e.onNext(b);e.onCompleted()}d.push(f),a.apply(b,d)}).publishLast().refCount()}},Ec.fromNodeCallback=function(a,b,c){return function(){var d=Qb.call(arguments,0);return new kd(function(e){function f(a){if(a)return void e.onError(a);var b=Qb.call(arguments,1);if(c){try{b=c(b)}catch(d){return void e.onError(d)}e.onNext(b)}else b.length<=1?e.onNext.apply(e,b):e.onNext(b);e.onCompleted()}d.push(f),a.apply(b,d)}).publishLast().refCount()}},fb.config.useNativeEvents=!1;var Tc=ab.angular&&angular.element?angular.element:ab.jQuery?ab.jQuery:ab.Zepto?ab.Zepto:null,Uc=!!ab.Ember&&"function"==typeof ab.Ember.addListener,Vc=!!ab.Backbone&&!!ab.Backbone.Marionette;Ec.fromEvent=function(a,b,c){if(a.addListener)return Wc(function(c){a.addListener(b,c)},function(c){a.removeListener(b,c)},c);if(!fb.config.useNativeEvents){if(Vc)return Wc(function(c){a.on(b,c)},function(c){a.off(b,c)},c);if(Uc)return Wc(function(c){Ember.addListener(a,b,c)},function(c){Ember.removeListener(a,b,c)},c);if(Tc){var d=Tc(a);return Wc(function(a){d.on(b,a)},function(a){d.off(b,a)},c)}}return new kd(function(d){return K(a,b,function(a){var b=a;if(c)try{b=c(arguments)}catch(e){return void d.onError(e)}d.onNext(b)})}).publish().refCount()};var Wc=Ec.fromEventPattern=function(a,b,c){return new kd(function(d){function e(a){var b=a;if(c)try{b=c(arguments)}catch(e){return void d.onError(e)}d.onNext(b)}var f=a(e);return ac(function(){b&&b(e,f)})}).publish().refCount()};Ec.startAsync=function(a){var b;try{b=a()}catch(c){return Mc(c)}return Fc(b)};var Xc=function(a){function b(a){var b=this.source.publish(),c=b.subscribe(a),d=bc,e=this.pauser.distinctUntilChanged().subscribe(function(a){a?d=b.connect():(d.dispose(),d=bc)});return new Zb(c,d,e)}function c(c,d){this.source=c,this.controller=new nd,this.pauser=d&&d.subscribe?this.controller.merge(d):this.controller,a.call(this,b)}return Rb(c,a),c.prototype.pause=function(){this.controller.onNext(!1)},c.prototype.resume=function(){this.controller.onNext(!0)},c}(Ec);yc.pausable=function(a){return new Xc(this,a)};var Yc=function(b){function c(b){var c,d=[],e=L(this.source,this.pauser.distinctUntilChanged().startWith(!1),function(a,b){return{data:a,shouldFire:b}}).subscribe(function(e){if(c!==a&&e.shouldFire!=c){if(e.shouldFire)for(;d.length>0;)b.onNext(d.shift())}else e.shouldFire?b.onNext(e.data):d.push(e.data);c=e.shouldFire},function(a){for(;d.length>0;)b.onNext(d.shift());b.onError(a)},function(){for(;d.length>0;)b.onNext(d.shift());b.onCompleted()});return e}function d(a,d){this.source=a,this.controller=new nd,this.pauser=d&&d.subscribe?this.controller.merge(d):this.controller,b.call(this,c)}return Rb(d,b),d.prototype.pause=function(){this.controller.onNext(!1)},d.prototype.resume=function(){this.controller.onNext(!0)},d}(Ec);yc.pausableBuffered=function(a){return new Yc(this,a)},yc.controlled=function(a){return null==a&&(a=!0),new Zc(this,a)};var Zc=function(a){function b(a){return this.source.subscribe(a)}function c(c,d){a.call(this,b),this.subject=new $c(d),this.source=c.multicast(this.subject).refCount()}return Rb(c,a),c.prototype.request=function(a){return null==a&&(a=-1),this.subject.request(a)},c}(Ec),$c=fb.ControlledSubject=function(a){function c(a){return this.subject.subscribe(a)}function d(b){null==b&&(b=!0),a.call(this,c),this.subject=new nd,this.enableQueue=b,this.queue=b?[]:null,this.requestedCount=0,this.requestedDisposable=bc,this.error=null,this.hasFailed=!1,this.hasCompleted=!1,this.controlledDisposable=bc}return Rb(d,a),Sb(d.prototype,wc,{onCompleted:function(){b.call(this),this.hasCompleted=!0,this.enableQueue&&0!==this.queue.length||this.subject.onCompleted()},onError:function(a){b.call(this),this.hasFailed=!0,this.error=a,this.enableQueue&&0!==this.queue.length||this.subject.onError(a)},onNext:function(a){b.call(this);var c=!1;0===this.requestedCount?this.enableQueue&&this.queue.push(a):(-1!==this.requestedCount&&0===this.requestedCount--&&this.disposeCurrentRequest(),c=!0),c&&this.subject.onNext(a)},_processRequest:function(a){if(this.enableQueue){for(;this.queue.length>=a&&a>0;)this.subject.onNext(this.queue.shift()),a--;return 0!==this.queue.length?{numberOfItems:a,returnValue:!0}:{numberOfItems:a,returnValue:!1}}return this.hasFailed?(this.subject.onError(this.error),this.controlledDisposable.dispose(),this.controlledDisposable=bc):this.hasCompleted&&(this.subject.onCompleted(),this.controlledDisposable.dispose(),this.controlledDisposable=bc),{numberOfItems:a,returnValue:!1}},request:function(a){b.call(this),this.disposeCurrentRequest();var c=this,d=this._processRequest(a);return a=d.numberOfItems,d.returnValue?bc:(this.requestedCount=a,this.requestedDisposable=ac(function(){c.requestedCount=0}),this.requestedDisposable)},disposeCurrentRequest:function(){this.requestedDisposable.dispose(),this.requestedDisposable=bc},dispose:function(){this.isDisposed=!0,this.error=null,this.subject.dispose(),this.requestedDisposable.dispose()}}),d}(Ec);yc.multicast=function(a,b){var c=this;return"function"==typeof a?new kd(function(d){var e=c.multicast(a());return new Zb(b(e).subscribe(d),e.connect())}):new cd(c,a)},yc.publish=function(a){return a?this.multicast(function(){return new nd},a):this.multicast(new nd)},yc.share=function(){return this.publish(null).refCount()},yc.publishLast=function(a){return a?this.multicast(function(){return new od},a):this.multicast(new od)},yc.publishValue=function(a,b){return 2===arguments.length?this.multicast(function(){return new ad(b)},a):this.multicast(new ad(a))},yc.shareValue=function(a){return this.publishValue(a).refCount()},yc.replay=function(a,b,c,d){return a?this.multicast(function(){return new bd(b,c,d)},a):this.multicast(new bd(b,c,d))},yc.shareReplay=function(a,b,c){return this.replay(null,a,b,c).refCount()};var _c=function(a,b){this.subject=a,this.observer=b};_c.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1),this.observer=null}};var ad=fb.BehaviorSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),a.onNext(this.value),new _c(this,a);var c=this.exception;return c?a.onError(c):a.onCompleted(),bc}function d(b){a.call(this,c),this.value=b,this.observers=[],this.isDisposed=!1,this.isStopped=!1,this.exception=null}return Rb(d,a),Sb(d.prototype,wc,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped){this.value=a;for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)}},dispose:function(){this.isDisposed=!0,this.observers=null,this.value=null,this.exception=null}}),d}(Ec),bd=fb.ReplaySubject=function(a){function c(a,b){this.subject=a,this.observer=b}function d(a){var d=new Cc(this.scheduler,a),e=new c(this,d);b.call(this),this._trim(this.scheduler.now()),this.observers.push(d);for(var f=this.q.length,g=0,h=this.q.length;h>g;g++)d.onNext(this.q[g].value);return this.hasError?(f++,d.onError(this.error)):this.isStopped&&(f++,d.onCompleted()),d.ensureActive(f),e}function e(b,c,e){this.bufferSize=null==b?Number.MAX_VALUE:b,this.windowSize=null==c?Number.MAX_VALUE:c,this.scheduler=e||kc,this.q=[],this.observers=[],this.isStopped=!1,this.isDisposed=!1,this.hasError=!1,this.error=null,a.call(this,d)}return c.prototype.dispose=function(){if(this.observer.dispose(),!this.subject.isDisposed){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1)}},Rb(e,a),Sb(e.prototype,wc,{hasObservers:function(){return this.observers.length>0},_trim:function(a){for(;this.q.length>this.bufferSize;)this.q.shift();for(;this.q.length>0&&a-this.q[0].interval>this.windowSize;)this.q.shift()},onNext:function(a){var c;if(b.call(this),!this.isStopped){var d=this.scheduler.now();this.q.push({interval:d,value:a}),this._trim(d);for(var e=this.observers.slice(0),f=0,g=e.length;g>f;f++)c=e[f],c.onNext(a),c.ensureActive()}},onError:function(a){var c;if(b.call(this),!this.isStopped){this.isStopped=!0,this.error=a,this.hasError=!0;var d=this.scheduler.now();this._trim(d);for(var e=this.observers.slice(0),f=0,g=e.length;g>f;f++)c=e[f],c.onError(a),c.ensureActive();this.observers=[]}},onCompleted:function(){var a;if(b.call(this),!this.isStopped){this.isStopped=!0;var c=this.scheduler.now();this._trim(c);for(var d=this.observers.slice(0),e=0,f=d.length;f>e;e++)a=d[e],a.onCompleted(),a.ensureActive();this.observers=[]}},dispose:function(){this.isDisposed=!0,this.observers=null}}),e}(Ec),cd=fb.ConnectableObservable=function(a){function b(b,c){var d,e=!1,f=b.asObservable();this.connect=function(){return e||(e=!0,d=new Zb(f.subscribe(c),ac(function(){e=!1}))),d},a.call(this,c.subscribe.bind(c))}return Rb(b,a),b.prototype.refCount=function(){var a,b=0,c=this;return new kd(function(d){var e=1===++b,f=c.subscribe(d);return e&&(a=c.connect()),function(){f.dispose(),0===--b&&a.dispose()}})},b}(Ec),dd=function(){function b(a){if(a&!1)return 2===a;for(var b=Math.sqrt(a),c=3;b>=c;){if(a%c===0)return!1;c+=2}return!0}function c(a){var c,d,e;for(c=0;c=a)return d;for(e=1|a;ec;c++){var e=a.charCodeAt(c);b=(b<<5)-b+e,b&=b}return b}function e(a){var b=668265261;return a=61^a^a>>>16,a+=a<<3,a^=a>>>4,a*=b,a^=a>>>15}function f(){return{key:null,value:null,next:0,hashCode:0}}function g(a,b){if(0>a)throw new Error("out of range");a>0&&this._initialize(a),this.comparer=b||kb,this.freeCount=0,this.size=0,this.freeList=-1}var h=[1,3,7,13,31,61,127,251,509,1021,2039,4093,8191,16381,32749,65521,131071,262139,524287,1048573,2097143,4194301,8388593,16777213,33554393,67108859,134217689,268435399,536870909,1073741789,2147483647],i="no such key",j="duplicate key",k=function(){var a=0;return function(b){if(null==b)throw new Error(i);if("string"==typeof b)return d(b);if("number"==typeof b)return e(b);if("boolean"==typeof b)return b===!0?1:0;if(b instanceof Date)return e(b.valueOf());if(b instanceof RegExp)return d(b.toString());if("function"==typeof b.valueOf){var c=b.valueOf();if("number"==typeof c)return e(c);if("string"==typeof b)return d(c)}if(b.getHashCode)return b.getHashCode();var f=17*a++;return b.getHashCode=function(){return f},f}}(),l=g.prototype;return l._initialize=function(a){var b,d=c(a);for(this.buckets=new Array(d),this.entries=new Array(d),b=0;d>b;b++)this.buckets[b]=-1,this.entries[b]=f();this.freeList=-1},l.add=function(a,b){return this._insert(a,b,!0)},l._insert=function(a,b,c){this.buckets||this._initialize(0);for(var d,e=2147483647&k(a),f=e%this.buckets.length,g=this.buckets[f];g>=0;g=this.entries[g].next)if(this.entries[g].hashCode===e&&this.comparer(this.entries[g].key,a)){if(c)throw new Error(j);return void(this.entries[g].value=b)}this.freeCount>0?(d=this.freeList,this.freeList=this.entries[d].next,--this.freeCount):(this.size===this.entries.length&&(this._resize(),f=e%this.buckets.length),d=this.size,++this.size),this.entries[d].hashCode=e,this.entries[d].next=this.buckets[f],this.entries[d].key=a,this.entries[d].value=b,this.buckets[f]=d +},l._resize=function(){var a=c(2*this.size),b=new Array(a);for(e=0;ee;++e)d[e]=f();for(var g=0;g=0;e=this.entries[e].next){if(this.entries[e].hashCode===b&&this.comparer(this.entries[e].key,a))return 0>d?this.buckets[c]=this.entries[e].next:this.entries[d].next=this.entries[e].next,this.entries[e].hashCode=-1,this.entries[e].next=this.freeList,this.entries[e].key=null,this.entries[e].value=null,this.freeList=e,++this.freeCount,!0;d=e}return!1},l.clear=function(){var a,b;if(!(this.size<=0)){for(a=0,b=this.buckets.length;b>a;++a)this.buckets[a]=-1;for(a=0;a=0;c=this.entries[c].next)if(this.entries[c].hashCode===b&&this.comparer(this.entries[c].key,a))return c;return-1},l.count=function(){return this.size-this.freeCount},l.tryGetValue=function(b){var c=this._findEntry(b);return c>=0?this.entries[c].value:a},l.getValues=function(){var a=0,b=[];if(this.entries)for(var c=0;c=0&&(b[a++]=this.entries[c].value);return b},l.get=function(a){var b=this._findEntry(a);if(b>=0)return this.entries[b].value;throw new Error(i)},l.set=function(a,b){this._insert(a,b,!1)},l.containskey=function(a){return this._findEntry(a)>=0},g}();yc.join=function(a,b,c,d){var e=this;return new kd(function(f){var g=new Zb,h=!1,i=!1,j=0,k=0,l=new dd,m=new dd;return g.add(e.subscribe(function(a){var c=j++,e=new cc;l.add(c,a),g.add(e);var i,k=function(){l.remove(c)&&0===l.count()&&h&&f.onCompleted(),g.remove(e)};try{i=b(a)}catch(n){return void f.onError(n)}e.setDisposable(i.take(1).subscribe(gb,f.onError.bind(f),k)),m.getValues().forEach(function(b){var c;try{c=d(a,b)}catch(e){return void f.onError(e)}f.onNext(c)})},f.onError.bind(f),function(){h=!0,(i||0===l.count())&&f.onCompleted()})),g.add(a.subscribe(function(a){var b=k++,e=new cc;m.add(b,a),g.add(e);var h,j=function(){m.remove(b)&&0===m.count()&&i&&f.onCompleted(),g.remove(e)};try{h=c(a)}catch(n){return void f.onError(n)}e.setDisposable(h.take(1).subscribe(gb,f.onError.bind(f),j)),l.getValues().forEach(function(b){var c;try{c=d(b,a)}catch(e){return void f.onError(e)}f.onNext(c)})},f.onError.bind(f),function(){i=!0,(h||0===m.count())&&f.onCompleted()})),g})},yc.groupJoin=function(a,b,c,d){var e=this;return new kd(function(f){function g(a){return function(b){b.onError(a)}}var h=new Zb,i=new dc(h),j=new dd,k=new dd,l=0,m=0;return h.add(e.subscribe(function(a){var c=new nd,e=l++;j.add(e,c);var m;try{m=d(a,Tb(c,i))}catch(n){return j.getValues().forEach(g(n)),void f.onError(n)}f.onNext(m),k.getValues().forEach(function(a){c.onNext(a)});var o=new cc;h.add(o);var p,q=function(){j.remove(e)&&c.onCompleted(),h.remove(o)};try{p=b(a)}catch(n){return j.getValues().forEach(g(n)),void f.onError(n)}o.setDisposable(p.take(1).subscribe(gb,function(a){j.getValues().forEach(g(a)),f.onError(a)},q))},function(a){j.getValues().forEach(g(a)),f.onError(a)},f.onCompleted.bind(f))),h.add(a.subscribe(function(a){var b=m++;k.add(b,a);var d=new cc;h.add(d);var e,i=function(){k.remove(b),h.remove(d)};try{e=c(a)}catch(l){return j.getValues().forEach(g(l)),void f.onError(l)}d.setDisposable(e.take(1).subscribe(gb,function(a){j.getValues().forEach(g(a)),f.onError(a)},i)),j.getValues().forEach(function(b){b.onNext(a)})},function(a){j.getValues().forEach(g(a)),f.onError(a)})),i})},yc.buffer=function(){return this.window.apply(this,arguments).selectMany(function(a){return a.toArray()})},yc.window=function(a,b){return 1===arguments.length&&"function"!=typeof arguments[0]?N.call(this,a):"function"==typeof a?O.call(this,a):M.call(this,a,b)},yc.pairwise=function(){var a=this;return new kd(function(b){var c,d=!1;return a.subscribe(function(a){d?b.onNext([c,a]):d=!0,c=a},b.onError.bind(b),b.onCompleted.bind(b))})},yc.partition=function(a,b){var c=this.publish().refCount();return[c.filter(a,b),c.filter(function(c,d,e){return!a.call(b,c,d,e)})]},yc.letBind=yc.let=function(a){return a(this)},Ec["if"]=Ec.ifThen=function(a,b,c){return Gc(function(){return c||(c=Hc()),nb(b)&&(b=Fc(b)),nb(c)&&(c=Fc(c)),"function"==typeof c.now&&(c=Hc(c)),a()?b:c})},Ec["for"]=Ec.forIn=function(a,b){return vc(a,b).concat()};var ed=Ec["while"]=Ec.whileDo=function(a,b){return nb(b)&&(b=Fc(b)),P(a,b).concat()};yc.doWhile=function(a){return Pc([this,ed(a,this)])},Ec["case"]=Ec.switchCase=function(a,b,c){return Gc(function(){nb(c)&&(c=Fc(c)),c||(c=Hc()),"function"==typeof c.now&&(c=Hc(c));var d=b[a()];return nb(d)&&(d=Fc(d)),d||c})},yc.expand=function(a,b){hb(b)||(b=jc);var c=this;return new kd(function(d){var e=[],f=new SerialDisposable,g=new Zb(f),h=0,i=!1,j=function(){var c=!1;e.length>0&&(c=!i,i=!0),c&&f.setDisposable(b.scheduleRecursive(function(b){var c;if(!(e.length>0))return void(i=!1);c=e.shift();var f=new cc;g.add(f),f.setDisposable(c.subscribe(function(b){d.onNext(b);var c=null;try{c=a(b)}catch(f){d.onError(f)}e.push(c),h++,j()},d.onError.bind(d),function(){g.remove(f),h--,0===h&&d.onCompleted()})),b()}))};return e.push(c),h++,j(),g})},Ec.forkJoin=function(){var a=k(arguments,0);return new kd(function(b){var c=a.length;if(0===c)return b.onCompleted(),bc;for(var d=new Zb,e=!1,f=new Array(c),g=new Array(c),h=new Array(c),i=0;c>i;i++)!function(i){var j=a[i];nb(j)&&(j=Fc(j)),d.add(j.subscribe(function(a){e||(f[i]=!0,h[i]=a)},function(a){e=!0,b.onError(a),d.dispose()},function(){if(!e){if(!f[i])return void b.onCompleted();g[i]=!0;for(var a=0;c>a;a++)if(!g[a])return;e=!0,b.onNext(h),b.onCompleted()}}))}(i);return d})},yc.forkJoin=function(a,b){var c=this;return new kd(function(d){var e,f,g=!1,h=!1,i=!1,j=!1,k=new cc,l=new cc;return nb(a)&&(a=Fc(a)),k.setDisposable(c.subscribe(function(a){i=!0,e=a},function(a){l.dispose(),d.onError(a)},function(){if(g=!0,h)if(i)if(j){var a;try{a=b(e,f)}catch(c){return void d.onError(c)}d.onNext(a),d.onCompleted()}else d.onCompleted();else d.onCompleted()})),l.setDisposable(a.subscribe(function(a){j=!0,f=a},function(a){k.dispose(),d.onError(a)},function(){if(h=!0,g)if(i)if(j){var a;try{a=b(e,f)}catch(c){return void d.onError(c)}d.onNext(a),d.onCompleted()}else d.onCompleted();else d.onCompleted()})),new Zb(k,l)})},yc.manySelect=function(a,b){hb(b)||(b=jc);var c=this;return Gc(function(){var d;return c.map(function(a){var b=new fd(a);return d&&d.onNext(a),d=b,b}).tap(gb,function(a){d&&d.onError(a)},function(){d&&d.onCompleted()}).observeOn(b).map(a)})};var fd=function(a){function b(a){var b=this,c=new Zb;return c.add(kc.schedule(function(){a.onNext(b.head),c.add(b.tail.mergeObservable().subscribe(a))})),c}function c(c){a.call(this,b),this.head=c,this.tail=new od}return Rb(c,a),Sb(c.prototype,wc,{onCompleted:function(){this.onNext(Ec.empty())},onError:function(a){this.onNext(Ec.throwException(a))},onNext:function(a){this.tail.onNext(a),this.tail.onCompleted()}}),c}(Ec),gd=function(){function a(){this.keys=[],this.values=[]}return a.prototype["delete"]=function(a){var b=this.keys.indexOf(a);return-1!==b&&(this.keys.splice(b,1),this.values.splice(b,1)),-1!==b},a.prototype.get=function(a,b){var c=this.keys.indexOf(a);return-1!==c?this.values[c]:b},a.prototype.set=function(a,b){var c=this.keys.indexOf(a);-1!==c&&(this.values[c]=b),this.values[this.keys.push(a)-1]=b},a.prototype.size=function(){return this.keys.length},a.prototype.has=function(a){return-1!==this.keys.indexOf(a)},a.prototype.getKeys=function(){return this.keys.slice(0)},a.prototype.getValues=function(){return this.values.slice(0)},a}();Q.prototype.and=function(a){var b=this.patterns.slice(0);return b.push(a),new Q(b)},Q.prototype.thenDo=function(a){return new R(this,a)},R.prototype.activate=function(a,b,c){for(var d=this,e=[],f=0,g=this.expression.patterns.length;g>f;f++)e.push(S(a,this.expression.patterns[f],b.onError.bind(b)));var h=new T(e,function(){var a;try{a=d.selector.apply(d,arguments)}catch(c){return void b.onError(c)}b.onNext(a)},function(){for(var a=0,b=e.length;b>a;a++)e[a].removeActivePlan(h);c(h)});for(f=0,g=e.length;g>f;f++)e[f].addActivePlan(h);return h},T.prototype.dequeue=function(){for(var a=this.joinObservers.getValues(),b=0,c=a.length;c>b;b++)a[b].queue.shift()},T.prototype.match=function(){var a,b,c,d,e,f=!0;for(b=0,c=this.joinObserverArray.length;c>b;b++)if(0===this.joinObserverArray[b].queue.length){f=!1;break}if(f){for(a=[],d=!1,b=0,c=this.joinObserverArray.length;c>b;b++)a.push(this.joinObserverArray[b].queue[0]),"C"===this.joinObserverArray[b].queue[0].kind&&(d=!0);if(d)this.onCompleted();else{for(this.dequeue(),e=[],b=0;bc;c++)b[c].match()}},c.error=gb,c.completed=gb,c.addActivePlan=function(a){this.activePlans.push(a)},c.subscribe=function(){this.subscription.setDisposable(this.source.materialize().subscribe(this))},c.removeActivePlan=function(a){var b=this.activePlans.indexOf(a);this.activePlans.splice(b,1),0===this.activePlans.length&&this.dispose()},c.dispose=function(){a.prototype.dispose.call(this),this.isDisposed||(this.isDisposed=!0,this.subscription.dispose())},b}(zc);yc.and=function(a){return new Q([this,a])},yc.thenDo=function(a){return new Q([this]).thenDo(a)},Ec.when=function(){var a=k(arguments,0);return new kd(function(b){var c,d,e,f,g,h,i=[],j=new gd;h=xc(b.onNext.bind(b),function(a){for(var c=j.getValues(),d=0,e=c.length;e>d;d++)c[d].onError(a);b.onError(a)},b.onCompleted.bind(b));try{for(d=0,e=a.length;e>d;d++)i.push(a[d].activate(j,h,function(a){var b=i.indexOf(a);i.splice(b,1),0===i.length&&h.onCompleted()}))}catch(k){Mc(k).subscribe(b)}for(c=new Zb,g=j.getValues(),d=0,e=g.length;e>d;d++)f=g[d],f.subscribe(),c.add(f);return c})};var id=Ec.interval=function(a,b){return X(a,a,hb(b)?b:mc)},jd=Ec.timer=function(b,c,d){var e;return hb(d)||(d=mc),c!==a&&"number"==typeof c?e=c:c!==a&&"object"==typeof c&&(d=c),b instanceof Date&&e===a?U(b.getTime(),d):b instanceof Date&&e!==a?(e=c,V(b.getTime(),e,d)):e===a?W(b,d):X(b,e,d)};yc.delay=function(a,b){return hb(b)||(b=mc),a instanceof Date?Z(this,a.getTime(),b):Y(this,a,b)},yc.throttle=function(a,b){return hb(b)||(b=mc),this.throttleWithSelector(function(){return jd(a,b)})},yc.windowWithTime=function(a,b,c){var d,e=this;return null==b&&(d=a),hb(c)||(c=mc),"number"==typeof b?d=b:"object"==typeof b&&(d=a,c=b),new kd(function(b){function f(){var a=new cc,e=!1,g=!1;l.setDisposable(a),j===i?(e=!0,g=!0):i>j?e=!0:g=!0;var n=e?j:i,o=n-m;m=n,e&&(j+=d),g&&(i+=d),a.setDisposable(c.scheduleWithRelative(o,function(){var a;g&&(a=new nd,k.push(a),b.onNext(Tb(a,h))),e&&(a=k.shift(),a.onCompleted()),f()}))}var g,h,i=d,j=a,k=[],l=new SerialDisposable,m=0;return g=new Zb(l),h=new dc(g),k.push(new nd),b.onNext(Tb(k[0],h)),f(),g.add(e.subscribe(function(a){var b,c;for(b=0,c=k.length;c>b;b++)k[b].onNext(a)},function(a){var c,d;for(c=0,d=k.length;d>c;c++)k[c].onError(a);b.onError(a)},function(){var a,c;for(a=0,c=k.length;c>a;a++)k[a].onCompleted();b.onCompleted()})),h})},yc.windowWithTimeOrCount=function(a,b,c){var d=this;return hb(c)||(c=mc),new kd(function(e){function f(b){var d=new cc;timerD.setDisposable(d),d.setDisposable(c.scheduleWithRelative(a,function(){var a;b===windowId&&(i=0,a=++windowId,j.onCompleted(),j=new nd,e.onNext(Tb(j,h)),f(a))}))}var f,g,h,i=0,j=new nd;return timerD=new SerialDisposable,windowId=0,g=new Zb(timerD),h=new dc(g),e.onNext(Tb(j,h)),f(0),g.add(d.subscribe(function(a){var c=0,d=!1;j.onNext(a),i++,i===b&&(d=!0,i=0,c=++windowId,j.onCompleted(),j=new nd,e.onNext(Tb(j,h))),d&&f(c)},function(a){j.onError(a),e.onError(a)},function(){j.onCompleted(),e.onCompleted()})),h})},yc.bufferWithTime=function(){return this.windowWithTime.apply(this,arguments).selectMany(function(a){return a.toArray()})},yc.bufferWithTimeOrCount=function(a,b,c){return this.windowWithTimeOrCount(a,b,c).selectMany(function(a){return a.toArray()})},yc.timeInterval=function(a){var b=this;return hb(a)||(a=mc),Gc(function(){var c=a.now();return b.map(function(b){var d=a.now(),e=d-c;return c=d,{value:b,interval:e}})})},yc.timestamp=function(a){return hb(a)||(a=mc),this.map(function(b){return{value:b,timestamp:a.now()}})},yc.sample=function(a,b){return hb(b)||(b=mc),"number"==typeof a?$(this,id(a,b)):$(this,a)},yc.timeout=function(a,b,c){b||(b=Mc(new Error("Timeout"))),hb(c)||(c=mc);var d=this,e=a instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new kd(function(f){var g=0,h=new cc,i=new SerialDisposable,j=!1,k=new SerialDisposable;i.setDisposable(h);var l=function(){var d=g;k.setDisposable(c[e](a,function(){g===d&&(nb(b)&&(b=Fc(b)),i.setDisposable(b.subscribe(f)))}))};return l(),h.setDisposable(d.subscribe(function(a){j||(g++,f.onNext(a),l())},function(a){j||(g++,f.onError(a))},function(){j||(g++,f.onCompleted())})),new Zb(i,k)})},Ec.generateWithAbsoluteTime=function(a,b,c,d,e,f){return hb(f)||(f=mc),new kd(function(g){var h,i,j=!0,k=!1,l=a;return f.scheduleRecursiveWithAbsolute(f.now(),function(a){k&&g.onNext(h);try{j?j=!1:l=c(l),k=b(l),k&&(h=d(l),i=e(l))}catch(f){return void g.onError(f)}k?a(i):g.onCompleted()})})},Ec.generateWithRelativeTime=function(a,b,c,d,e,f){return hb(f)||(f=mc),new kd(function(g){var h,i,j=!0,k=!1,l=a;return f.scheduleRecursiveWithRelative(0,function(a){k&&g.onNext(h);try{j?j=!1:l=c(l),k=b(l),k&&(h=d(l),i=e(l))}catch(f){return void g.onError(f)}k?a(i):g.onCompleted()})})},yc.delaySubscription=function(a,b){return this.delayWithSelector(jd(a,hb(b)?b:mc),Hc)},yc.delayWithSelector=function(a,b){var c,d,e=this;return"function"==typeof a?d=a:(c=a,d=b),new kd(function(a){var b=new Zb,f=!1,g=function(){f&&0===b.length&&a.onCompleted()},h=new SerialDisposable,i=function(){h.setDisposable(e.subscribe(function(c){var e;try{e=d(c)}catch(f){return void a.onError(f)}var h=new cc;b.add(h),h.setDisposable(e.subscribe(function(){a.onNext(c),b.remove(h),g()},a.onError.bind(a),function(){a.onNext(c),b.remove(h),g()}))},a.onError.bind(a),function(){f=!0,h.dispose(),g()}))};return c?h.setDisposable(c.subscribe(function(){i()},a.onError.bind(a),function(){i()})):i(),new Zb(h,b)})},yc.timeoutWithSelector=function(a,b,c){if(1===arguments.length){b=a;var a=Kc()}c||(c=Mc(new Error("Timeout")));var d=this;return new kd(function(e){var f=new SerialDisposable,g=new SerialDisposable,h=new cc;f.setDisposable(h);var i=0,j=!1,k=function(a){var b=i,d=function(){return i===b},h=new cc;g.setDisposable(h),h.setDisposable(a.subscribe(function(){d()&&f.setDisposable(c.subscribe(e)),h.dispose()},function(a){d()&&e.onError(a)},function(){d()&&f.setDisposable(c.subscribe(e))}))};k(a);var l=function(){var a=!j;return a&&i++,a};return h.setDisposable(d.subscribe(function(a){if(l()){e.onNext(a);var c;try{c=b(a)}catch(d){return void e.onError(d)}k(c)}},function(a){l()&&e.onError(a)},function(){l()&&e.onCompleted()})),new Zb(f,g)})},yc.throttleWithSelector=function(a){var b=this;return new kd(function(c){var d,e=!1,f=new SerialDisposable,g=0,h=b.subscribe(function(b){var h;try{h=a(b)}catch(i){return void c.onError(i)}e=!0,d=b,g++;var j=g,k=new cc;f.setDisposable(k),k.setDisposable(h.subscribe(function(){e&&g===j&&c.onNext(d),e=!1,k.dispose()},c.onError.bind(c),function(){e&&g===j&&c.onNext(d),e=!1,k.dispose()}))},function(a){f.dispose(),c.onError(a),e=!1,g++},function(){f.dispose(),e&&c.onNext(d),c.onCompleted(),e=!1,g++});return new Zb(h,f)})},yc.skipLastWithTime=function(a,b){hb(b)||(b=mc);var c=this;return new kd(function(d){var e=[];return c.subscribe(function(c){var f=b.now();for(e.push({interval:f,value:c});e.length>0&&f-e[0].interval>=a;)d.onNext(e.shift().value)},d.onError.bind(d),function(){for(var c=b.now();e.length>0&&c-e[0].interval>=a;)d.onNext(e.shift().value);d.onCompleted()})})},yc.takeLastWithTime=function(a,b){var c=this;return hb(b)||(b=mc),new kd(function(d){var e=[];return c.subscribe(function(c){var d=b.now();for(e.push({interval:d,value:c});e.length>0&&d-e[0].interval>=a;)e.shift()},d.onError.bind(d),function(){for(var c=b.now();e.length>0;){var f=e.shift();c-f.interval<=a&&d.onNext(f.value)}d.onCompleted()})})},yc.takeLastBufferWithTime=function(a,b){var c=this;return hb(b)||(b=mc),new kd(function(d){var e=[];return c.subscribe(function(c){var d=b.now();for(e.push({interval:d,value:c});e.length>0&&d-e[0].interval>=a;)e.shift()},d.onError.bind(d),function(){for(var c=b.now(),f=[];e.length>0;){var g=e.shift();c-g.interval<=a&&f.push(g.value)}d.onNext(f),d.onCompleted()})})},yc.takeWithTime=function(a,b){var c=this;return hb(b)||(b=mc),new kd(function(d){return new Zb(b.scheduleWithRelative(a,d.onCompleted.bind(d)),c.subscribe(d))})},yc.skipWithTime=function(a,b){var c=this;return hb(b)||(b=mc),new kd(function(d){var e=!1;return new Zb(b.scheduleWithRelative(a,function(){e=!0}),c.subscribe(function(a){e&&d.onNext(a)},d.onError.bind(d),d.onCompleted.bind(d)))})},yc.skipUntilWithTime=function(a,b){hb(b)||(b=mc);var c=this,d=a instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new kd(function(e){var f=!1;return new Zb(b[d](a,function(){f=!0}),c.subscribe(function(a){f&&e.onNext(a)},e.onError.bind(e),e.onCompleted.bind(e)))})},yc.takeUntilWithTime=function(a,b){hb(b)||(b=mc);var c=this,d=a instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new kd(function(e){return new Zb(b[d](a,function(){e.onCompleted()}),c.subscribe(e))})},yc.exclusive=function(){var a=this;return new kd(function(b){var c=!1,d=!1,e=new cc,f=new Zb;return f.add(e),e.setDisposable(a.subscribe(function(a){if(!c){c=!0,nb(a)&&(a=Fc(a));var e=new cc;f.add(e),e.setDisposable(a.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){f.remove(e),c=!1,d&&1===f.length&&b.onCompleted()}))}},b.onError.bind(b),function(){d=!0,c||1!==f.length||b.onCompleted()})),f})},yc.exclusiveMap=function(a,b){var c=this;return new kd(function(d){var e=0,f=!1,g=!0,h=new cc,i=new Zb;return i.add(h),h.setDisposable(c.subscribe(function(c){f||(f=!0,innerSubscription=new cc,i.add(innerSubscription),nb(c)&&(c=Fc(c)),innerSubscription.setDisposable(c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}d.onNext(g)},d.onError.bind(d),function(){i.remove(innerSubscription),f=!1,g&&1===i.length&&d.onCompleted()})))},d.onError.bind(d),function(){g=!0,1!==i.length||f||d.onCompleted()})),i})},fb.VirtualTimeScheduler=function(a){function b(){throw new Error("Not implemented")}function c(){return this.toDateTimeOffset(this.clock)}function d(a,b){return this.scheduleAbsoluteWithState(a,this.clock,b)}function e(a,b,c){return this.scheduleRelativeWithState(a,this.toRelative(b),c)}function f(a,b,c){return this.scheduleRelativeWithState(a,this.toRelative(b-this.now()),c)}function g(a,b){return b(),bc}function h(b,g){this.clock=b,this.comparer=g,this.isEnabled=!1,this.queue=new Xb(1024),a.call(this,c,d,e,f)}Rb(h,a);var i=h.prototype;return i.add=b,i.toDateTimeOffset=b,i.toRelative=b,i.schedulePeriodicWithState=function(a,b,c){var d=new ic(this,a,b,c);return d.start()},i.scheduleRelativeWithState=function(a,b,c){var d=this.add(this.clock,b);return this.scheduleAbsoluteWithState(a,d,c)},i.scheduleRelative=function(a,b){return this.scheduleRelativeWithState(b,a,g)},i.start=function(){if(!this.isEnabled){this.isEnabled=!0;do{var a=this.getNext();null!==a?(this.comparer(a.dueTime,this.clock)>0&&(this.clock=a.dueTime),a.invoke()):this.isEnabled=!1}while(this.isEnabled)}},i.stop=function(){this.isEnabled=!1},i.advanceTo=function(a){var b=this.comparer(this.clock,a);if(this.comparer(this.clock,a)>0)throw new Error(qb);if(0!==b&&!this.isEnabled){this.isEnabled=!0;do{var c=this.getNext();null!==c&&this.comparer(c.dueTime,a)<=0?(this.comparer(c.dueTime,this.clock)>0&&(this.clock=c.dueTime),c.invoke()):this.isEnabled=!1}while(this.isEnabled);this.clock=a}},i.advanceBy=function(a){var b=this.add(this.clock,a),c=this.comparer(this.clock,b);if(c>0)throw new Error(qb);0!==c&&this.advanceTo(b)},i.sleep=function(a){var b=this.add(this.clock,a);if(this.comparer(this.clock,b)>=0)throw new Error(qb);this.clock=b},i.getNext=function(){for(;this.queue.length>0;){var a=this.queue.peek();if(!a.isCancelled())return a;this.queue.dequeue()}return null},i.scheduleAbsolute=function(a,b){return this.scheduleAbsoluteWithState(b,a,g)},i.scheduleAbsoluteWithState=function(a,b,c){function d(a,b){return e.queue.remove(f),c(a,b)}var e=this,f=new ec(this,a,d,b,this.comparer);return this.queue.enqueue(f),f.disposable},h}(fc),fb.HistoricalScheduler=function(a){function b(b,c){var d=null==b?0:b,e=c||lb;a.call(this,d,e)}Rb(b,a);var c=b.prototype;return c.add=function(a,b){return a+b},c.toDateTimeOffset=function(a){return new Date(a).getTime()},c.toRelative=function(a){return a},b}(fb.VirtualTimeScheduler);var kd=fb.AnonymousObservable=function(a){function b(a){return a&&"function"==typeof a.dispose?a:"function"==typeof a?ac(a):bc}function c(d){function e(a){var c=function(){try{e.setDisposable(b(d(e)))}catch(a){if(!e.fail(a))throw a}},e=new ld(a);return kc.scheduleRequired()?kc.schedule(c):c(),e}return this instanceof c?void a.call(this,e):new c(d)}return Rb(c,a),c}(Ec),ld=function(a){function b(b){a.call(this),this.observer=b,this.m=new cc}Rb(b,a);var c=b.prototype;return c.next=function(a){var b=!1;try{this.observer.onNext(a),b=!0}catch(c){throw c}finally{b||this.dispose()}},c.error=function(a){try{this.observer.onError(a)}catch(b){throw b}finally{this.dispose()}},c.completed=function(){try{this.observer.onCompleted()}catch(a){throw a}finally{this.dispose()}},c.setDisposable=function(a){this.m.setDisposable(a)},c.getDisposable=function(){return this.m.getDisposable()},c.disposable=function(a){return arguments.length?this.getDisposable():setDisposable(a)},c.dispose=function(){a.prototype.dispose.call(this),this.m.dispose()},b}(zc),md=function(a){function b(a){return this.underlyingObservable.subscribe(a)}function c(c,d,e){a.call(this,b),this.key=c,this.underlyingObservable=e?new kd(function(a){return new Zb(e.getDisposable(),d.subscribe(a))}):d}return Rb(c,a),c}(Ec),nd=fb.Subject=function(a){function c(a){return b.call(this),this.isStopped?this.exception?(a.onError(this.exception),bc):(a.onCompleted(),bc):(this.observers.push(a),new _c(this,a))}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return Rb(d,a),Sb(d.prototype,wc,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped)for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)},dispose:function(){this.isDisposed=!0,this.observers=null}}),d.create=function(a,b){return new pd(a,b)},d}(Ec),od=fb.AsyncSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),new _c(this,a);var c=this.exception,d=this.hasValue,e=this.value;return c?a.onError(c):d?(a.onNext(e),a.onCompleted()):a.onCompleted(),bc}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return Rb(d,a),Sb(d.prototype,wc,{hasObservers:function(){return b.call(this),this.observers.length>0},onCompleted:function(){var a,c,d;if(b.call(this),!this.isStopped){this.isStopped=!0;var e=this.observers.slice(0),f=this.value,g=this.hasValue;if(g)for(c=0,d=e.length;d>c;c++)a=e[c],a.onNext(f),a.onCompleted();else for(c=0,d=e.length;d>c;c++)e[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){b.call(this),this.isStopped||(this.value=a,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),d}(Ec),pd=fb.AnonymousSubject=function(a){function b(b,c){this.observer=b,this.observable=c,a.call(this,this.observable.subscribe.bind(this.observable))}return Rb(b,a),Sb(b.prototype,wc,{onCompleted:function(){this.observer.onCompleted()},onError:function(a){this.observer.onError(a)},onNext:function(a){this.observer.onNext(a)}}),b}(Ec);"function"==typeof define&&"object"==typeof define.amd&&define.amd?(ab.Rx=fb,define(function(){return fb})):bb&&cb?db?(cb.exports=fb).Rx=fb:bb.Rx=fb:ab.Rx=fb}).call(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.all.js b/ajax/libs/rxjs/2.3.9/rx.all.js new file mode 100644 index 000000000..1a0f74df2 --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.all.js @@ -0,0 +1,9224 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { + + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, + isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = Date.now, + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || + '_es6shim_iterator_'; + // Bug for mozilla version + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { + return; + } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { + return; + } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = + SerialDisposable = Rx.SerialDisposable = (function () { + function BooleanDisposable () { + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + old && old.dispose(); + shouldDispose && value && value.dispose(); + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + old && old.dispose(); + }; + + return BooleanDisposable; + }()); + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + timeSpan < 0 && (timeSpan = 0); + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + (function (schedulerProto) { + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function scheduleInnerRecursive(action, self) { + action(function(dt) { self(action, dt); }); + } + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { self(_action); }); }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + }(Scheduler.prototype)); + + (function (schedulerProto) { + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, action); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var s = state; + + var id = setInterval(function () { + s = action(s); + }, period); + + return disposableCreate(function () { + clearInterval(id); + }); + }; + }(Scheduler.prototype)); + + (function (schedulerProto) { + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchError = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + }(Scheduler.prototype)); + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt); + + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + + currentScheduler.scheduleRequired = function () { return !queue; }; + currentScheduler.ensureTrampoline = function (action) { + if (!queue) { this.schedule(action); } else { action(); } + }; + + return currentScheduler; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, + dt = Scheduler.normalize(dueTime); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** @private */ + var CatchScheduler = (function (_super) { + + function localNow() { + return this._scheduler.now(); + } + + function scheduleNow(state, action) { + return this._scheduler.scheduleWithState(state, this._wrap(action)); + } + + function scheduleRelative(state, dueTime, action) { + return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); + } + + function scheduleAbsolute(state, dueTime, action) { + return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); + } + + inherits(CatchScheduler, _super); + + /** @private */ + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + /** @private */ + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + /** @private */ + CatchScheduler.prototype._wrap = function (action) { + var parent = this; + return function (self, state) { + try { + return action(parent._getRecursiveWrapper(self), state); + } catch (e) { + if (!parent._handler(e)) { throw e; } + return disposableEmpty; + } + }; + }; + + /** @private */ + CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { + if (this._recursiveOriginal !== scheduler) { + this._recursiveOriginal = scheduler; + var wrapper = this._clone(scheduler); + wrapper._recursiveOriginal = scheduler; + wrapper._recursiveWrapper = wrapper; + this._recursiveWrapper = wrapper; + } + return this._recursiveWrapper; + }; + + /** @private */ + CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var self = this, failed = false, d = new SingleAssignmentDisposable(); + + d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { + if (failed) { return null; } + try { + return action(state1); + } catch (e) { + failed = true; + if (!self._handler(e)) { throw e; } + d.dispose(); + return null; + } + })); + + return d; + }; + + return CatchScheduler; + }(Scheduler)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { + return observerOrOnNext && typeof observerOrOnNext === 'object' ? + this._acceptObservable(observerOrOnNext) : + this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notifications + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + Notification.prototype.toObservable = function (scheduler) { + var notification = this; + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + notification.kind === 'N' && observer.onCompleted(); + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + + function _accept (onNext) { return onNext(this.value); } + function _acceptObservable(observer) { return observer.onNext(this.value); } + function toString () { return 'OnNext(' + this.value + ')'; } + + return function (value) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + + function _accept (onNext, onError) { return onError(this.exception); } + function _acceptObservable(observer) { return observer.onError(this.exception); } + function toString () { return 'OnError(' + this.exception + ')'; } + + return function (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { return onCompleted(); } + function _acceptObservable(observer) { return observer.onCompleted(); } + function toString () { return 'OnCompleted()'; } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var CheckedObserver = (function (_super) { + inherits(CheckedObserver, _super); + + function CheckedObserver(observer) { + _super.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + try { + this._observer.onNext(value); + } catch (e) { + throw e; + } finally { + this._state = 0; + } + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + try { + this._observer.onError(err); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + try { + this._observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { + inherits(ScheduledObserver, _super); + + function ScheduledObserver(scheduler, observer) { + _super.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + /** @private */ + var ObserveOnObserver = (function (_super) { + inherits(ObserveOnObserver, _super); + + /** @private */ + function ObserveOnObserver() { + _super.apply(this, arguments); + } + + /** @private */ + ObserveOnObserver.prototype.next = function (value) { + _super.prototype.next.call(this, value); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.error = function (e) { + _super.prototype.error.call(this, e); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.completed = function () { + _super.prototype.completed.call(this); + this.ensureActive(); + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber = typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted); + + return this._subscribe(subscriber); + }; + + return Observable; + })(); + + /** + * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + * + * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects + * that require to be run on a scheduler, use subscribeOn. + * + * @param {Scheduler} scheduler Scheduler to notify observers on. + * @returns {Observable} The source sequence whose observations happen on the specified scheduler. + */ + observableProto.observeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(new ObserveOnObserver(scheduler, observer)); + }); + }; + + /** + * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; + * see the remarks section for more information on the distinction between subscribeOn and observeOn. + + * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer + * callbacks on a scheduler, use observeOn. + + * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. + * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); + d.setDisposable(m); + m.setDisposable(scheduler.schedule(function () { + d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); + })); + return d; + }); + }; + + /** + * Converts a Promise to an Observable sequence + * @param {Promise} An ES6 Compliant promise. + * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. + */ + var observableFromPromise = Observable.fromPromise = function (promise) { + return observableDefer(function () { + var subject = new Rx.AsyncSubject(); + + promise.then( + function (value) { + if (!subject.isDisposed) { + subject.onNext(value); + subject.onCompleted(); + } + }, + subject.onError.bind(subject)); + + return subject; + }); + }; + /* + * Converts an existing observable sequence to an ES6 Compatible Promise + * @example + * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); + * + * // With config + * Rx.config.Promise = RSVP.Promise; + * var promise = Rx.Observable.return(42).toPromise(); + * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. + * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. + */ + observableProto.toPromise = function (promiseCtor) { + promiseCtor || (promiseCtor = Rx.config.Promise); + if (!promiseCtor) { + throw new Error('Promise type not provided nor in Rx.config.Promise'); + } + var source = this; + return new promiseCtor(function (resolve, reject) { + // No cancellation can be done + var value, hasValue = false; + source.subscribe(function (v) { + value = v; + hasValue = true; + }, function (err) { + reject(err); + }, function () { + if (hasValue) { + resolve(value); + } + }); + }); + }; + /** + * Creates a list from an observable sequence. + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + var self = this; + return new AnonymousObservable(function(observer) { + var arr = []; + return self.subscribe( + arr.push.bind(arr), + observer.onError.bind(observer), + function () { + observer.onNext(arr); + observer.onCompleted(); + }); + }); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.create = Observable.createWithDisposable = function (subscribe) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + var maxSafeInteger = Math.pow(2, 53) - 1; + + function numberIsFinite(value) { + return typeof value === 'number' && root.isFinite(value); + } + + function isNan(n) { + return n !== n; + } + + function isIterable(o) { + return o[$iterator$] !== undefined; + } + + function sign(value) { + var number = +value; + if (number === 0) { return number; } + if (isNaN(number)) { return number; } + return number < 0 ? -1 : 1; + } + + function toLength(o) { + var len = +o.length; + if (isNaN(len)) { return 0; } + if (len === 0 || !numberIsFinite(len)) { return len; } + len = sign(len) * Math.floor(Math.abs(len)); + if (len <= 0) { return 0; } + if (len > maxSafeInteger) { return maxSafeInteger; } + return len; + } + + function isCallable(f) { + return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; + } + + /** + * This method creates a new Observable sequence from an array-like or iterable object. + * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. + * @param {Function} [mapFn] Map function to call on every element of the array. + * @param {Any} [thisArg] The context to use calling the mapFn if provided. + * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + Observable.from = function (iterable, mapFn, thisArg, scheduler) { + if (iterable == null) { + throw new Error('iterable cannot be null.') + } + if (mapFn && !isCallable(mapFn)) { + throw new Error('mapFn when provided must be a function'); + } + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var list = Object(iterable), + objIsIterable = isIterable(list), + len = objIsIterable ? 0 : toLength(list), + it = objIsIterable ? list[$iterator$]() : null, + i = 0; + return scheduler.scheduleRecursive(function (self) { + if (i < len || objIsIterable) { + var result; + if (objIsIterable) { + var next = it.next(); + if (next.done) { + observer.onCompleted(); + return; + } + + result = next.value; + } else { + result = list[i]; + } + + if (mapFn && isCallable(mapFn)) { + try { + result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); + } catch (e) { + observer.onError(e); + return; + } + } + + observer.onNext(result); + i++; + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * var res = Rx.Observable.fromArray([1,2,3]); + * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0, len = array.length; + return scheduler.scheduleRecursive(function (self) { + if (count < len) { + observer.onNext(array[count++]); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. + * @returns {Observable} The generated sequence. + */ + Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var first = true, state = initialState; + return scheduler.scheduleRecursive(function (self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + } + } catch (exception) { + observer.onError(exception); + return; + } + if (hasResult) { + observer.onNext(result); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.of = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return observableFromArray(args); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + var observableOf = Observable.ofWithScheduler = function (scheduler) { + var len = arguments.length - 1, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } + return observableFromArray(args, scheduler); + }; + + /** + * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). + * @returns {Observable} An observable sequence whose observers will never get called. + */ + var observableNever = Observable.never = function () { + return new AnonymousObservable(function () { + return disposableEmpty; + }); + }; + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.range(0, 10); + * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleRecursiveWithState(0, function (i, self) { + if (i < count) { + observer.onNext(start + i); + self(i + 1); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.repeat(42); + * var res = Rx.Observable.repeat(42, 4); + * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'just', and 'returnValue' for browsers 0) { + subscribe(q.shift()); + } else { + activeCount--; + isStopped && activeCount === 0 && observer.onCompleted(); + } + })); + } + group.add(sources.subscribe(function (innerSource) { + if (activeCount < maxConcurrentOrOther) { + activeCount++; + subscribe(innerSource); + } else { + q.push(innerSource); + } + }, observer.onError.bind(observer), function () { + isStopped = true; + activeCount === 0 && observer.onCompleted(); + })); + return group; + }); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * + * @example + * 1 - merged = Rx.Observable.merge(xs, ys, zs); + * 2 - merged = Rx.Observable.merge([xs, ys, zs]); + * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); + * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources; + if (!arguments[0]) { + scheduler = immediateScheduler; + sources = slice.call(arguments, 1); + } else if (arguments[0].now) { + scheduler = arguments[0]; + sources = slice.call(arguments, 1); + } else { + scheduler = immediateScheduler; + sources = slice.call(arguments, 0); + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableFromArray(sources, scheduler).mergeObservable(); + }; + + /** + * Merges an observable sequence of observable sequences into an observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.mergeObservable = observableProto.mergeAll =function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + isStopped = false, + m = new SingleAssignmentDisposable(); + + group.add(m); + m.setDisposable(sources.subscribe(function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + innerSubscription.setDisposable(innerSource.subscribe(function (x) { + observer.onNext(x); + }, observer.onError.bind(observer), function () { + group.remove(innerSubscription); + if (isStopped && group.length === 1) { observer.onCompleted(); } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (group.length === 1) { observer.onCompleted(); } + })); + return group; + }); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. + * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. + */ + observableProto.onErrorResumeNext = function (second) { + if (!second) { + throw new Error('Second observable is required'); + } + return onErrorResumeNext([this, second]); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * + * @example + * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); + * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); + * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. + */ + var onErrorResumeNext = Observable.onErrorResumeNext = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var pos = 0, subscription = new SerialDisposable(), + cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, d; + if (pos < sources.length) { + current = sources[pos++]; + isPromise(current) && (current = observableFromPromise(current)); + d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { + self(); + }, function () { + self(); + })); + } else { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + isOpen && observer.onNext(left); + }, observer.onError.bind(observer), function () { + isOpen && observer.onCompleted(); + })); + + isPromise(other) && (other = observableFromPromise(other)); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, observer.onError.bind(observer), function () { + rightSubscription.dispose(); + })); + + return disposables; + }); + }; + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasLatest = false, + innerSubscription = new SerialDisposable(), + isStopped = false, + latest = 0, + subscription = sources.subscribe(function (innerSource) { + var d = new SingleAssignmentDisposable(), id = ++latest; + hasLatest = true; + innerSubscription.setDisposable(d); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + d.setDisposable(innerSource.subscribe(function (x) { + if (latest === id) { + observer.onNext(x); + } + }, function (e) { + if (latest === id) { + observer.onError(e); + } + }, function () { + if (latest === id) { + hasLatest = false; + if (isStopped) { + observer.onCompleted(); + } + } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (!hasLatest) { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, innerSubscription); + }); + }; + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + isPromise(other) && (other = observableFromPromise(other)); + return new CompositeDisposable( + source.subscribe(observer), + other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) + ); + }); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], result; + try { + result = resultSelector(left, right); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + } else { + observer.onCompleted(); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. + * + * @example + * 1 - res = obs1.zip(obs2, fn); + * 1 - res = x1.zip([1,2,3], fn); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { + return zipArray.apply(this, arguments); + } + var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); + sources.unshift(parent); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + var res, queuedValues; + if (queues.every(function (x) { return x.length > 0; })) { + try { + queuedValues = queues.map(function (x) { return x.shift(); }); + res = resultSelector.apply(parent, queuedValues); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(function (x) { return x; })) { + observer.onCompleted(); + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = sources[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + * @param arguments Observable sources. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var args = slice.call(arguments, 0), + first = args.shift(); + return first.zip.apply(first, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + return; + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(identity)) { + observer.onCompleted(); + return; + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + })(idx); + } + + var compositeDisposable = new CompositeDisposable(subscriptions); + compositeDisposable.add(disposableCreate(function () { + for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { + queues[qIdx] = []; + } + })); + return compositeDisposable; + }); + }; + + /** + * Hides the identity of an observable sequence. + * @returns {Observable} An observable sequence that hides the identity of the source sequence. + */ + observableProto.asObservable = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(observer); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. + * + * @example + * var res = xs.bufferWithCount(10); + * var res = xs.bufferWithCount(10, 1); + * @param {Number} count Length of each buffer. + * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithCount = function (count, skip) { + if (typeof skip !== 'number') { + skip = count; + } + return this.windowWithCount(count, skip).selectMany(function (x) { + return x.toArray(); + }).where(function (x) { + return x.length > 0; + }); + }; + + /** + * Dematerializes the explicit notification values of an observable sequence as implicit notifications. + * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + return x.accept(observer); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + * + * var obs = observable.distinctUntilChanged(); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. + * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. + * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + observableProto.distinctUntilChanged = function (keySelector, comparer) { + var source = this; + keySelector || (keySelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var comparerEquals = false, key; + try { + key = keySelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + if (hasCurrentKey) { + try { + comparerEquals = comparer(currentKey, key); + } catch (exception) { + observer.onError(exception); + return; + } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + observer.onNext(value); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * + * @example + * var res = observable.do(observer); + * var res = observable.do(onNext); + * var res = observable.do(onNext, onError); + * var res = observable.do(onNext, onError, onCompleted); + * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { + var source = this, onNextFunc; + if (typeof observerOrOnNext === 'function') { + onNextFunc = observerOrOnNext; + } else { + onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); + onError = observerOrOnNext.onError.bind(observerOrOnNext); + onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); + } + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + try { + onNextFunc(x); + } catch (e) { + observer.onError(e); + } + observer.onNext(x); + }, function (err) { + if (!onError) { + observer.onError(err); + } else { + try { + onError(err); + } catch (e) { + observer.onError(e); + } + observer.onError(err); + } + }, function () { + if (!onCompleted) { + observer.onCompleted(); + } else { + try { + onCompleted(); + } catch (e) { + observer.onError(e); + } + observer.onCompleted(); + } + }); + }); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * + * @example + * var res = observable.finallyAction(function () { console.log('sequence ended'; }); + * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. + * @returns {Observable} Source sequence with the action-invoking termination behavior applied. + */ + observableProto['finally'] = observableProto.finallyAction = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription; + try { + subscription = source.subscribe(observer); + } catch (e) { + action(); + throw e; + } + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Materializes the implicit notifications of an observable sequence as explicit notification values. + * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. + */ + observableProto.materialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (value) { + observer.onNext(notificationCreateOnNext(value)); + }, function (e) { + observer.onNext(notificationCreateOnError(e)); + observer.onCompleted(); + }, function () { + observer.onNext(notificationCreateOnCompleted()); + observer.onCompleted(); + }); + }); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * + * @example + * var res = repeated = source.repeat(); + * var res = repeated = source.repeat(42); + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + observableProto.repeat = function (repeatCount) { + return enumerableRepeat(this, repeatCount).concat(); + }; + + /** + * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. + * Note if you encounter an error and want it to retry once, then you must use .retry(2); + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(2); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchException(); + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @example + * var res = source.scan(function (acc, x) { return acc + x; }); + * var res = source.scan(0, function (acc, x) { return acc + x; }); + * @param {Mixed} [seed] The initial accumulator value. + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @returns {Observable} An observable sequence containing the accumulated values. + */ + observableProto.scan = function () { + var hasSeed = false, seed, accumulator, source = this; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[0]; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return new AnonymousObservable(function (observer) { + var hasAccumulation, accumulation, hasValue; + return source.subscribe ( + function (x) { + try { + if (!hasValue) { + hasValue = true; + } + + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(accumulation); + }, + observer.onError.bind(observer), + function () { + if (!hasValue && hasSeed) { + observer.onNext(seed); + } + observer.onCompleted(); + } + ); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + observer.onNext(q.shift()); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * + * @memberOf Observable# + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && 'now' in Object(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + values = slice.call(arguments, start); + return enumerableFor([observableFromArray(values, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence. + * + * @example + * var res = source.takeLast(5); + * + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, observer.onError.bind(observer), function () { + while(q.length > 0) { observer.onNext(q.shift()); } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, observer.onError.bind(observer), function () { + observer.onNext(q); + observer.onCompleted(); + }); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. + * + * var res = xs.windowWithCount(10); + * var res = xs.windowWithCount(10, 1); + * @param {Number} count Length of each window. + * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithCount = function (count, skip) { + var source = this; + if (count <= 0) { + throw new Error(argumentOutOfRange); + } + if (arguments.length === 1) { + skip = count; + } + if (skip <= 0) { + throw new Error(argumentOutOfRange); + } + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), + refCountDisposable = new RefCountDisposable(m), + n = 0, + q = [], + createWindow = function () { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + }; + createWindow(); + m.setDisposable(source.subscribe(function (x) { + var s; + for (var i = 0, len = q.length; i < len; i++) { + q[i].onNext(x); + } + var c = n - count + 1; + if (c >= 0 && c % skip === 0) { + s = q.shift(); + s.onCompleted(); + } + n++; + if (n % skip === 0) { + createWindow(); + } + }, function (exception) { + while (q.length > 0) { + q.shift().onError(exception); + } + observer.onError(exception); + }, function () { + while (q.length > 0) { + q.shift().onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + function concatMap(source, selector, thisArg) { + return source.map(function (x, i) { + var result = selector.call(thisArg, x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).concatAll(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { + if (resultSelector) { + return this.concatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }); + } + return typeof selector === 'function' ? + concatMap(this, selector, thisArg) : + concatMap(this, function () { return selector; }); + }; + + /** + * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. + * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. + * @param {Function} onError A transform function to apply when an error occurs in the source sequence. + * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. + * @param {Any} [thisArg] An optional "this" to use to invoke each transform. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. + */ + observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + var result; + try { + result = onNext.call(thisArg, x, index++); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + }, + function (err) { + var result; + try { + result = onError.call(thisArg, err); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }, + function () { + var result; + try { + result = onCompleted.call(thisArg); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }); + }).concatAll(); + }; + /** + * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * var res = obs = xs.defaultIfEmpty(); + * 2 - obs = xs.defaultIfEmpty(false); + * + * @memberOf Observable# + * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. + * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. + */ + observableProto.defaultIfEmpty = function (defaultValue) { + var source = this; + if (defaultValue === undefined) { + defaultValue = null; + } + return new AnonymousObservable(function (observer) { + var found = false; + return source.subscribe(function (x) { + found = true; + observer.onNext(x); + }, observer.onError.bind(observer), function () { + if (!found) { + observer.onNext(defaultValue); + } + observer.onCompleted(); + }); + }); + }; + + // Swap out for Array.findIndex + function arrayIndexOfComparer(array, item, comparer) { + for (var i = 0, len = array.length; i < len; i++) { + if (comparer(array[i], item)) { return i; } + } + return -1; + } + + function HashSet(comparer) { + this.comparer = comparer; + this.set = []; + } + HashSet.prototype.push = function(value) { + var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; + retValue && this.set.push(value); + return retValue; + }; + + /** + * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. + * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. + * + * @example + * var res = obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [comparer] Used to compare items in the collection. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, comparer) { + var source = this; + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hashSet = new HashSet(comparer); + return source.subscribe(function (x) { + var key = x; + + if (keySelector) { + try { + key = keySelector(x); + } catch (e) { + observer.onError(e); + return; + } + } + hashSet.push(key) && observer.onNext(x); + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer)); + }); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. + * + * @example + * var res = observable.groupBy(function (x) { return x.id; }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. + * @param {Function} [comparer] Used to determine whether the objects are equal. + * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + observableProto.groupBy = function (keySelector, elementSelector, comparer) { + return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function. + * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same + * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. + * + * @example + * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} durationSelector A function to signal the expiration of a group. + * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. + * @returns {Observable} + * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. + * + */ + observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { + var source = this; + elementSelector || (elementSelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + function handleError(e) { return function (item) { item.onError(e); }; } + var map = new Dictionary(0, comparer), + groupDisposable = new CompositeDisposable(), + refCountDisposable = new RefCountDisposable(groupDisposable); + + groupDisposable.add(source.subscribe(function (x) { + var key; + try { + key = keySelector(x); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + var fireNewMapEntry = false, + writer = map.tryGetValue(key); + if (!writer) { + writer = new Subject(); + map.set(key, writer); + fireNewMapEntry = true; + } + + if (fireNewMapEntry) { + var group = new GroupedObservable(key, writer, refCountDisposable), + durationGroup = new GroupedObservable(key, writer); + try { + duration = durationSelector(durationGroup); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + observer.onNext(group); + + var md = new SingleAssignmentDisposable(); + groupDisposable.add(md); + + var expire = function () { + map.remove(key) && writer.onCompleted(); + groupDisposable.remove(md); + }; + + md.setDisposable(duration.take(1).subscribe( + noop, + function (exn) { + map.getValues().forEach(handleError(exn)); + observer.onError(exn); + }, + expire) + ); + } + + var element; + try { + element = elementSelector(x); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + writer.onNext(element); + }, function (ex) { + map.getValues().forEach(handleError(ex)); + observer.onError(ex); + }, function () { + map.getValues().forEach(function (item) { item.onCompleted(); }); + observer.onCompleted(); + })); + + return refCountDisposable; + }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + observableProto.select = observableProto.map = function (selector, thisArg) { + var parent = this; + return new AnonymousObservable(function (observer) { + var count = 0; + return parent.subscribe(function (value) { + var result; + try { + result = selector.call(thisArg, value, count++, parent); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Retrieves the value of a specified property from all elements in the Observable sequence. + * @param {String} property The property to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function (property) { + return this.select(function (x) { return x[property]; }); + }; + + function flatMap(source, selector, thisArg) { + return source.map(function (x, i) { + var result = selector.call(thisArg, x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).mergeObservable(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { + if (resultSelector) { + return this.flatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }, thisArg); + } + return typeof selector === 'function' ? + flatMap(this, selector, thisArg) : + flatMap(this, function () { return selector; }); + }; + + /** + * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. + * @param {Function} onError A transform function to apply when an error occurs in the source sequence. + * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. + * @param {Any} [thisArg] An optional "this" to use to invoke each transform. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. + */ + observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + var result; + try { + result = onNext.call(thisArg, x, index++); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + }, + function (err) { + var result; + try { + result = onError.call(thisArg, err); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }, + function () { + var result; + try { + result = onCompleted.call(thisArg); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }); + }).mergeAll(); + }; + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { + throw new Error(argumentOutOfRange); + } + var observable = this; + return new AnonymousObservable(function (observer) { + var remaining = count; + return observable.subscribe(function (x) { + if (remaining <= 0) { + observer.onNext(x); + } else { + remaining--; + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + * The element's index is used in the logic of the predicate function. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !predicate.call(thisArg, x, i++, source); + } catch (e) { + observer.onError(e); + return; + } + } + if (running) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.exception = null; + } + }); + + return BehaviorSubject; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. + */ + var ReplaySubject = Rx.ReplaySubject = (function (_super) { + + function RemovableDisposable (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + RemovableDisposable.prototype.dispose = function () { + this.observer.dispose(); + if (!this.subject.isDisposed) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + } + }; + + function subscribe(observer) { + var so = new ScheduledObserver(this.scheduler, observer), + subscription = new RemovableDisposable(this, so); + checkDisposed.call(this); + this._trim(this.scheduler.now()); + this.observers.push(so); + + var n = this.q.length; + + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } + + if (this.hasError) { + n++; + so.onError(this.error); + } else if (this.isStopped) { + n++; + so.onCompleted(); + } + + so.ensureActive(n); + return subscription; + } + + inherits(ReplaySubject, _super); + + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; + this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + _super.call(this, subscribe); + } + + addProperties(ReplaySubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /* @private */ + _trim: function (now) { + while (this.q.length > this.bufferSize) { + this.q.shift(); + } + while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { + this.q.shift(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); + + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onNext(value); + observer.ensureActive(); + } + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { + inherits(ConnectableObservable, __super__); + + function ConnectableObservable(source, subject) { + var hasSubscription = false, + subscription, + sourceObservable = source.asObservable(); + + this.connect = function () { + if (!hasSubscription) { + hasSubscription = true; + subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { + hasSubscription = false; + })); + } + return subscription; + }; + + __super__.call(this, subject.subscribe.bind(subject)); + } + + ConnectableObservable.prototype.refCount = function () { + var connectableSubscription, count = 0, source = this; + return new AnonymousObservable(function (observer) { + var shouldConnect = ++count === 1, + subscription = source.subscribe(observer); + shouldConnect && (connectableSubscription = source.connect()); + return function () { + subscription.dispose(); + --count === 0 && connectableSubscription.dispose(); + }; + }); + }; + + return ConnectableObservable; + }(Observable)); + + var Dictionary = (function () { + + var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], + noSuchkey = "no such key", + duplicatekey = "duplicate key"; + + function isPrime(candidate) { + if (candidate & 1 === 0) { return candidate === 2; } + var num1 = Math.sqrt(candidate), + num2 = 3; + while (num2 <= num1) { + if (candidate % num2 === 0) { return false; } + num2 += 2; + } + return true; + } + + function getPrime(min) { + var index, num, candidate; + for (index = 0; index < primes.length; ++index) { + num = primes[index]; + if (num >= min) { return num; } + } + candidate = min | 1; + while (candidate < primes[primes.length - 1]) { + if (isPrime(candidate)) { return candidate; } + candidate += 2; + } + return min; + } + + function stringHashFn(str) { + var hash = 757602046; + if (!str.length) { return hash; } + for (var i = 0, len = str.length; i < len; i++) { + var character = str.charCodeAt(i); + hash = ((hash<<5)-hash)+character; + hash = hash & hash; + } + return hash; + } + + function numberHashFn(key) { + var c2 = 0x27d4eb2d; + key = (key ^ 61) ^ (key >>> 16); + key = key + (key << 3); + key = key ^ (key >>> 4); + key = key * c2; + key = key ^ (key >>> 15); + return key; + } + + var getHashCode = (function () { + var uniqueIdCounter = 0; + + return function (obj) { + if (obj == null) { throw new Error(noSuchkey); } + + // Check for built-ins before tacking on our own for any object + if (typeof obj === 'string') { return stringHashFn(obj); } + if (typeof obj === 'number') { return numberHashFn(obj); } + if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } + if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } + if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } + if (typeof obj.valueOf === 'function') { + // Hack check for valueOf + var valueOf = obj.valueOf(); + if (typeof valueOf === 'number') { return numberHashFn(valueOf); } + if (typeof obj === 'string') { return stringHashFn(valueOf); } + } + if (obj.getHashCode) { return obj.getHashCode(); } + + var id = 17 * uniqueIdCounter++; + obj.getHashCode = function () { return id; }; + return id; + }; + }()); + + function newEntry() { + return { key: null, value: null, next: 0, hashCode: 0 }; + } + + function Dictionary(capacity, comparer) { + if (capacity < 0) { throw new Error('out of range'); } + if (capacity > 0) { this._initialize(capacity); } + + this.comparer = comparer || defaultComparer; + this.freeCount = 0; + this.size = 0; + this.freeList = -1; + } + + var dictionaryProto = Dictionary.prototype; + + dictionaryProto._initialize = function (capacity) { + var prime = getPrime(capacity), i; + this.buckets = new Array(prime); + this.entries = new Array(prime); + for (i = 0; i < prime; i++) { + this.buckets[i] = -1; + this.entries[i] = newEntry(); + } + this.freeList = -1; + }; + + dictionaryProto.add = function (key, value) { + return this._insert(key, value, true); + }; + + dictionaryProto._insert = function (key, value, add) { + if (!this.buckets) { this._initialize(0); } + var index3, + num = getHashCode(key) & 2147483647, + index1 = num % this.buckets.length; + for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { + if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { + if (add) { throw new Error(duplicatekey); } + this.entries[index2].value = value; + return; + } + } + if (this.freeCount > 0) { + index3 = this.freeList; + this.freeList = this.entries[index3].next; + --this.freeCount; + } else { + if (this.size === this.entries.length) { + this._resize(); + index1 = num % this.buckets.length; + } + index3 = this.size; + ++this.size; + } + this.entries[index3].hashCode = num; + this.entries[index3].next = this.buckets[index1]; + this.entries[index3].key = key; + this.entries[index3].value = value; + this.buckets[index1] = index3; + }; + + dictionaryProto._resize = function () { + var prime = getPrime(this.size * 2), + numArray = new Array(prime); + for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } + var entryArray = new Array(prime); + for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } + for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } + for (var index1 = 0; index1 < this.size; ++index1) { + var index2 = entryArray[index1].hashCode % prime; + entryArray[index1].next = numArray[index2]; + numArray[index2] = index1; + } + this.buckets = numArray; + this.entries = entryArray; + }; + + dictionaryProto.remove = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647, + index1 = num % this.buckets.length, + index2 = -1; + for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { + if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { + if (index2 < 0) { + this.buckets[index1] = this.entries[index3].next; + } else { + this.entries[index2].next = this.entries[index3].next; + } + this.entries[index3].hashCode = -1; + this.entries[index3].next = this.freeList; + this.entries[index3].key = null; + this.entries[index3].value = null; + this.freeList = index3; + ++this.freeCount; + return true; + } else { + index2 = index3; + } + } + } + return false; + }; + + dictionaryProto.clear = function () { + var index, len; + if (this.size <= 0) { return; } + for (index = 0, len = this.buckets.length; index < len; ++index) { + this.buckets[index] = -1; + } + for (index = 0; index < this.size; ++index) { + this.entries[index] = newEntry(); + } + this.freeList = -1; + this.size = 0; + }; + + dictionaryProto._findEntry = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647; + for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { + if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { + return index; + } + } + } + return -1; + }; + + dictionaryProto.count = function () { + return this.size - this.freeCount; + }; + + dictionaryProto.tryGetValue = function (key) { + var entry = this._findEntry(key); + return entry >= 0 ? + this.entries[entry].value : + undefined; + }; + + dictionaryProto.getValues = function () { + var index = 0, results = []; + if (this.entries) { + for (var index1 = 0; index1 < this.size; index1++) { + if (this.entries[index1].hashCode >= 0) { + results[index++] = this.entries[index1].value; + } + } + } + return results; + }; + + dictionaryProto.get = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { return this.entries[entry].value; } + throw new Error(noSuchkey); + }; + + dictionaryProto.set = function (key, value) { + this._insert(key, value, false); + }; + + dictionaryProto.containskey = function (key) { + return this._findEntry(key) >= 0; + }; + + return Dictionary; + }()); + + /** + * Correlates the elements of two sequences based on overlapping durations. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(); + var leftDone = false, rightDone = false; + var leftId = 0, rightId = 0; + var leftMap = new Dictionary(), rightMap = new Dictionary(); + + group.add(left.subscribe( + function (value) { + var id = leftId++; + var md = new SingleAssignmentDisposable(); + + leftMap.add(id, value); + group.add(md); + + var expire = function () { + leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); + + rightMap.getValues().forEach(function (v) { + var result; + try { + result = resultSelector(value, v); + } catch (exn) { + observer.onError(exn); + return; + } + + observer.onNext(result); + }); + }, + observer.onError.bind(observer), + function () { + leftDone = true; + (rightDone || leftMap.count() === 0) && observer.onCompleted(); + }) + ); + + group.add(right.subscribe( + function (value) { + var id = rightId++; + var md = new SingleAssignmentDisposable(); + + rightMap.add(id, value); + group.add(md); + + var expire = function () { + rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = rightDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); + + leftMap.getValues().forEach(function (v) { + var result; + try { + result = resultSelector(v, value); + } catch(exn) { + observer.onError(exn); + return; + } + + observer.onNext(result); + }); + }, + observer.onError.bind(observer), + function () { + rightDone = true; + (leftDone || rightMap.count() === 0) && observer.onCompleted(); + }) + ); + return group; + }); + }; + + /** + * Correlates the elements of two sequences based on overlapping durations, and groups the results. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(); + var r = new RefCountDisposable(group); + var leftMap = new Dictionary(), rightMap = new Dictionary(); + var leftId = 0, rightId = 0; + + function handleError(e) { return function (v) { v.onError(e); }; }; + + group.add(left.subscribe( + function (value) { + var s = new Subject(); + var id = leftId++; + leftMap.add(id, s); + + var result; + try { + result = resultSelector(value, addRef(s, r)); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + observer.onNext(result); + + rightMap.getValues().forEach(function (v) { s.onNext(v); }); + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + leftMap.remove(id) && s.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe( + noop, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + expire) + ); + }, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + observer.onCompleted.bind(observer)) + ); + + group.add(right.subscribe( + function (value) { + var id = rightId++; + rightMap.add(id, value); + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + rightMap.remove(id); + group.remove(md); + }; + + var duration; + try { + duration = rightDurationSelector(value); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + md.setDisposable(duration.take(1).subscribe( + noop, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + expire) + ); + + leftMap.getValues().forEach(function (v) { v.onNext(value); }); + }, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }) + ); + + return r; + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers. + * + * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { + return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows. + * + * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { + if (arguments.length === 1 && typeof arguments[0] !== 'function') { + return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector); + } + return typeof windowOpeningsOrClosingSelector === 'function' ? + observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : + observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); + }; + + function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { + return windowOpenings.groupJoin(this, windowClosingSelector, function () { + return observableEmpty(); + }, function (_, window) { + return window; + }); + } + + function observableWindowWithBounaries(windowBoundaries) { + var source = this; + return new AnonymousObservable(function (observer) { + var window = new Subject(), + d = new CompositeDisposable(), + r = new RefCountDisposable(d); + + observer.onNext(addRef(window, r)); + + d.add(source.subscribe(function (x) { + window.onNext(x); + }, function (err) { + window.onError(err); + observer.onError(err); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + + d.add(windowBoundaries.subscribe(function (w) { + window.onCompleted(); + window = new Subject(); + observer.onNext(addRef(window, r)); + }, function (err) { + window.onError(err); + observer.onError(err); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + + return r; + }); + } + + function observableWindowWithClosingSelector(windowClosingSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var createWindowClose, + m = new SerialDisposable(), + d = new CompositeDisposable(m), + r = new RefCountDisposable(d), + window = new Subject(); + observer.onNext(addRef(window, r)); + d.add(source.subscribe(function (x) { + window.onNext(x); + }, function (ex) { + window.onError(ex); + observer.onError(ex); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + createWindowClose = function () { + var m1, windowClose; + try { + windowClose = windowClosingSelector(); + } catch (exception) { + observer.onError(exception); + return; + } + m1 = new SingleAssignmentDisposable(); + m.setDisposable(m1); + m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) { + window.onError(ex); + observer.onError(ex); + }, function () { + window.onCompleted(); + window = new Subject(); + observer.onNext(addRef(window, r)); + createWindowClose(); + })); + }; + createWindowClose(); + return r; + }); + } + + /** + * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. + * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. + * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. + * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. + */ + observableProto.pairwise = function () { + var source = this; + return new AnonymousObservable(function (observer) { + var previous, hasPrevious = false; + return source.subscribe( + function (x) { + if (hasPrevious) { + observer.onNext([previous, x]); + } else { + hasPrevious = true; + } + previous = x; + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer)); + }); + }; + /** + * Returns two observables which partition the observations of the source by the given function. + * The first will trigger observations for those values for which the predicate returns true. + * The second will trigger observations for those values where the predicate returns false. + * The predicate is executed once for each subscribed observer. + * Both also propagate all error observations arising from the source and each completes + * when the source completes. + * @param {Function} predicate + * The function to determine which output Observable will trigger a particular observation. + * @returns {Array} + * An array of observables. The first triggers when the predicate returns true, + * and the second triggers when the predicate returns false. + */ + observableProto.partition = function(predicate, thisArg) { + var published = this.publish().refCount(); + return [ + published.filter(predicate, thisArg), + published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) + ]; + }; + + function enumerableWhile(condition, source) { + return new Enumerable(function () { + return new Enumerator(function () { + return condition() ? + { done: false, value: source } : + { done: true, value: undefined }; + }); + }); + } + + /** + * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. + * This operator allows for a fluent style of writing queries that use the same sequence multiple times. + * + * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + observableProto.letBind = observableProto['let'] = function (func) { + return func(this); + }; + + /** + * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers 0) { + isOwner = !isAcquired; + isAcquired = true; + } + if (isOwner) { + m.setDisposable(scheduler.scheduleRecursive(function (self) { + var work; + if (q.length > 0) { + work = q.shift(); + } else { + isAcquired = false; + return; + } + var m1 = new SingleAssignmentDisposable(); + d.add(m1); + m1.setDisposable(work.subscribe(function (x) { + observer.onNext(x); + var result = null; + try { + result = selector(x); + } catch (e) { + observer.onError(e); + } + q.push(result); + activeCount++; + ensureActive(); + }, observer.onError.bind(observer), function () { + d.remove(m1); + activeCount--; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + self(); + })); + } + }; + + q.push(source); + activeCount++; + ensureActive(); + return d; + }); + }; + + /** + * Runs all observable sequences in parallel and collect their last elements. + * + * @example + * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); + * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); + * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. + */ + Observable.forkJoin = function () { + var allSources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (subscriber) { + var count = allSources.length; + if (count === 0) { + subscriber.onCompleted(); + return disposableEmpty; + } + var group = new CompositeDisposable(), + finished = false, + hasResults = new Array(count), + hasCompleted = new Array(count), + results = new Array(count); + + for (var idx = 0; idx < count; idx++) { + (function (i) { + var source = allSources[i]; + isPromise(source) && (source = observableFromPromise(source)); + group.add( + source.subscribe( + function (value) { + if (!finished) { + hasResults[i] = true; + results[i] = value; + } + }, + function (e) { + finished = true; + subscriber.onError(e); + group.dispose(); + }, + function () { + if (!finished) { + if (!hasResults[i]) { + subscriber.onCompleted(); + return; + } + hasCompleted[i] = true; + for (var ix = 0; ix < count; ix++) { + if (!hasCompleted[ix]) { return; } + } + finished = true; + subscriber.onNext(results); + subscriber.onCompleted(); + } + })); + })(idx); + } + + return group; + }); + }; + + /** + * Runs two observable sequences in parallel and combines their last elemenets. + * + * @param {Observable} second Second observable sequence. + * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. + * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. + */ + observableProto.forkJoin = function (second, resultSelector) { + var first = this; + + return new AnonymousObservable(function (observer) { + var leftStopped = false, rightStopped = false, + hasLeft = false, hasRight = false, + lastLeft, lastRight, + leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); + + isPromise(second) && (second = observableFromPromise(second)); + + leftSubscription.setDisposable( + first.subscribe(function (left) { + hasLeft = true; + lastLeft = left; + }, function (err) { + rightSubscription.dispose(); + observer.onError(err); + }, function () { + leftStopped = true; + if (rightStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + rightSubscription.setDisposable( + second.subscribe(function (right) { + hasRight = true; + lastRight = right; + }, function (err) { + leftSubscription.dispose(); + observer.onError(err); + }, function () { + rightStopped = true; + if (leftStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + return new CompositeDisposable(leftSubscription, rightSubscription); + }); + }; + + /** + * Comonadic bind operator. + * @param {Function} selector A transform function to apply to each element. + * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. + * @returns {Observable} An observable sequence which results from the comonadic bind operation. + */ + observableProto.manySelect = function (selector, scheduler) { + isScheduler(scheduler) || (scheduler = immediateScheduler); + var source = this; + return observableDefer(function () { + var chain; + + return source + .map(function (x) { + var curr = new ChainObservable(x); + + chain && chain.onNext(x); + chain = curr; + + return curr; + }) + .tap( + noop, + function (e) { chain && chain.onError(e); }, + function () { chain && chain.onCompleted(); } + ) + .observeOn(scheduler) + .map(selector); + }); + }; + + var ChainObservable = (function (__super__) { + + function subscribe (observer) { + var self = this, g = new CompositeDisposable(); + g.add(currentThreadScheduler.schedule(function () { + observer.onNext(self.head); + g.add(self.tail.mergeObservable().subscribe(observer)); + })); + + return g; + } + + inherits(ChainObservable, __super__); + + function ChainObservable(head) { + __super__.call(this, subscribe); + this.head = head; + this.tail = new AsyncSubject(); + } + + addProperties(ChainObservable.prototype, Observer, { + onCompleted: function () { + this.onNext(Observable.empty()); + }, + onError: function (e) { + this.onNext(Observable.throwException(e)); + }, + onNext: function (v) { + this.tail.onNext(v); + this.tail.onCompleted(); + } + }); + + return ChainObservable; + + }(Observable)); + + /** @private */ + var Map = (function () { + + /** + * @constructor + * @private + */ + function Map() { + this.keys = []; + this.values = []; + } + + /** + * @private + * @memberOf Map# + */ + Map.prototype['delete'] = function (key) { + var i = this.keys.indexOf(key); + if (i !== -1) { + this.keys.splice(i, 1); + this.values.splice(i, 1); + } + return i !== -1; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.get = function (key, fallback) { + var i = this.keys.indexOf(key); + return i !== -1 ? this.values[i] : fallback; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.set = function (key, value) { + var i = this.keys.indexOf(key); + if (i !== -1) { + this.values[i] = value; + } + this.values[this.keys.push(key) - 1] = value; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.size = function () { return this.keys.length; }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.has = function (key) { + return this.keys.indexOf(key) !== -1; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.getKeys = function () { return this.keys.slice(0); }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.getValues = function () { return this.values.slice(0); }; + + return Map; + }()); + + /** + * @constructor + * Represents a join pattern over observable sequences. + */ + function Pattern(patterns) { + this.patterns = patterns; + } + + /** + * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. + * + * @param other Observable sequence to match in addition to the current pattern. + * @return Pattern object that matches when all observable sequences in the pattern have an available value. + */ + Pattern.prototype.and = function (other) { + var patterns = this.patterns.slice(0); + patterns.push(other); + return new Pattern(patterns); + }; + + /** + * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. + * + * @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. + * @return Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + Pattern.prototype.thenDo = function (selector) { + return new Plan(this, selector); + }; + + function Plan(expression, selector) { + this.expression = expression; + this.selector = selector; + } + + Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { + var self = this; + var joinObservers = []; + for (var i = 0, len = this.expression.patterns.length; i < len; i++) { + joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); + } + var activePlan = new ActivePlan(joinObservers, function () { + var result; + try { + result = self.selector.apply(self, arguments); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, function () { + for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { + joinObservers[j].removeActivePlan(activePlan); + } + deactivate(activePlan); + }); + for (i = 0, len = joinObservers.length; i < len; i++) { + joinObservers[i].addActivePlan(activePlan); + } + return activePlan; + }; + + function planCreateObserver(externalSubscriptions, observable, onError) { + var entry = externalSubscriptions.get(observable); + if (!entry) { + var observer = new JoinObserver(observable, onError); + externalSubscriptions.set(observable, observer); + return observer; + } + return entry; + } + + // Active Plan + function ActivePlan(joinObserverArray, onNext, onCompleted) { + var i, joinObserver; + this.joinObserverArray = joinObserverArray; + this.onNext = onNext; + this.onCompleted = onCompleted; + this.joinObservers = new Map(); + for (i = 0; i < this.joinObserverArray.length; i++) { + joinObserver = this.joinObserverArray[i]; + this.joinObservers.set(joinObserver, joinObserver); + } + } + + ActivePlan.prototype.dequeue = function () { + var values = this.joinObservers.getValues(); + for (var i = 0, len = values.length; i < len; i++) { + values[i].queue.shift(); + } + }; + ActivePlan.prototype.match = function () { + var firstValues, i, len, isCompleted, values, hasValues = true; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + if (this.joinObserverArray[i].queue.length === 0) { + hasValues = false; + break; + } + } + if (hasValues) { + firstValues = []; + isCompleted = false; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + firstValues.push(this.joinObserverArray[i].queue[0]); + if (this.joinObserverArray[i].queue[0].kind === 'C') { + isCompleted = true; + } + } + if (isCompleted) { + this.onCompleted(); + } else { + this.dequeue(); + values = []; + for (i = 0; i < firstValues.length; i++) { + values.push(firstValues[i].value); + } + this.onNext.apply(this, values); + } + } + }; + + /** @private */ + var JoinObserver = (function (_super) { + + inherits(JoinObserver, _super); + + /** + * @constructor + * @private + */ + function JoinObserver(source, onError) { + _super.call(this); + this.source = source; + this.onError = onError; + this.queue = []; + this.activePlans = []; + this.subscription = new SingleAssignmentDisposable(); + this.isDisposed = false; + } + + var JoinObserverPrototype = JoinObserver.prototype; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.next = function (notification) { + if (!this.isDisposed) { + if (notification.kind === 'E') { + this.onError(notification.exception); + return; + } + this.queue.push(notification); + var activePlans = this.activePlans.slice(0); + for (var i = 0, len = activePlans.length; i < len; i++) { + activePlans[i].match(); + } + } + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.error = noop; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.completed = noop; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.addActivePlan = function (activePlan) { + this.activePlans.push(activePlan); + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.subscribe = function () { + this.subscription.setDisposable(this.source.materialize().subscribe(this)); + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.removeActivePlan = function (activePlan) { + var idx = this.activePlans.indexOf(activePlan); + this.activePlans.splice(idx, 1); + if (this.activePlans.length === 0) { + this.dispose(); + } + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + if (!this.isDisposed) { + this.isDisposed = true; + this.subscription.dispose(); + } + }; + + return JoinObserver; + } (AbstractObserver)); + + /** + * Creates a pattern that matches when both observable sequences have an available value. + * + * @param right Observable sequence to match with the current sequence. + * @return {Pattern} Pattern object that matches when both observable sequences have an available value. + */ + observableProto.and = function (right) { + return new Pattern([this, right]); + }; + + /** + * Matches when the observable sequence has an available value and projects the value. + * + * @param selector Selector that will be invoked for values in the source sequence. + * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + observableProto.thenDo = function (selector) { + return new Pattern([this]).thenDo(selector); + }; + + /** + * Joins together the results from several patterns. + * + * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. + * @returns {Observable} Observable sequence with the results form matching several patterns. + */ + Observable.when = function () { + var plans = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var activePlans = [], + externalSubscriptions = new Map(), + group, + i, len, + joinObserver, + joinValues, + outObserver; + outObserver = observerCreate(observer.onNext.bind(observer), function (exception) { + var values = externalSubscriptions.getValues(); + for (var j = 0, jlen = values.length; j < jlen; j++) { + values[j].onError(exception); + } + observer.onError(exception); + }, observer.onCompleted.bind(observer)); + try { + for (i = 0, len = plans.length; i < len; i++) { + activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { + var idx = activePlans.indexOf(activePlan); + activePlans.splice(idx, 1); + if (activePlans.length === 0) { + outObserver.onCompleted(); + } + })); + } + } catch (e) { + observableThrow(e).subscribe(observer); + } + group = new CompositeDisposable(); + joinValues = externalSubscriptions.getValues(); + for (i = 0, len = joinValues.length; i < len; i++) { + joinObserver = joinValues[i]; + joinObserver.subscribe(); + group.add(joinObserver); + } + return group; + }); + }; + + function observableTimerDate(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithAbsolute(dueTime, function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerDateAndPeriod(dueTime, period, scheduler) { + return new AnonymousObservable(function (observer) { + var count = 0, d = dueTime, p = normalizeTime(period); + return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { + if (p > 0) { + var now = scheduler.now(); + d = d + p; + d <= now && (d = now + p); + } + observer.onNext(count++); + self(d); + }); + }); + } + + function observableTimerTimeSpan(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { + return dueTime === period ? + new AnonymousObservable(function (observer) { + return scheduler.schedulePeriodicWithState(0, period, function (count) { + observer.onNext(count); + return count + 1; + }); + }) : + observableDefer(function () { + return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); + }); + } + + /** + * Returns an observable sequence that produces a value after each period. + * + * @example + * 1 - res = Rx.Observable.interval(1000); + * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); + * + * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. + * @returns {Observable} An observable sequence that produces a value after each period. + */ + var observableinterval = Observable.interval = function (period, scheduler) { + return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); + }; + + /** + * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. + * + * @example + * 1 - res = Rx.Observable.timer(new Date()); + * 2 - res = Rx.Observable.timer(new Date(), 1000); + * 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout); + * + * 5 - res = Rx.Observable.timer(5000); + * 6 - res = Rx.Observable.timer(5000, 1000); + * 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); + * 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. + * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. + */ + var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { + var period; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { + period = periodOrScheduler; + } else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') { + scheduler = periodOrScheduler; + } + if (dueTime instanceof Date && period === undefined) { + return observableTimerDate(dueTime.getTime(), scheduler); + } + if (dueTime instanceof Date && period !== undefined) { + period = periodOrScheduler; + return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); + } + return period === undefined ? + observableTimerTimeSpan(dueTime, scheduler) : + observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); + }; + + function observableDelayTimeSpan(source, dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + var active = false, + cancelable = new SerialDisposable(), + exception = null, + q = [], + running = false, + subscription; + subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { + var d, shouldRun; + if (notification.value.kind === 'E') { + q = []; + q.push(notification); + exception = notification.value.exception; + shouldRun = !running; + } else { + q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); + shouldRun = !active; + active = true; + } + if (shouldRun) { + if (exception !== null) { + observer.onError(exception); + } else { + d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { + var e, recurseDueTime, result, shouldRecurse; + if (exception !== null) { + return; + } + running = true; + do { + result = null; + if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { + result = q.shift().value; + } + if (result !== null) { + result.accept(observer); + } + } while (result !== null); + shouldRecurse = false; + recurseDueTime = 0; + if (q.length > 0) { + shouldRecurse = true; + recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); + } else { + active = false; + } + e = exception; + running = false; + if (e !== null) { + observer.onError(e); + } else if (shouldRecurse) { + self(recurseDueTime); + } + })); + } + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + } + + function observableDelayDate(source, dueTime, scheduler) { + return observableDefer(function () { + return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); + }); + } + + /** + * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. + * + * @example + * 1 - res = Rx.Observable.delay(new Date()); + * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); + * + * 3 - res = Rx.Observable.delay(5000); + * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); + * @memberOf Observable# + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. + * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delay = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return dueTime instanceof Date ? + observableDelayDate(this, dueTime.getTime(), scheduler) : + observableDelayTimeSpan(this, dueTime, scheduler); + }; + + /** + * Ignores values from an observable sequence which are followed by another value before dueTime. + * + * @example + * 1 - res = source.throttle(5000); // 5 seconds + * 2 - res = source.throttle(5000, scheduler); + * + * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttle = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. + * + * @example + * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second + * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds + * + * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + var source = this, timeShift; + + timeShiftOrScheduler == null && (timeShift = timeSpan); + isScheduler(scheduler) || (scheduler = timeoutScheduler); + if (typeof timeShiftOrScheduler === 'number') { + timeShift = timeShiftOrScheduler; + } else if (typeof timeShiftOrScheduler === 'object') { + timeShift = timeSpan; + scheduler = timeShiftOrScheduler; + } + return new AnonymousObservable(function (observer) { + var groupDisposable, + nextShift = timeShift, + nextSpan = timeSpan, + q = [], + refCountDisposable, + timerD = new SerialDisposable(), + totalTime = 0; + groupDisposable = new CompositeDisposable(timerD), + refCountDisposable = new RefCountDisposable(groupDisposable); + + + q.push(new Subject()); + observer.onNext(addRef(q[0], refCountDisposable)); + createTimer(); + groupDisposable.add(source.subscribe(function (x) { + var i, len; + for (i = 0, len = q.length; i < len; i++) { + q[i].onNext(x); + } + }, function (e) { + var i, len; + for (i = 0, len = q.length; i < len; i++) { + q[i].onError(e); + } + observer.onError(e); + }, function () { + var i, len; + for (i = 0, len = q.length; i < len; i++) { + q[i].onCompleted(); + } + observer.onCompleted(); + })); + + return refCountDisposable; + + function createTimer () { + var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; + timerD.setDisposable(m); + + if (nextSpan === nextShift) { + isSpan = true; + isShift = true; + } else if (nextSpan < nextShift) { + isSpan = true; + } else { + isShift = true; + } + + var newTotalTime = isSpan ? nextSpan : nextShift, + ts = newTotalTime - totalTime; + totalTime = newTotalTime; + isSpan && (nextSpan += timeShift); + isShift && (nextShift += timeShift); + + m.setDisposable(scheduler.scheduleWithRelative(ts, function () { + var s; + if (isShift) { + s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + } + if (isSpan) { + s = q.shift(); + s.onCompleted(); + } + createTimer(); + })); + } + }); + }; + + /** + * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. + * @example + * 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items + * 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items + * + * @memberOf Observable# + * @param {Number} timeSpan Maximum time length of a window. + * @param {Number} count Maximum element count of a window. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var createTimer, + groupDisposable, + n = 0, + refCountDisposable, + s = new Subject() + timerD = new SerialDisposable(), + windowId = 0; + groupDisposable = new CompositeDisposable(timerD); + refCountDisposable = new RefCountDisposable(groupDisposable); + + observer.onNext(addRef(s, refCountDisposable)); + createTimer(0); + groupDisposable.add(source.subscribe(function (x) { + var newId = 0, newWindow = false; + s.onNext(x); + n++; + if (n === count) { + newWindow = true; + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + } + newWindow && createTimer(newId); + }, function (e) { + s.onError(e); + observer.onError(e); + }, function () { + s.onCompleted(); + observer.onCompleted(); + })); + + return refCountDisposable; + + function createTimer(id) { + var m = new SingleAssignmentDisposable(); + timerD.setDisposable(m); + m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { + var newId; + if (id !== windowId) { return; } + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + createTimer(newId); + })); + } + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. + * + * @example + * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second + * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds + * + * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. + * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); + }; + + /** + * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. + * + * @example + * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array + * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array + * + * @param {Number} timeSpan Maximum time length of a buffer. + * @param {Number} count Maximum element count of a buffer. + * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { + return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { + return x.toArray(); + }); + }; + + /** + * Records the time interval between consecutive values in an observable sequence. + * + * @example + * 1 - res = source.timeInterval(); + * 2 - res = source.timeInterval(Rx.Scheduler.timeout); + * + * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with time interval information on values. + */ + observableProto.timeInterval = function (scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return observableDefer(function () { + var last = scheduler.now(); + return source.map(function (x) { + var now = scheduler.now(), span = now - last; + last = now; + return { value: x, interval: span }; + }); + }); + }; + + /** + * Records the timestamp for each value in an observable sequence. + * + * @example + * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } + * 2 - res = source.timestamp(Rx.Scheduler.timeout); + * + * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with timestamp information on values. + */ + observableProto.timestamp = function (scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return this.map(function (x) { + return { value: x, timestamp: scheduler.now() }; + }); + }; + + function sampleObservable(source, sampler) { + + return new AnonymousObservable(function (observer) { + var atEnd, value, hasValue; + + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + observer.onNext(value); + } + atEnd && observer.onCompleted(); + } + + return new CompositeDisposable( + source.subscribe(function (newValue) { + hasValue = true; + value = newValue; + }, observer.onError.bind(observer), function () { + atEnd = true; + }), + sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) + ); + }); + } + + /** + * Samples the observable sequence at each interval. + * + * @example + * 1 - res = source.sample(sampleObservable); // Sampler tick sequence + * 2 - res = source.sample(5000); // 5 seconds + * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. + * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Sampled observable sequence. + */ + observableProto.sample = function (intervalOrSampler, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return typeof intervalOrSampler === 'number' ? + sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : + sampleObservable(this, intervalOrSampler); + }; + + /** + * Returns the source observable sequence or the other observable sequence if dueTime elapses. + * + * @example + * 1 - res = source.timeout(new Date()); // As a date + * 2 - res = source.timeout(5000); // 5 seconds + * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable + * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable + * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable + * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. + * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. + * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeout = function (dueTime, other, scheduler) { + other || (other = observableThrow(new Error('Timeout'))); + isScheduler(scheduler) || (scheduler = timeoutScheduler); + + var source = this, schedulerMethod = dueTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + + return new AnonymousObservable(function (observer) { + var id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + + subscription.setDisposable(original); + + var createTimer = function () { + var myId = id; + timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { + if (id === myId) { + isPromise(other) && (other = observableFromPromise(other)); + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + createTimer(); + + original.setDisposable(source.subscribe(function (x) { + if (!switched) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + if (!switched) { + id++; + observer.onError(e); + } + }, function () { + if (!switched) { + id++; + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithAbsoluteTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return new Date(); } + * }); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { + hasResult && observer.onNext(result); + + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithRelativeTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return 500; } + * ); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithRelative(0, function (self) { + hasResult && observer.onNext(result); + + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Time shifts the observable sequence by delaying the subscription. + * + * @example + * 1 - res = source.delaySubscription(5000); // 5s + * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Number} dueTime Absolute or relative time to perform the subscription at. + * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delaySubscription = function (dueTime, scheduler) { + return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty); + }; + + /** + * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only + * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector + * + * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. + * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { + var source = this, subDelay, selector; + if (typeof subscriptionDelay === 'function') { + selector = subscriptionDelay; + } else { + subDelay = subscriptionDelay; + selector = delayDurationSelector; + } + return new AnonymousObservable(function (observer) { + var delays = new CompositeDisposable(), atEnd = false, done = function () { + if (atEnd && delays.length === 0) { + observer.onCompleted(); + } + }, subscription = new SerialDisposable(), start = function () { + subscription.setDisposable(source.subscribe(function (x) { + var delay; + try { + delay = selector(x); + } catch (error) { + observer.onError(error); + return; + } + var d = new SingleAssignmentDisposable(); + delays.add(d); + d.setDisposable(delay.subscribe(function () { + observer.onNext(x); + delays.remove(d); + done(); + }, observer.onError.bind(observer), function () { + observer.onNext(x); + delays.remove(d); + done(); + })); + }, observer.onError.bind(observer), function () { + atEnd = true; + subscription.dispose(); + done(); + })); + }; + + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(function () { + start(); + }, observer.onError.bind(observer), function () { start(); })); + } + + return new CompositeDisposable(subscription, delays); + }); + }; + + /** + * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. + * + * @example + * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); + * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); + * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); + * + * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). + * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. + * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { + if (arguments.length === 1) { + timeoutdurationSelector = firstTimeout; + var firstTimeout = observableNever(); + } + other || (other = observableThrow(new Error('Timeout'))); + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); + + subscription.setDisposable(original); + + var id = 0, switched = false, setTimer = function (timeout) { + var myId = id, timerWins = function () { + return id === myId; + }; + var d = new SingleAssignmentDisposable(); + timer.setDisposable(d); + d.setDisposable(timeout.subscribe(function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + d.dispose(); + }, function (e) { + if (timerWins()) { + observer.onError(e); + } + }, function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + setTimer(firstTimeout); + var observerWins = function () { + var res = !switched; + if (res) { + id++; + } + return res; + }; + + original.setDisposable(source.subscribe(function (x) { + if (observerWins()) { + observer.onNext(x); + var timeout; + try { + timeout = timeoutdurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + setTimer(timeout); + } + }, function (e) { + if (observerWins()) { + observer.onError(e); + } + }, function () { + if (observerWins()) { + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); + * + * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttleWithSelector = function (throttleDurationSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { + var throttle; + try { + throttle = throttleDurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + hasValue = true; + value = x; + id++; + var currentid = id, d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(throttle.subscribe(function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + }, observer.onError.bind(observer), function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + })); + }, function (e) { + cancelable.dispose(); + observer.onError(e); + hasValue = false; + id++; + }, function () { + cancelable.dispose(); + if (hasValue) { + observer.onNext(value); + } + observer.onCompleted(); + hasValue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * 1 - res = source.skipLastWithTime(5000); + * 2 - res = source.skipLastWithTime(5000, scheduler); + * + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for skipping elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. + */ + observableProto.skipLastWithTime = function (duration, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. + * + * @example + * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var q = []; + + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { + observer.onNext(next.value); + } + } + + observer.onCompleted(); + }); + }); + }; + + /** + * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastBufferWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var q = []; + + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(), res = []; + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { + res.push(next.value); + } + } + + observer.onNext(res); + observer.onCompleted(); + }); + }); + }; + + /** + * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + observableProto.takeWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), source.subscribe(observer)); + }); + }; + + /** + * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.skipWithTime(5000, [optional scheduler]); + * + * @description + * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. + * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded + * may not execute immediately, despite the zero due time. + * + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. + * @param {Number} duration Duration for skipping elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + observableProto.skipWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false; + return new CompositeDisposable( + scheduler.scheduleWithRelative(duration, function () { open = true; }), + source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); + }); + }; + + /** + * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. + * + * @examples + * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); + * 2 - res = source.skipUntilWithTime(5000, [optional scheduler]); + * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. + * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped until the specified start time. + */ + observableProto.skipUntilWithTime = function (startTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = startTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (observer) { + var open = false; + + return new CompositeDisposable( + scheduler[schedulerMethod](startTime, function () { open = true; }), + source.subscribe( + function (x) { open && observer.onNext(x); }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer))); + }); + }; + + /** + * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); + * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); + * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. + * @param {Scheduler} scheduler Scheduler to run the timer on. + * @returns {Observable} An observable sequence with the elements taken until the specified end time. + */ + observableProto.takeUntilWithTime = function (endTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = endTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { + observer.onCompleted(); + }), source.subscribe(observer)); + }); + }; + + /* + * Performs a exclusive waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @returns {Observable} A exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusive = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasCurrent = false, + isStopped = false, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + if (!hasCurrent) { + hasCurrent = true; + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + var innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + innerSubscription.setDisposable(innerSource.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (!hasCurrent && g.length === 1) { + observer.onCompleted(); + } + })); + + return g; + }); + }; + /* + * Performs a exclusive map waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @param {Function} selector Selector to invoke for every item in the current subscription. + * @param {Any} [thisArg] An optional context to invoke with the selector parameter. + * @returns {Observable} An exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusiveMap = function (selector, thisArg) { + var sources = this; + return new AnonymousObservable(function (observer) { + var index = 0, + hasCurrent = false, + isStopped = true, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + + if (!hasCurrent) { + hasCurrent = true; + + innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + innerSubscription.setDisposable(innerSource.subscribe( + function (x) { + var result; + try { + result = selector.call(thisArg, x, index++, innerSource); + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(result); + }, + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (g.length === 1 && !hasCurrent) { + observer.onCompleted(); + } + })); + return g; + }); + }; + /** Provides a set of extension methods for virtual time scheduling. */ + Rx.VirtualTimeScheduler = (function (__super__) { + + function notImplemented() { + throw new Error('Not implemented'); + } + + function localNow() { + return this.toDateTimeOffset(this.clock); + } + + function scheduleNow(state, action) { + return this.scheduleAbsoluteWithState(state, this.clock, action); + } + + function scheduleRelative(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + inherits(VirtualTimeScheduler, __super__); + + /** + * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. + * + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function VirtualTimeScheduler(initialClock, comparer) { + this.clock = initialClock; + this.comparer = comparer; + this.isEnabled = false; + this.queue = new PriorityQueue(1024); + __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + VirtualTimeSchedulerPrototype.add = notImplemented; + + /** + * Converts an absolute time to a number + * @param {Any} The absolute time. + * @returns {Number} The absolute time in ms + */ + VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + VirtualTimeSchedulerPrototype.toRelative = notImplemented; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { + var s = new SchedulePeriodicRecursive(this, state, period, action); + return s.start(); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { + var runAt = this.add(this.clock, dueTime); + return this.scheduleAbsoluteWithState(state, runAt, action); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { + return this.scheduleRelativeWithState(action, dueTime, invokeAction); + }; + + /** + * Starts the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.start = function () { + if (!this.isEnabled) { + this.isEnabled = true; + do { + var next = this.getNext(); + if (next !== null) { + this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); + next.invoke(); + } else { + this.isEnabled = false; + } + } while (this.isEnabled); + } + }; + + /** + * Stops the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.stop = function () { + this.isEnabled = false; + }; + + /** + * Advances the scheduler's clock to the specified time, running all work till that point. + * @param {Number} time Absolute time to advance the scheduler's clock to. + */ + VirtualTimeSchedulerPrototype.advanceTo = function (time) { + var dueToClock = this.comparer(this.clock, time); + if (this.comparer(this.clock, time) > 0) { + throw new Error(argumentOutOfRange); + } + if (dueToClock === 0) { + return; + } + if (!this.isEnabled) { + this.isEnabled = true; + do { + var next = this.getNext(); + if (next !== null && this.comparer(next.dueTime, time) <= 0) { + this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); + next.invoke(); + } else { + this.isEnabled = false; + } + } while (this.isEnabled); + this.clock = time; + } + }; + + /** + * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.advanceBy = function (time) { + var dt = this.add(this.clock, time), + dueToClock = this.comparer(this.clock, dt); + if (dueToClock > 0) { throw new Error(argumentOutOfRange); } + if (dueToClock === 0) { return; } + + this.advanceTo(dt); + }; + + /** + * Advances the scheduler's clock by the specified relative time. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.sleep = function (time) { + var dt = this.add(this.clock, time); + if (this.comparer(this.clock, dt) >= 0) { throw new Error(argumentOutOfRange); } + + this.clock = dt; + }; + + /** + * Gets the next scheduled item to be executed. + * @returns {ScheduledItem} The next scheduled item. + */ + VirtualTimeSchedulerPrototype.getNext = function () { + while (this.queue.length > 0) { + var next = this.queue.peek(); + if (next.isCancelled()) { + this.queue.dequeue(); + } else { + return next; + } + } + return null; + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Scheduler} scheduler Scheduler to execute the action on. + * @param {Number} dueTime Absolute time at which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { + return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Absolute time at which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { + var self = this; + + function run(scheduler, state1) { + self.queue.remove(si); + return action(scheduler, state1); + } + + var si = new ScheduledItem(this, state, run, dueTime, this.comparer); + this.queue.enqueue(si); + + return si.disposable; + }; + + return VirtualTimeScheduler; + }(Scheduler)); + + /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ + Rx.HistoricalScheduler = (function (__super__) { + inherits(HistoricalScheduler, __super__); + + /** + * Creates a new historical scheduler with the specified initial clock value. + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function HistoricalScheduler(initialClock, comparer) { + var clock = initialClock == null ? 0 : initialClock; + var cmp = comparer || defaultSubComparer; + __super__.call(this, clock, cmp); + } + + var HistoricalSchedulerProto = HistoricalScheduler.prototype; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + HistoricalSchedulerProto.add = function (absolute, relative) { + return absolute + relative; + }; + + HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { + return new Date(absolute).getTime(); + }; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * @memberOf HistoricalScheduler + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + HistoricalSchedulerProto.toRelative = function (timeSpan) { + return timeSpan; + }; + + return HistoricalScheduler; + }(Rx.VirtualTimeScheduler)); + var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { + inherits(AnonymousObservable, __super__); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } + + return typeof subscriber === 'function' ? + disposableCreate(subscriber) : + disposableEmpty; + } + + function AnonymousObservable(subscribe) { + if (!(this instanceof AnonymousObservable)) { + return new AnonymousObservable(subscribe); + } + + function s(observer) { + var setDisposable = function () { + try { + autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); + } catch (e) { + if (!autoDetachObserver.fail(e)) { + throw e; + } + } + }; + + var autoDetachObserver = new AutoDetachObserver(observer); + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.schedule(setDisposable); + } else { + setDisposable(); + } + + return autoDetachObserver; + } + + __super__.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + /** @private */ + var AutoDetachObserver = (function (_super) { + inherits(AutoDetachObserver, _super); + + function AutoDetachObserver(observer) { + _super.call(this); + this.observer = observer; + this.m = new SingleAssignmentDisposable(); + } + + var AutoDetachObserverPrototype = AutoDetachObserver.prototype; + + AutoDetachObserverPrototype.next = function (value) { + var noError = false; + try { + this.observer.onNext(value); + noError = true; + } catch (e) { + throw e; + } finally { + if (!noError) { + this.dispose(); + } + } + }; + + AutoDetachObserverPrototype.error = function (exn) { + try { + this.observer.onError(exn); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.completed = function () { + try { + this.observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; + /* @private */ + AutoDetachObserverPrototype.disposable = function (value) { + return arguments.length ? this.getDisposable() : setDisposable(value); + }; + + AutoDetachObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + /** @private */ + var GroupedObservable = (function (_super) { + inherits(GroupedObservable, _super); + + function subscribe(observer) { + return this.underlyingObservable.subscribe(observer); + } + + /** + * @constructor + * @private + */ + function GroupedObservable(key, underlyingObservable, mergedDisposable) { + _super.call(this, subscribe); + this.key = key; + this.underlyingObservable = !mergedDisposable ? + underlyingObservable : + new AnonymousObservable(function (observer) { + return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); + }); + } + + return GroupedObservable; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.exception) { + observer.onError(this.exception); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, _super); + + /** + * Creates a subject. + * @constructor + */ + function Subject() { + _super.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + } + + addProperties(Subject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (__super__) { + + function subscribe(observer) { + checkDisposed.call(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + var ex = this.exception, + hv = this.hasValue, + v = this.value; + + if (ex) { + observer.onError(ex); + } else if (hv) { + observer.onNext(v); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, __super__); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + __super__.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.value = null; + this.hasValue = false; + this.observers = []; + this.exception = null; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed.call(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var o, i, len; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var os = this.observers.slice(0), + v = this.value, + hv = this.hasValue; + + if (hv) { + for (i = 0, len = os.length; i < len; i++) { + o = os[i]; + o.onNext(v); + o.onCompleted(); + } + } else { + for (i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the error. + * @param {Mixed} error The Error to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed.call(this); + if (this.isStopped) { return; } + this.value = value; + this.hasValue = true; + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { + inherits(AnonymousSubject, __super__); + + function AnonymousSubject(observer, observable) { + this.observer = observer; + this.observable = observable; + __super__.call(this, this.observable.subscribe.bind(this.observable)); + } + + addProperties(AnonymousSubject.prototype, Observer, { + onCompleted: function () { + this.observer.onCompleted(); + }, + onError: function (exception) { + this.observer.onError(exception); + }, + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } +}.call(this)); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.all.min.js b/ajax/libs/rxjs/2.3.9/rx.all.min.js new file mode 100644 index 000000000..4102f45ef --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.all.min.js @@ -0,0 +1,3 @@ +(function(a){function b(){if(this.isDisposed)throw new Error(qb)}function c(a){var b=typeof a;return a&&("function"==b||"object"==b)||!1}function d(a){var b=[];if(!c(a))return b;Nb.nonEnumArgs&&a.length&&h(a)&&(a=Pb.call(a));var d=Nb.enumPrototypes&&"function"==typeof a,e=Nb.enumErrorProps&&(a===Hb||a instanceof Error);for(var f in a)d&&"prototype"==f||e&&("message"==f||"name"==f)||b.push(f);if(Nb.nonEnumShadows&&a!==Ib){var g=a.constructor,i=-1,j=Lb.length;if(a===(g&&g.prototype))var k=a===stringProto?Db:a===Hb?yb:Eb.call(a),l=Mb[k];for(;++i-1:void 0});return c.pop(),d.pop(),result}function k(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:Pb.call(a)}function l(a,b){for(var c=new Array(a),d=0;a>d;d++)c[d]=b();return c}function m(a,b){this.scheduler=a,this.disposable=b,this.isDisposed=!1}function n(a){return"number"==typeof a&&_.isFinite(a)}function o(b){return b[rb]!==a}function p(a){var b=+a;return 0===b?b:isNaN(b)?b:0>b?-1:1}function q(a){var b=+a.length;return isNaN(b)?0:0!==b&&n(b)?(b=p(b)*Math.floor(Math.abs(b)),0>=b?0:b>Fc?Fc:b):b}function r(a){return"[object Function]"===Object.prototype.toString.call(a)&&"function"==typeof a}function s(a,b){return new hd(function(c){var d=new _b,e=new SerialDisposable;return e.setDisposable(d),d.setDisposable(a.subscribe(c.onNext.bind(c),function(a){var d,f;try{f=b(a)}catch(g){return void c.onError(g)}mb(f)&&(f=Cc(f)),d=new _b,e.setDisposable(d),d.setDisposable(f.subscribe(c))},c.onCompleted.bind(c))),e})}function t(a,b){var c=this;return new hd(function(d){var e=0,f=a.length;return c.subscribe(function(c){if(f>e){var g,h=a[e++];try{g=b(c,h)}catch(i){return void d.onError(i)}d.onNext(g)}else d.onCompleted()},d.onError.bind(d),d.onCompleted.bind(d))})}function u(a,b,c){return a.map(function(a,d){var e=b.call(c,a,d);return mb(e)?Cc(e):e}).concatAll()}function v(a,b,c){for(var d=0,e=a.length;e>d;d++)if(c(a[d],b))return d;return-1}function w(a){this.comparer=a,this.set=[]}function x(a,b,c){return a.map(function(a,d){var e=b.call(c,a,d);return mb(e)?Cc(e):e}).mergeObservable()}function y(a,b,c){return new hd(function(d){var e=!1,f=null,g=[];return a.subscribe(function(a){var h,i;try{i=b(a)}catch(j){return void d.onError(j)}if(h=0,e)try{h=c(i,f)}catch(k){return void d.onError(k)}else e=!0,f=i;h>0&&(f=i,g=[]),h>=0&&g.push(a)},d.onError.bind(d),function(){d.onNext(g),d.onCompleted()})})}function z(a){if(0===a.length)throw new Error(ob);return a[0]}function A(a,b,c){return new hd(function(d){var e=0,f=b.length;return a.subscribe(function(a){var g=!1;try{f>e&&(g=c(a,b[e++]))}catch(h){return void d.onError(h)}g||(d.onNext(!1),d.onCompleted())},d.onError.bind(d),function(){d.onNext(e===f),d.onCompleted()})})}function B(a,b,c,d){if(0>b)throw new Error(pb);return new hd(function(e){var f=b;return a.subscribe(function(a){0===f&&(e.onNext(a),e.onCompleted()),f--},e.onError.bind(e),function(){c?(e.onNext(d),e.onCompleted()):e.onError(new Error(pb))})})}function C(a,b,c){return new hd(function(d){var e=c,f=!1;return a.subscribe(function(a){f?d.onError(new Error("Sequence contains more than one element")):(e=a,f=!0)},d.onError.bind(d),function(){f||b?(d.onNext(e),d.onCompleted()):d.onError(new Error(ob))})})}function D(a,b,c){return new hd(function(d){return a.subscribe(function(a){d.onNext(a),d.onCompleted()},d.onError.bind(d),function(){b?(d.onNext(c),d.onCompleted()):d.onError(new Error(ob))})})}function E(a,b,c){return new hd(function(d){var e=c,f=!1;return a.subscribe(function(a){e=a,f=!0},d.onError.bind(d),function(){f||b?(d.onNext(e),d.onCompleted()):d.onError(new Error(ob))})})}function F(b,c,d,e){return new hd(function(f){var g=0;return b.subscribe(function(a){var h;try{h=c.call(d,a,g,b)}catch(i){return void f.onError(i)}h?(f.onNext(e?g:a),f.onCompleted()):g++},f.onError.bind(f),function(){f.onNext(e?-1:a),f.onCompleted()})})}function G(a,b){return new hd(function(c){var d=new b;return a.subscribe(d.add.bind(d),c.onError.bind(c),function(){c.onNext(d),c.onCompleted()})})}function H(a,b,c,d){return new hd(function(e){var f=new b;return a.subscribe(function(a){var b;try{b=c(a)}catch(g){return void e.onError(g)}var h=a;if(d)try{h=d(a)}catch(g){return void e.onError(g)}f.set(b,h)},e.onError.bind(e),function(){e.onNext(f),e.onCompleted()})})}function I(a,b,c){if(a.addEventListener)return a.addEventListener(b,c,!1),Zb(function(){a.removeEventListener(b,c,!1)});throw new Error("No listener found")}function J(a,b,c){var d=new Wb;if("[object NodeList]"===Object.prototype.toString.call(a))for(var e=0,f=a.length;f>e;e++)d.add(J(a.item(e),b,c));else a&&d.add(I(a,b,c));return d}function K(a,b,c){return new hd(function(d){function e(a,b){j[b]=a;var e;if(g[b]=!0,h||(h=g.every(hb))){try{e=c.apply(null,j)}catch(f){return void d.onError(f)}d.onNext(e)}else i&&d.onCompleted()}var f=2,g=[!1,!1],h=!1,i=!1,j=new Array(f);return new Wb(a.subscribe(function(a){e(a,0)},d.onError.bind(d),function(){i=!0,d.onCompleted()}),b.subscribe(function(a){e(a,1)},d.onError.bind(d)))})}function L(a,b){return a.groupJoin(this,b,function(){return Ec()},function(a,b){return b})}function M(a){var b=this;return new hd(function(c){var d=new kd,e=new Wb,f=new ac(e);return c.onNext(Sb(d,f)),e.add(b.subscribe(function(a){d.onNext(a)},function(a){d.onError(a),c.onError(a)},function(){d.onCompleted(),c.onCompleted()})),e.add(a.subscribe(function(){d.onCompleted(),d=new kd,c.onNext(Sb(d,f))},function(a){d.onError(a),c.onError(a)},function(){d.onCompleted(),c.onCompleted()})),f})}function N(a){var b=this;return new hd(function(c){var d,e=new SerialDisposable,f=new Wb(e),g=new ac(f),h=new kd;return c.onNext(Sb(h,g)),f.add(b.subscribe(function(a){h.onNext(a)},function(a){h.onError(a),c.onError(a)},function(){h.onCompleted(),c.onCompleted()})),d=function(){var b,f;try{f=a()}catch(i){return void c.onError(i)}b=new _b,e.setDisposable(b),b.setDisposable(f.take(1).subscribe(fb,function(a){h.onError(a),c.onError(a)},function(){h.onCompleted(),h=new kd,c.onNext(Sb(h,g)),d()}))},d(),g})}function O(b,c){return new qc(function(){return new pc(function(){return b()?{done:!1,value:c}:{done:!0,value:a}})})}function P(a){this.patterns=a}function Q(a,b){this.expression=a,this.selector=b}function R(a,b,c){var d=a.get(b);if(!d){var e=new ed(b,c);return a.set(b,e),e}return d}function S(a,b,c){var d,e;for(this.joinObserverArray=a,this.onNext=b,this.onCompleted=c,this.joinObservers=new dd,d=0;d0){var b=c.now();f+=g,b>=f&&(f=b+g)}d.onNext(e++),a(f)})})}function V(a,b){return new hd(function(c){return b.scheduleWithRelative(dc(a),function(){c.onNext(0),c.onCompleted()})})}function W(a,b,c){return a===b?new hd(function(a){return c.schedulePeriodicWithState(0,b,function(b){return a.onNext(b),b+1})}):Dc(function(){return U(c.now()+a,b,c)})}function X(a,b,c){return new hd(function(d){var e,f=!1,g=new SerialDisposable,h=null,i=[],j=!1;return e=a.materialize().timestamp(c).subscribe(function(a){var e,k;"E"===a.value.kind?(i=[],i.push(a),h=a.value.exception,k=!j):(i.push({value:a.value,timestamp:a.timestamp+b}),k=!f,f=!0),k&&(null!==h?d.onError(h):(e=new _b,g.setDisposable(e),e.setDisposable(c.scheduleRecursiveWithRelative(b,function(a){var b,e,g,k;if(null===h){j=!0;do g=null,i.length>0&&i[0].timestamp-c.now()<=0&&(g=i.shift().value),null!==g&&g.accept(d);while(null!==g);k=!1,e=0,i.length>0?(k=!0,e=Math.max(0,i[0].timestamp-c.now())):f=!1,b=h,j=!1,null!==b?d.onError(b):k&&a(e)}}))))}),new Wb(e,g)})}function Y(a,b,c){return Dc(function(){return X(a,b-c.now(),c)})}function Z(a,b){return new hd(function(c){function d(){g&&(g=!1,c.onNext(f)),e&&c.onCompleted()}var e,f,g;return new Wb(a.subscribe(function(a){g=!0,f=a},c.onError.bind(c),function(){e=!0}),b.subscribe(d,c.onError.bind(c),d))})}var $={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},_=$[typeof window]&&window||this,ab=$[typeof exports]&&exports&&!exports.nodeType&&exports,bb=$[typeof module]&&module&&!module.nodeType&&module,cb=bb&&bb.exports===ab&&ab,db=$[typeof global]&&global;!db||db.global!==db&&db.window!==db||(_=db);var eb={internals:{},config:{Promise:_.Promise},helpers:{}},fb=eb.helpers.noop=function(){},gb=(eb.helpers.notDefined=function(a){return"undefined"==typeof a},eb.helpers.isScheduler=function(a){return a instanceof eb.Scheduler}),hb=eb.helpers.identity=function(a){return a},ib=(eb.helpers.pluck=function(a){return function(b){return b[a]}},eb.helpers.just=function(a){return function(){return a}},eb.helpers.defaultNow=Date.now),jb=eb.helpers.defaultComparer=function(a,b){return Ob(a,b)},kb=eb.helpers.defaultSubComparer=function(a,b){return a>b?1:b>a?-1:0},lb=(eb.helpers.defaultKeySerializer=function(a){return a.toString()},eb.helpers.defaultError=function(a){throw a}),mb=eb.helpers.isPromise=function(a){return!!a&&"function"==typeof a.then},nb=(eb.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},eb.helpers.not=function(a){return!a}),ob="Sequence contains no elements.",pb="Argument out of range",qb="Object has been disposed",rb="function"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";_.Set&&"function"==typeof(new _.Set)["@@iterator"]&&(rb="@@iterator");var sb,tb={done:!0,value:a},ub="[object Arguments]",vb="[object Array]",wb="[object Boolean]",xb="[object Date]",yb="[object Error]",zb="[object Function]",Ab="[object Number]",Bb="[object Object]",Cb="[object RegExp]",Db="[object String]",Eb=Object.prototype.toString,Fb=Object.prototype.hasOwnProperty,Gb=Eb.call(arguments)==ub,Hb=Error.prototype,Ib=Object.prototype,Jb=Ib.propertyIsEnumerable;try{sb=!(Eb.call(document)==Bb&&!({toString:0}+""))}catch(Kb){sb=!0}var Lb=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Mb={};Mb[vb]=Mb[xb]=Mb[Ab]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},Mb[wb]=Mb[Db]={constructor:!0,toString:!0,valueOf:!0},Mb[yb]=Mb[zb]=Mb[Cb]={constructor:!0,toString:!0},Mb[Bb]={constructor:!0};var Nb={};!function(){var a=function(){this.x=1},b=[];a.prototype={valueOf:1,y:1};for(var c in new a)b.push(c);for(c in arguments);Nb.enumErrorProps=Jb.call(Hb,"message")||Jb.call(Hb,"name"),Nb.enumPrototypes=Jb.call(a,"prototype"),Nb.nonEnumArgs=0!=c,Nb.nonEnumShadows=!/valueOf/.test(b)}(1),Gb||(h=function(a){return a&&"object"==typeof a?Fb.call(a,"callee"):!1}),i(/x/)&&(i=function(a){return"function"==typeof a&&Eb.call(a)==zb});var Ob=eb.internals.isEqual=function(a,b){return j(a,b,[],[])},Pb=Array.prototype.slice,Qb=({}.hasOwnProperty,this.inherits=eb.internals.inherits=function(a,b){function c(){this.constructor=a}c.prototype=b.prototype,a.prototype=new c}),Rb=eb.internals.addProperties=function(a){for(var b=Pb.call(arguments,1),c=0,d=b.length;d>c;c++){var e=b[c];for(var f in e)a[f]=e[f]}},Sb=eb.internals.addRef=function(a,b){return new hd(function(c){return new Wb(b.getDisposable(),a.subscribe(c))})},Tb=function(a,b){this.id=a,this.value=b};Tb.prototype.compareTo=function(a){var b=this.value.compareTo(a.value);return 0===b&&(b=this.id-a.id),b};var Ub=eb.internals.PriorityQueue=function(a){this.items=new Array(a),this.length=0},Vb=Ub.prototype;Vb.isHigherPriority=function(a,b){return this.items[a].compareTo(this.items[b])<0},Vb.percolate=function(a){if(!(a>=this.length||0>a)){var b=a-1>>1;if(!(0>b||b===a)&&this.isHigherPriority(a,b)){var c=this.items[a];this.items[a]=this.items[b],this.items[b]=c,this.percolate(b)}}},Vb.heapify=function(b){if(b===a&&(b=0),!(b>=this.length||0>b)){var c=2*b+1,d=2*b+2,e=b;if(cb;b++)a[b].dispose()}},Xb.toArray=function(){return this.disposables.slice(0)};var Yb=eb.Disposable=function(a){this.isDisposed=!1,this.action=a||fb};Yb.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var Zb=Yb.create=function(a){return new Yb(a)},$b=Yb.empty={dispose:fb},_b=eb.SingleAssignmentDisposable=SerialDisposable=eb.SerialDisposable=function(){function a(){this.isDisposed=!1,this.current=null}var b=a.prototype;return b.getDisposable=function(){return this.current},b.setDisposable=function(a){var b,c=this.isDisposed;c||(b=this.current,this.current=a),b&&b.dispose(),c&&a&&a.dispose()},b.dispose=function(){var a;this.isDisposed||(this.isDisposed=!0,a=this.current,this.current=null),a&&a.dispose()},a}(),ac=eb.RefCountDisposable=function(){function a(a){this.disposable=a,this.disposable.count++,this.isInnerDisposed=!1}function b(a){this.underlyingDisposable=a,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return a.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},b.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},b.prototype.getDisposable=function(){return this.isDisposed?$b:new a(this)},b}();m.prototype.dispose=function(){var a=this;this.scheduler.schedule(function(){a.isDisposed||(a.isDisposed=!0,a.disposable.dispose())})};var bc=eb.internals.ScheduledItem=function(a,b,c,d,e){this.scheduler=a,this.state=b,this.action=c,this.dueTime=d,this.comparer=e||kb,this.disposable=new _b};bc.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},bc.prototype.compareTo=function(a){return this.comparer(this.dueTime,a.dueTime)},bc.prototype.isCancelled=function(){return this.disposable.isDisposed},bc.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var cc=eb.Scheduler=function(){function a(a,b,c,d){this.now=a,this._schedule=b,this._scheduleRelative=c,this._scheduleAbsolute=d}function b(a,b){return b(),$b}var c=a.prototype;return c.schedule=function(a){return this._schedule(a,b)},c.scheduleWithState=function(a,b){return this._schedule(a,b)},c.scheduleWithRelative=function(a,c){return this._scheduleRelative(c,a,b)},c.scheduleWithRelativeAndState=function(a,b,c){return this._scheduleRelative(a,b,c)},c.scheduleWithAbsolute=function(a,c){return this._scheduleAbsolute(c,a,b)},c.scheduleWithAbsoluteAndState=function(a,b,c){return this._scheduleAbsolute(a,b,c)},a.now=ib,a.normalize=function(a){return 0>a&&(a=0),a},a}(),dc=cc.normalize;!function(a){function b(a,b){var c=b.first,d=b.second,e=new Wb,f=function(b){d(b,function(b){var c=!1,d=!1,g=a.scheduleWithState(b,function(a,b){return c?e.remove(g):d=!0,f(b),$b});d||(e.add(g),c=!0)})};return f(c),e}function c(a,b,c){var d=b.first,e=b.second,f=new Wb,g=function(b){e(b,function(b,d){var e=!1,h=!1,i=a[c].call(a,b,d,function(a,b){return e?f.remove(i):h=!0,g(b),$b});h||(f.add(i),e=!0)})};return g(d),f}function d(a,b){a(function(c){b(a,c)})}a.scheduleRecursive=function(a){return this.scheduleRecursiveWithState(a,function(a,b){a(function(){b(a)})})},a.scheduleRecursiveWithState=function(a,c){return this.scheduleWithState({first:a,second:c},b)},a.scheduleRecursiveWithRelative=function(a,b){return this.scheduleRecursiveWithRelativeAndState(b,a,d)},a.scheduleRecursiveWithRelativeAndState=function(a,b,d){return this._scheduleRelative({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithRelativeAndState")})},a.scheduleRecursiveWithAbsolute=function(a,b){return this.scheduleRecursiveWithAbsoluteAndState(b,a,d)},a.scheduleRecursiveWithAbsoluteAndState=function(a,b,d){return this._scheduleAbsolute({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithAbsoluteAndState")})}}(cc.prototype),function(){cc.prototype.schedulePeriodic=function(a,b){return this.schedulePeriodicWithState(null,a,b)},cc.prototype.schedulePeriodicWithState=function(a,b,c){var d=a,e=setInterval(function(){d=c(d)},b);return Zb(function(){clearInterval(e)})}}(cc.prototype),function(a){a.catchError=a["catch"]=function(a){return new kc(this,a)}}(cc.prototype);var ec,fc=eb.internals.SchedulePeriodicRecursive=function(){function a(a,b){b(0,this._period);try{this._state=this._action(this._state)}catch(c){throw this._cancel.dispose(),c}}function b(a,b,c,d){this._scheduler=a,this._state=b,this._period=c,this._action=d}return b.prototype.start=function(){var b=new _b;return this._cancel=b,b.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,a.bind(this))),b},b}(),gc=cc.immediate=function(){function a(a,b){return b(this,a)}function b(a,b,c){for(var d=dc(d);d-this.now()>0;);return c(this,a)}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new cc(ib,a,b,c)}(),hc=cc.currentThread=function(){function a(a){for(var b;a.length>0;)if(b=a.dequeue(),!b.isCancelled()){for(;b.dueTime-cc.now()>0;);b.isCancelled()||b.invoke()}}function b(a,b){return this.scheduleWithRelativeAndState(a,0,b)}function c(b,c,d){var f=this.now()+cc.normalize(c),g=new bc(this,b,d,f);if(e)e.enqueue(g);else{e=new Ub(4),e.enqueue(g);try{a(e)}catch(h){throw h}finally{e=null}}return g.disposable}function d(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}var e,f=new cc(ib,b,c,d);return f.scheduleRequired=function(){return!e},f.ensureTrampoline=function(a){e?a():this.schedule(a)},f}(),ic=fb;!function(){function a(){if(!_.postMessage||_.importScripts)return!1;var a=!1,b=_.onmessage;return _.onmessage=function(){a=!0},_.postMessage("","*"),_.onmessage=b,a}function b(a){if("string"==typeof a.data&&a.data.substring(0,f.length)===f){var b=a.data.substring(f.length),c=g[b];c(),delete g[b]}}var c=RegExp("^"+String(Eb).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),d="function"==typeof(d=db&&cb&&db.setImmediate)&&!c.test(d)&&d,e="function"==typeof(e=db&&cb&&db.clearImmediate)&&!c.test(e)&&e;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))ec=process.nextTick;else if("function"==typeof d)ec=d,ic=e;else if(a()){var f="ms.rx.schedule"+Math.random(),g={},h=0;_.addEventListener?_.addEventListener("message",b,!1):_.attachEvent("onmessage",b,!1),ec=function(a){var b=h++;g[b]=a,_.postMessage(f+b,"*")}}else if(_.MessageChannel){var i=new _.MessageChannel,j={},k=0;i.port1.onmessage=function(a){var b=a.data,c=j[b];c(),delete j[b]},ec=function(a){var b=k++;j[b]=a,i.port2.postMessage(b)}}else"document"in _&&"onreadystatechange"in _.document.createElement("script")?ec=function(a){var b=_.document.createElement("script");b.onreadystatechange=function(){a(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},_.document.documentElement.appendChild(b)}:(ec=function(a){return setTimeout(a,0)},ic=clearTimeout)}();var jc=cc.timeout=function(){function a(a,b){var c=this,d=new _b,e=ec(function(){d.isDisposed||d.setDisposable(b(c,a))});return new Wb(d,Zb(function(){ic(e)}))}function b(a,b,c){var d=this,e=cc.normalize(b);if(0===e)return d.scheduleWithState(a,c);var f=new _b,g=setTimeout(function(){f.isDisposed||f.setDisposable(c(d,a))},e);return new Wb(f,Zb(function(){clearTimeout(g)}))}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new cc(ib,a,b,c)}(),kc=function(a){function b(){return this._scheduler.now()}function c(a,b){return this._scheduler.scheduleWithState(a,this._wrap(b))}function d(a,b,c){return this._scheduler.scheduleWithRelativeAndState(a,b,this._wrap(c))}function e(a,b,c){return this._scheduler.scheduleWithAbsoluteAndState(a,b,this._wrap(c))}function f(f,g){this._scheduler=f,this._handler=g,this._recursiveOriginal=null,this._recursiveWrapper=null,a.call(this,b,c,d,e)}return Qb(f,a),f.prototype._clone=function(a){return new f(a,this._handler)},f.prototype._wrap=function(a){var b=this;return function(c,d){try{return a(b._getRecursiveWrapper(c),d)}catch(e){if(!b._handler(e))throw e;return $b}}},f.prototype._getRecursiveWrapper=function(a){if(this._recursiveOriginal!==a){this._recursiveOriginal=a;var b=this._clone(a);b._recursiveOriginal=a,b._recursiveWrapper=b,this._recursiveWrapper=b}return this._recursiveWrapper},f.prototype.schedulePeriodicWithState=function(a,b,c){var d=this,e=!1,f=new _b;return f.setDisposable(this._scheduler.schedulePeriodicWithState(a,b,function(a){if(e)return null;try{return c(a)}catch(b){if(e=!0,!d._handler(b))throw b;return f.dispose(),null}})),f},f}(cc),lc=eb.Notification=function(){function a(a,b){this.hasValue=null==b?!1:b,this.kind=a}return a.prototype.accept=function(a,b,c){return a&&"object"==typeof a?this._acceptObservable(a):this._accept(a,b,c)},a.prototype.toObservable=function(a){var b=this;return gb(a)||(a=gc),new hd(function(c){return a.schedule(function(){b._acceptObservable(c),"N"===b.kind&&c.onCompleted()})})},a}(),mc=lc.createOnNext=function(){function a(a){return a(this.value)}function b(a){return a.onNext(this.value)}function c(){return"OnNext("+this.value+")"}return function(d){var e=new lc("N",!0);return e.value=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),nc=lc.createOnError=function(){function a(a,b){return b(this.exception)}function b(a){return a.onError(this.exception)}function c(){return"OnError("+this.exception+")"}return function(d){var e=new lc("E");return e.exception=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),oc=lc.createOnCompleted=function(){function a(a,b,c){return c()}function b(a){return a.onCompleted()}function c(){return"OnCompleted()"}return function(){var d=new lc("C");return d._accept=a,d._acceptObservable=b,d.toString=c,d}}(),pc=eb.internals.Enumerator=function(a){this._next=a};pc.prototype.next=function(){return this._next()},pc.prototype[rb]=function(){return this};var qc=eb.internals.Enumerable=function(a){this._iterator=a};qc.prototype[rb]=function(){return this._iterator()},qc.prototype.concat=function(){var a=this;return new hd(function(b){var c;try{c=a[rb]()}catch(d){return void b.onError()}var e,f=new SerialDisposable,g=gc.scheduleRecursive(function(a){var d;if(!e){try{d=c.next()}catch(g){return void b.onError(g)}if(d.done)return void b.onCompleted();var h=d.value;mb(h)&&(h=Cc(h));var i=new _b;f.setDisposable(i),i.setDisposable(h.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){a()}))}});return new Wb(f,g,Zb(function(){e=!0}))})},qc.prototype.catchException=function(){var a=this;return new hd(function(b){var c;try{c=a[rb]()}catch(d){return void b.onError()}var e,f,g=new SerialDisposable,h=gc.scheduleRecursive(function(a){if(!e){var d;try{d=c.next()}catch(h){return void b.onError(h)}if(d.done)return void(f?b.onError(f):b.onCompleted());var i=d.value;mb(i)&&(i=Cc(i));var j=new _b;g.setDisposable(j),j.setDisposable(i.subscribe(b.onNext.bind(b),function(b){f=b,a()},b.onCompleted.bind(b)))}});return new Wb(g,h,Zb(function(){e=!0}))})};var rc=qc.repeat=function(a,b){return null==b&&(b=-1),new qc(function(){var c=b;return new pc(function(){return 0===c?tb:(c>0&&c--,{done:!1,value:a})})})},sc=qc.forEach=function(a,b,c){return b||(b=hb),new qc(function(){var d=-1;return new pc(function(){return++d0&&(a=!this.isAcquired,this.isAcquired=!0),a&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(a){var c;if(!(b.queue.length>0))return void(b.isAcquired=!1);c=b.queue.shift();try{c()}catch(d){throw b.queue=[],b.hasFaulted=!0,d}a()}))},b.prototype.dispose=function(){a.prototype.dispose.call(this),this.disposable.dispose()},b}(wc),Ac=function(a){function b(){a.apply(this,arguments)}return Qb(b,a),b.prototype.next=function(b){a.prototype.next.call(this,b),this.ensureActive()},b.prototype.error=function(b){a.prototype.error.call(this,b),this.ensureActive()},b.prototype.completed=function(){a.prototype.completed.call(this),this.ensureActive()},b}(zc),Bc=eb.Observable=function(){function a(a){this._subscribe=a}return vc=a.prototype,vc.subscribe=vc.forEach=function(a,b,c){var d="object"==typeof a?a:uc(a,b,c);return this._subscribe(d)},a}();vc.observeOn=function(a){var b=this;return new hd(function(c){return b.subscribe(new Ac(a,c))})},vc.subscribeOn=function(a){var b=this;return new hd(function(c){var d=new _b,e=new SerialDisposable;return e.setDisposable(d),d.setDisposable(a.schedule(function(){e.setDisposable(new m(a,b.subscribe(c)))})),e})};var Cc=Bc.fromPromise=function(a){return Dc(function(){var b=new eb.AsyncSubject;return a.then(function(a){b.isDisposed||(b.onNext(a),b.onCompleted())},b.onError.bind(b)),b})};vc.toPromise=function(a){if(a||(a=eb.config.Promise),!a)throw new Error("Promise type not provided nor in Rx.config.Promise");var b=this;return new a(function(a,c){var d,e=!1;b.subscribe(function(a){d=a,e=!0},function(a){c(a)},function(){e&&a(d)})})},vc.toArray=function(){var a=this;return new hd(function(b){var c=[];return a.subscribe(c.push.bind(c),b.onError.bind(b),function(){b.onNext(c),b.onCompleted()})})},Bc.create=Bc.createWithDisposable=function(a){return new hd(a)};var Dc=Bc.defer=function(a){return new hd(function(b){var c;try{c=a()}catch(d){return Jc(d).subscribe(b)}return mb(c)&&(c=Cc(c)),c.subscribe(b)})},Ec=Bc.empty=function(a){return gb(a)||(a=gc),new hd(function(b){return a.schedule(function(){b.onCompleted()})})},Fc=Math.pow(2,53)-1;Bc.from=function(a,b,c,d){if(null==a)throw new Error("iterable cannot be null.");if(b&&!r(b))throw new Error("mapFn when provided must be a function");return gb(d)||(d=hc),new hd(function(e){var f=Object(a),g=o(f),h=g?0:q(f),i=g?f[rb]():null,j=0;return d.scheduleRecursive(function(a){if(h>j||g){var d;if(g){var k=i.next();if(k.done)return void e.onCompleted();d=k.value}else d=f[j];if(b&&r(b))try{d=c?b.call(c,d,j):b(d,j)}catch(l){return void e.onError(l)}e.onNext(d),j++,a()}else e.onCompleted()})})};var Gc=Bc.fromArray=function(a,b){return gb(b)||(b=hc),new hd(function(c){var d=0,e=a.length;return b.scheduleRecursive(function(b){e>d?(c.onNext(a[d++]),b()):c.onCompleted()})})};Bc.generate=function(a,b,c,d,e){return gb(e)||(e=hc),new hd(function(f){var g=!0,h=a;return e.scheduleRecursive(function(a){var e,i;try{g?g=!1:h=c(h),e=b(h),e&&(i=d(h))}catch(j){return void f.onError(j)}e?(f.onNext(i),a()):f.onCompleted()})})},Bc.of=function(){for(var a=arguments.length,b=new Array(a),c=0;a>c;c++)b[c]=arguments[c];return Gc(b)};var Hc=(Bc.ofWithScheduler=function(a){for(var b=arguments.length-1,c=new Array(b),d=0;b>d;d++)c[d]=arguments[d+1];return Gc(c,a)},Bc.never=function(){return new hd(function(){return $b})});Bc.range=function(a,b,c){return gb(c)||(c=hc),new hd(function(d){return c.scheduleRecursiveWithState(0,function(c,e){b>c?(d.onNext(a+c),e(c+1)):d.onCompleted()})})},Bc.repeat=function(a,b,c){return gb(c)||(c=hc),Ic(a,c).repeat(null==b?-1:b)};var Ic=Bc["return"]=Bc.returnValue=Bc.just=function(a,b){return gb(b)||(b=gc),new hd(function(c){return b.schedule(function(){c.onNext(a),c.onCompleted() +})})},Jc=Bc["throw"]=Bc.throwException=function(a,b){return gb(b)||(b=gc),new hd(function(c){return b.schedule(function(){c.onError(a)})})};Bc.using=function(a,b){return new hd(function(c){var d,e,f=$b;try{d=a(),d&&(f=d),e=b(d)}catch(g){return new Wb(Jc(g).subscribe(c),f)}return new Wb(e.subscribe(c),f)})},vc.amb=function(a){var b=this;return new hd(function(c){function d(){f||(f=g,j.dispose())}function e(){f||(f=h,i.dispose())}var f,g="L",h="R",i=new _b,j=new _b;return mb(a)&&(a=Cc(a)),i.setDisposable(b.subscribe(function(a){d(),f===g&&c.onNext(a)},function(a){d(),f===g&&c.onError(a)},function(){d(),f===g&&c.onCompleted()})),j.setDisposable(a.subscribe(function(a){e(),f===h&&c.onNext(a)},function(a){e(),f===h&&c.onError(a)},function(){e(),f===h&&c.onCompleted()})),new Wb(i,j)})},Bc.amb=function(){function a(a,b){return a.amb(b)}for(var b=Hc(),c=k(arguments,0),d=0,e=c.length;e>d;d++)b=a(b,c[d]);return b},vc["catch"]=vc.catchException=function(a){return"function"==typeof a?s(this,a):Kc([this,a])};var Kc=Bc.catchException=Bc["catch"]=function(){var a=k(arguments,0);return sc(a).catchException()};vc.combineLatest=function(){var a=Pb.call(arguments);return Array.isArray(a[0])?a[0].unshift(this):a.unshift(this),Lc.apply(this,a)};var Lc=Bc.combineLatest=function(){var a=Pb.call(arguments),b=a.pop();return Array.isArray(a[0])&&(a=a[0]),new hd(function(c){function d(a){var d;if(h[a]=!0,i||(i=h.every(hb))){try{d=b.apply(null,k)}catch(e){return void c.onError(e)}c.onNext(d)}else j.filter(function(b,c){return c!==a}).every(hb)&&c.onCompleted()}function e(a){j[a]=!0,j.every(hb)&&c.onCompleted()}for(var f=function(){return!1},g=a.length,h=l(g,f),i=!1,j=l(g,f),k=new Array(g),m=new Array(g),n=0;g>n;n++)!function(b){var f=a[b],g=new _b;mb(f)&&(f=Cc(f)),g.setDisposable(f.subscribe(function(a){k[b]=a,d(b)},c.onError.bind(c),function(){e(b)})),m[b]=g}(n);return new Wb(m)})};vc.concat=function(){var a=Pb.call(arguments,0);return a.unshift(this),Mc.apply(this,a)};var Mc=Bc.concat=function(){var a=k(arguments,0);return sc(a).concat()};vc.concatObservable=vc.concatAll=function(){return this.merge(1)},vc.merge=function(a){if("number"!=typeof a)return Nc(this,a);var b=this;return new hd(function(c){function d(a){var b=new _b;f.add(b),mb(a)&&(a=Cc(a)),b.setDisposable(a.subscribe(c.onNext.bind(c),c.onError.bind(c),function(){f.remove(b),h.length>0?d(h.shift()):(e--,g&&0===e&&c.onCompleted())}))}var e=0,f=new Wb,g=!1,h=[];return f.add(b.subscribe(function(b){a>e?(e++,d(b)):h.push(b)},c.onError.bind(c),function(){g=!0,0===e&&c.onCompleted()})),f})};var Nc=Bc.merge=function(){var a,b;return arguments[0]?arguments[0].now?(a=arguments[0],b=Pb.call(arguments,1)):(a=gc,b=Pb.call(arguments,0)):(a=gc,b=Pb.call(arguments,1)),Array.isArray(b[0])&&(b=b[0]),Gc(b,a).mergeObservable()};vc.mergeObservable=vc.mergeAll=function(){var a=this;return new hd(function(b){var c=new Wb,d=!1,e=new _b;return c.add(e),e.setDisposable(a.subscribe(function(a){var e=new _b;c.add(e),mb(a)&&(a=Cc(a)),e.setDisposable(a.subscribe(function(a){b.onNext(a)},b.onError.bind(b),function(){c.remove(e),d&&1===c.length&&b.onCompleted()}))},b.onError.bind(b),function(){d=!0,1===c.length&&b.onCompleted()})),c})},vc.onErrorResumeNext=function(a){if(!a)throw new Error("Second observable is required");return Oc([this,a])};var Oc=Bc.onErrorResumeNext=function(){var a=k(arguments,0);return new hd(function(b){var c=0,d=new SerialDisposable,e=gc.scheduleRecursive(function(e){var f,g;c0})){try{f=h.map(function(a){return a.shift()}),e=c.apply(a,f)}catch(g){return void d.onError(g)}d.onNext(e)}else i.filter(function(a,c){return c!==b}).every(hb)&&d.onCompleted()}function f(a){i[a]=!0,i.every(function(a){return a})&&d.onCompleted()}for(var g=b.length,h=l(g,function(){return[]}),i=l(g,function(){return!1}),j=new Array(g),k=0;g>k;k++)!function(a){var c=b[a],g=new _b;mb(c)&&(c=Cc(c)),g.setDisposable(c.subscribe(function(b){h[a].push(b),e(a)},d.onError.bind(d),function(){f(a)})),j[a]=g}(k);return new Wb(j)})},Bc.zip=function(){var a=Pb.call(arguments,0),b=a.shift();return b.zip.apply(b,a)},Bc.zipArray=function(){var a=k(arguments,0);return new hd(function(b){function c(a){if(f.every(function(a){return a.length>0})){var c=f.map(function(a){return a.shift()});b.onNext(c)}else if(g.filter(function(b,c){return c!==a}).every(hb))return void b.onCompleted()}function d(a){return g[a]=!0,g.every(hb)?void b.onCompleted():void 0}for(var e=a.length,f=l(e,function(){return[]}),g=l(e,function(){return!1}),h=new Array(e),i=0;e>i;i++)!function(e){h[e]=new _b,h[e].setDisposable(a[e].subscribe(function(a){f[e].push(a),c(e)},b.onError.bind(b),function(){d(e)}))}(i);var j=new Wb(h);return j.add(Zb(function(){for(var a=0,b=f.length;b>a;a++)f[a]=[]})),j})},vc.asObservable=function(){var a=this;return new hd(function(b){return a.subscribe(b)})},vc.bufferWithCount=function(a,b){return"number"!=typeof b&&(b=a),this.windowWithCount(a,b).selectMany(function(a){return a.toArray()}).where(function(a){return a.length>0})},vc.dematerialize=function(){var a=this;return new hd(function(b){return a.subscribe(function(a){return a.accept(b)},b.onError.bind(b),b.onCompleted.bind(b))})},vc.distinctUntilChanged=function(a,b){var c=this;return a||(a=hb),b||(b=jb),new hd(function(d){var e,f=!1;return c.subscribe(function(c){var g,h=!1;try{g=a(c)}catch(i){return void d.onError(i)}if(f)try{h=b(e,g)}catch(i){return void d.onError(i)}f&&h||(f=!0,e=g,d.onNext(c))},d.onError.bind(d),d.onCompleted.bind(d))})},vc["do"]=vc.doAction=vc.tap=function(a,b,c){var d,e=this;return"function"==typeof a?d=a:(d=a.onNext.bind(a),b=a.onError.bind(a),c=a.onCompleted.bind(a)),new hd(function(a){return e.subscribe(function(b){try{d(b)}catch(c){a.onError(c)}a.onNext(b)},function(c){if(b){try{b(c)}catch(d){a.onError(d)}a.onError(c)}else a.onError(c)},function(){if(c){try{c()}catch(b){a.onError(b)}a.onCompleted()}else a.onCompleted()})})},vc["finally"]=vc.finallyAction=function(a){var b=this;return new hd(function(c){var d;try{d=b.subscribe(c)}catch(e){throw a(),e}return Zb(function(){try{d.dispose()}catch(b){throw b}finally{a()}})})},vc.ignoreElements=function(){var a=this;return new hd(function(b){return a.subscribe(fb,b.onError.bind(b),b.onCompleted.bind(b))})},vc.materialize=function(){var a=this;return new hd(function(b){return a.subscribe(function(a){b.onNext(mc(a))},function(a){b.onNext(nc(a)),b.onCompleted()},function(){b.onNext(oc()),b.onCompleted()})})},vc.repeat=function(a){return rc(this,a).concat()},vc.retry=function(a){return rc(this,a).catchException()},vc.scan=function(){var a,b,c=!1,d=this;return 2===arguments.length?(c=!0,a=arguments[0],b=arguments[1]):b=arguments[0],new hd(function(e){var f,g,h;return d.subscribe(function(d){try{h||(h=!0),f?g=b(g,d):(g=c?b(a,d):d,f=!0)}catch(i){return void e.onError(i)}e.onNext(g)},e.onError.bind(e),function(){!h&&c&&e.onNext(a),e.onCompleted()})})},vc.skipLast=function(a){var b=this;return new hd(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&c.onNext(d.shift())},c.onError.bind(c),c.onCompleted.bind(c))})},vc.startWith=function(){var a,b,c=0;return arguments.length&&"now"in Object(arguments[0])?(b=arguments[0],c=1):b=gc,a=Pb.call(arguments,c),sc([Gc(a,b),this]).concat()},vc.takeLast=function(a){var b=this;return new hd(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&d.shift()},c.onError.bind(c),function(){for(;d.length>0;)c.onNext(d.shift());c.onCompleted()})})},vc.takeLastBuffer=function(a){var b=this;return new hd(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&d.shift()},c.onError.bind(c),function(){c.onNext(d),c.onCompleted()})})},vc.windowWithCount=function(a,b){var c=this;if(0>=a)throw new Error(pb);if(1===arguments.length&&(b=a),0>=b)throw new Error(pb);return new hd(function(d){var e=new _b,f=new ac(e),g=0,h=[],i=function(){var a=new kd;h.push(a),d.onNext(Sb(a,f))};return i(),e.setDisposable(c.subscribe(function(c){for(var d,e=0,f=h.length;f>e;e++)h[e].onNext(c);var j=g-a+1;j>=0&&j%b===0&&(d=h.shift(),d.onCompleted()),g++,g%b===0&&i()},function(a){for(;h.length>0;)h.shift().onError(a);d.onError(a)},function(){for(;h.length>0;)h.shift().onCompleted();d.onCompleted()})),f})},vc.selectConcat=vc.concatMap=function(a,b,c){return b?this.concatMap(function(c,d){var e=a(c,d),f=mb(e)?Cc(e):e;return f.map(function(a){return b(c,a,d)})}):"function"==typeof a?u(this,a,c):u(this,function(){return a})},vc.concatMapObserver=vc.selectConcatObserver=function(a,b,c,d){var e=this;return new hd(function(f){var g=0;return e.subscribe(function(b){var c;try{c=a.call(d,b,g++)}catch(e){return void f.onError(e)}mb(c)&&(c=Cc(c)),f.onNext(c)},function(a){var c;try{c=b.call(d,a)}catch(e){return void f.onError(e)}mb(c)&&(c=Cc(c)),f.onNext(c),f.onCompleted()},function(){var a;try{a=c.call(d)}catch(b){return void f.onError(b)}mb(a)&&(a=Cc(a)),f.onNext(a),f.onCompleted()})}).concatAll()},vc.defaultIfEmpty=function(b){var c=this;return b===a&&(b=null),new hd(function(a){var d=!1;return c.subscribe(function(b){d=!0,a.onNext(b)},a.onError.bind(a),function(){d||a.onNext(b),a.onCompleted()})})},w.prototype.push=function(a){var b=-1===v(this.set,a,this.comparer);return b&&this.set.push(a),b},vc.distinct=function(a,b){var c=this;return b||(b=jb),new hd(function(d){var e=new w(b);return c.subscribe(function(b){var c=b;if(a)try{c=a(b)}catch(f){return void d.onError(f)}e.push(c)&&d.onNext(b)},d.onError.bind(d),d.onCompleted.bind(d))})},vc.groupBy=function(a,b,c){return this.groupByUntil(a,b,Hc,c)},vc.groupByUntil=function(a,b,c,d){var e=this;return b||(b=hb),d||(d=jb),new hd(function(f){function g(a){return function(b){b.onError(a)}}var h=new ad(0,d),i=new Wb,j=new ac(i);return i.add(e.subscribe(function(d){var e;try{e=a(d)}catch(k){return h.getValues().forEach(g(k)),void f.onError(k)}var l=!1,m=h.tryGetValue(e);if(m||(m=new kd,h.set(e,m),l=!0),l){var n=new jd(e,m,j),o=new jd(e,m);try{duration=c(o)}catch(k){return h.getValues().forEach(g(k)),void f.onError(k)}f.onNext(n);var p=new _b;i.add(p);var q=function(){h.remove(e)&&m.onCompleted(),i.remove(p)};p.setDisposable(duration.take(1).subscribe(fb,function(a){h.getValues().forEach(g(a)),f.onError(a)},q))}var r;try{r=b(d)}catch(k){return h.getValues().forEach(g(k)),void f.onError(k)}m.onNext(r)},function(a){h.getValues().forEach(g(a)),f.onError(a)},function(){h.getValues().forEach(function(a){a.onCompleted()}),f.onCompleted()})),j})},vc.select=vc.map=function(a,b){var c=this;return new hd(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},vc.pluck=function(a){return this.select(function(b){return b[a]})},vc.selectMany=vc.flatMap=function(a,b,c){return b?this.flatMap(function(c,d){var e=a(c,d),f=mb(e)?Cc(e):e;return f.map(function(a){return b(c,a,d)})},c):"function"==typeof a?x(this,a,c):x(this,function(){return a})},vc.flatMapObserver=vc.selectManyObserver=function(a,b,c,d){var e=this;return new hd(function(f){var g=0;return e.subscribe(function(b){var c;try{c=a.call(d,b,g++)}catch(e){return void f.onError(e)}mb(c)&&(c=Cc(c)),f.onNext(c)},function(a){var c;try{c=b.call(d,a)}catch(e){return void f.onError(e)}mb(c)&&(c=Cc(c)),f.onNext(c),f.onCompleted()},function(){var a;try{a=c.call(d)}catch(b){return void f.onError(b)}mb(a)&&(a=Cc(a)),f.onNext(a),f.onCompleted()})}).mergeAll()},vc.selectSwitch=vc.flatMapLatest=vc.switchMap=function(a,b){return this.select(a,b).switchLatest()},vc.skip=function(a){if(0>a)throw new Error(pb);var b=this;return new hd(function(c){var d=a;return b.subscribe(function(a){0>=d?c.onNext(a):d--},c.onError.bind(c),c.onCompleted.bind(c))})},vc.skipWhile=function(a,b){var c=this;return new hd(function(d){var e=0,f=!1;return c.subscribe(function(g){if(!f)try{f=!a.call(b,g,e++,c)}catch(h){return void d.onError(h)}f&&d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},vc.take=function(a,b){if(0>a)throw new Error(pb);if(0===a)return Ec(b);var c=this;return new hd(function(b){var d=a;return c.subscribe(function(a){d>0&&(d--,b.onNext(a),0===d&&b.onCompleted())},b.onError.bind(b),b.onCompleted.bind(b))})},vc.takeWhile=function(a,b){var c=this;return new hd(function(d){var e=0,f=!0;return c.subscribe(function(g){if(f){try{f=a.call(b,g,e++,c)}catch(h){return void d.onError(h)}f?d.onNext(g):d.onCompleted()}},d.onError.bind(d),d.onCompleted.bind(d))})},vc.where=vc.filter=function(a,b){var c=this;return new hd(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}g&&d.onNext(f)},d.onError.bind(d),d.onCompleted.bind(d))})},vc.finalValue=function(){var a=this;return new hd(function(b){var c,d=!1;return a.subscribe(function(a){d=!0,c=a},b.onError.bind(b),function(){d?(b.onNext(c),b.onCompleted()):b.onError(new Error(ob))})})},vc.aggregate=function(){var a,b,c;return 2===arguments.length?(a=arguments[0],b=!0,c=arguments[1]):c=arguments[0],b?this.scan(a,c).startWith(a).finalValue():this.scan(c).finalValue()},vc.reduce=function(a){var b,c;return 2===arguments.length&&(c=!0,b=arguments[1]),c?this.scan(b,a).startWith(b).finalValue():this.scan(a).finalValue()},vc.some=vc.any=function(a,b){var c=this;return a?c.where(a,b).any():new hd(function(a){return c.subscribe(function(){a.onNext(!0),a.onCompleted()},a.onError.bind(a),function(){a.onNext(!1),a.onCompleted()})})},vc.isEmpty=function(){return this.any().map(nb)},vc.every=vc.all=function(a,b){return this.where(function(b){return!a(b)},b).any().select(function(a){return!a})},vc.contains=function(a,b){return b||(b=jb),this.where(function(c){return b(c,a)}).any()},vc.count=function(a,b){return a?this.where(a,b).count():this.aggregate(0,function(a){return a+1})},vc.sum=function(a,b){return a?this.select(a,b).sum():this.aggregate(0,function(a,b){return a+b})},vc.minBy=function(a,b){return b||(b=kb),y(this,a,function(a,c){return-1*b(a,c)})},vc.min=function(a){return this.minBy(hb,a).select(function(a){return z(a)})},vc.maxBy=function(a,b){return b||(b=kb),y(this,a,b)},vc.max=function(a){return this.maxBy(hb,a).select(function(a){return z(a)})},vc.average=function(a,b){return a?this.select(a,b).average():this.scan({sum:0,count:0},function(a,b){return{sum:a.sum+b,count:a.count+1}}).finalValue().select(function(a){if(0===a.count)throw new Error("The input sequence was empty");return a.sum/a.count})},vc.sequenceEqual=function(a,b){var c=this;return b||(b=jb),Array.isArray(a)?A(c,a,b):new hd(function(d){var e=!1,f=!1,g=[],h=[],i=c.subscribe(function(a){var c,e;if(h.length>0){e=h.shift();try{c=b(e,a)}catch(i){return void d.onError(i)}c||(d.onNext(!1),d.onCompleted())}else f?(d.onNext(!1),d.onCompleted()):g.push(a)},d.onError.bind(d),function(){e=!0,0===g.length&&(h.length>0?(d.onNext(!1),d.onCompleted()):f&&(d.onNext(!0),d.onCompleted()))});mb(a)&&(a=Cc(a));var j=a.subscribe(function(a){var c,f;if(g.length>0){f=g.shift();try{c=b(f,a)}catch(i){return void d.onError(i)}c||(d.onNext(!1),d.onCompleted())}else e?(d.onNext(!1),d.onCompleted()):h.push(a)},d.onError.bind(d),function(){f=!0,0===h.length&&(g.length>0?(d.onNext(!1),d.onCompleted()):e&&(d.onNext(!0),d.onCompleted()))});return new Wb(i,j)})},vc.elementAt=function(a){return B(this,a,!1)},vc.elementAtOrDefault=function(a,b){return B(this,a,!0,b)},vc.single=function(a,b){return a?this.where(a,b).single():C(this,!1)},vc.singleOrDefault=function(a,b,c){return a?this.where(a,c).singleOrDefault(null,b):C(this,!0,b)},vc.first=function(a,b){return a?this.where(a,b).first():D(this,!1)},vc.firstOrDefault=function(a,b){return a?this.where(a).firstOrDefault(null,b):D(this,!0,b)},vc.last=function(a,b){return a?this.where(a,b).last():E(this,!1)},vc.lastOrDefault=function(a,b,c){return a?this.where(a,c).lastOrDefault(null,b):E(this,!0,b)},vc.find=function(a,b){return F(this,a,b,!1)},vc.findIndex=function(a,b){return F(this,a,b,!0)},_.Set&&(vc.toSet=function(){return G(this,_.Set)}),_.WeakSet&&(vc.toWeakSet=function(){return G(this,_.WeakSet)}),_.Map&&(vc.toMap=function(a,b){return H(this,_.Map,a,b)}),_.WeakMap&&(vc.toWeakMap=function(a,b){return H(this,_.WeakMap,a,b)}),Bc.start=function(a,b,c){return Pc(a,b,c)()};var Pc=Bc.toAsync=function(a,b,c){return gb(c)||(c=jc),function(){var d=arguments,e=new ld;return c.schedule(function(){var c;try{c=a.apply(b,d)}catch(f){return void e.onError(f)}e.onNext(c),e.onCompleted()}),e.asObservable()}};Bc.fromCallback=function(a,b,c){return function(){var d=Pb.call(arguments,0);return new hd(function(e){function f(a){var b=a;if(c){try{b=c(arguments)}catch(d){return void e.onError(d)}e.onNext(b)}else b.length<=1?e.onNext.apply(e,b):e.onNext(b);e.onCompleted()}d.push(f),a.apply(b,d)}).publishLast().refCount()}},Bc.fromNodeCallback=function(a,b,c){return function(){var d=Pb.call(arguments,0);return new hd(function(e){function f(a){if(a)return void e.onError(a);var b=Pb.call(arguments,1);if(c){try{b=c(b)}catch(d){return void e.onError(d)}e.onNext(b)}else b.length<=1?e.onNext.apply(e,b):e.onNext(b);e.onCompleted()}d.push(f),a.apply(b,d)}).publishLast().refCount()}},eb.config.useNativeEvents=!1;var Qc=_.angular&&angular.element?angular.element:_.jQuery?_.jQuery:_.Zepto?_.Zepto:null,Rc=!!_.Ember&&"function"==typeof _.Ember.addListener,Sc=!!_.Backbone&&!!_.Backbone.Marionette;Bc.fromEvent=function(a,b,c){if(a.addListener)return Tc(function(c){a.addListener(b,c)},function(c){a.removeListener(b,c)},c);if(!eb.config.useNativeEvents){if(Sc)return Tc(function(c){a.on(b,c)},function(c){a.off(b,c)},c);if(Rc)return Tc(function(c){Ember.addListener(a,b,c)},function(c){Ember.removeListener(a,b,c)},c);if(Qc){var d=Qc(a);return Tc(function(a){d.on(b,a)},function(a){d.off(b,a)},c)}}return new hd(function(d){return J(a,b,function(a){var b=a;if(c)try{b=c(arguments)}catch(e){return void d.onError(e)}d.onNext(b)})}).publish().refCount()};var Tc=Bc.fromEventPattern=function(a,b,c){return new hd(function(d){function e(a){var b=a;if(c)try{b=c(arguments)}catch(e){return void d.onError(e)}d.onNext(b)}var f=a(e);return Zb(function(){b&&b(e,f)})}).publish().refCount()};Bc.startAsync=function(a){var b;try{b=a()}catch(c){return Jc(c)}return Cc(b)};var Uc=function(a){function b(a){var b=this.source.publish(),c=b.subscribe(a),d=$b,e=this.pauser.distinctUntilChanged().subscribe(function(a){a?d=b.connect():(d.dispose(),d=$b)});return new Wb(c,d,e)}function c(c,d){this.source=c,this.controller=new kd,this.pauser=d&&d.subscribe?this.controller.merge(d):this.controller,a.call(this,b)}return Qb(c,a),c.prototype.pause=function(){this.controller.onNext(!1)},c.prototype.resume=function(){this.controller.onNext(!0)},c}(Bc);vc.pausable=function(a){return new Uc(this,a)};var Vc=function(b){function c(b){var c,d=[],e=K(this.source,this.pauser.distinctUntilChanged().startWith(!1),function(a,b){return{data:a,shouldFire:b}}).subscribe(function(e){if(c!==a&&e.shouldFire!=c){if(e.shouldFire)for(;d.length>0;)b.onNext(d.shift())}else e.shouldFire?b.onNext(e.data):d.push(e.data);c=e.shouldFire},function(a){for(;d.length>0;)b.onNext(d.shift());b.onError(a)},function(){for(;d.length>0;)b.onNext(d.shift());b.onCompleted()});return e}function d(a,d){this.source=a,this.controller=new kd,this.pauser=d&&d.subscribe?this.controller.merge(d):this.controller,b.call(this,c)}return Qb(d,b),d.prototype.pause=function(){this.controller.onNext(!1)},d.prototype.resume=function(){this.controller.onNext(!0)},d}(Bc);vc.pausableBuffered=function(a){return new Vc(this,a)},vc.controlled=function(a){return null==a&&(a=!0),new Wc(this,a)};var Wc=function(a){function b(a){return this.source.subscribe(a)}function c(c,d){a.call(this,b),this.subject=new Xc(d),this.source=c.multicast(this.subject).refCount()}return Qb(c,a),c.prototype.request=function(a){return null==a&&(a=-1),this.subject.request(a)},c}(Bc),Xc=eb.ControlledSubject=function(a){function c(a){return this.subject.subscribe(a)}function d(b){null==b&&(b=!0),a.call(this,c),this.subject=new kd,this.enableQueue=b,this.queue=b?[]:null,this.requestedCount=0,this.requestedDisposable=$b,this.error=null,this.hasFailed=!1,this.hasCompleted=!1,this.controlledDisposable=$b}return Qb(d,a),Rb(d.prototype,tc,{onCompleted:function(){b.call(this),this.hasCompleted=!0,this.enableQueue&&0!==this.queue.length||this.subject.onCompleted()},onError:function(a){b.call(this),this.hasFailed=!0,this.error=a,this.enableQueue&&0!==this.queue.length||this.subject.onError(a)},onNext:function(a){b.call(this);var c=!1;0===this.requestedCount?this.enableQueue&&this.queue.push(a):(-1!==this.requestedCount&&0===this.requestedCount--&&this.disposeCurrentRequest(),c=!0),c&&this.subject.onNext(a)},_processRequest:function(a){if(this.enableQueue){for(;this.queue.length>=a&&a>0;)this.subject.onNext(this.queue.shift()),a--;return 0!==this.queue.length?{numberOfItems:a,returnValue:!0}:{numberOfItems:a,returnValue:!1}}return this.hasFailed?(this.subject.onError(this.error),this.controlledDisposable.dispose(),this.controlledDisposable=$b):this.hasCompleted&&(this.subject.onCompleted(),this.controlledDisposable.dispose(),this.controlledDisposable=$b),{numberOfItems:a,returnValue:!1}},request:function(a){b.call(this),this.disposeCurrentRequest();var c=this,d=this._processRequest(a);return a=d.numberOfItems,d.returnValue?$b:(this.requestedCount=a,this.requestedDisposable=Zb(function(){c.requestedCount=0}),this.requestedDisposable)},disposeCurrentRequest:function(){this.requestedDisposable.dispose(),this.requestedDisposable=$b},dispose:function(){this.isDisposed=!0,this.error=null,this.subject.dispose(),this.requestedDisposable.dispose()}}),d}(Bc);vc.multicast=function(a,b){var c=this;return"function"==typeof a?new hd(function(d){var e=c.multicast(a());return new Wb(b(e).subscribe(d),e.connect())}):new _c(c,a)},vc.publish=function(a){return a?this.multicast(function(){return new kd},a):this.multicast(new kd)},vc.share=function(){return this.publish(null).refCount()},vc.publishLast=function(a){return a?this.multicast(function(){return new ld},a):this.multicast(new ld)},vc.publishValue=function(a,b){return 2===arguments.length?this.multicast(function(){return new Zc(b)},a):this.multicast(new Zc(a))},vc.shareValue=function(a){return this.publishValue(a).refCount()},vc.replay=function(a,b,c,d){return a?this.multicast(function(){return new $c(b,c,d)},a):this.multicast(new $c(b,c,d))},vc.shareReplay=function(a,b,c){return this.replay(null,a,b,c).refCount()};var Yc=function(a,b){this.subject=a,this.observer=b};Yc.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1),this.observer=null}};var Zc=eb.BehaviorSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),a.onNext(this.value),new Yc(this,a);var c=this.exception;return c?a.onError(c):a.onCompleted(),$b}function d(b){a.call(this,c),this.value=b,this.observers=[],this.isDisposed=!1,this.isStopped=!1,this.exception=null}return Qb(d,a),Rb(d.prototype,tc,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped){this.value=a;for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)}},dispose:function(){this.isDisposed=!0,this.observers=null,this.value=null,this.exception=null}}),d}(Bc),$c=eb.ReplaySubject=function(a){function c(a,b){this.subject=a,this.observer=b}function d(a){var d=new zc(this.scheduler,a),e=new c(this,d);b.call(this),this._trim(this.scheduler.now()),this.observers.push(d);for(var f=this.q.length,g=0,h=this.q.length;h>g;g++)d.onNext(this.q[g].value);return this.hasError?(f++,d.onError(this.error)):this.isStopped&&(f++,d.onCompleted()),d.ensureActive(f),e}function e(b,c,e){this.bufferSize=null==b?Number.MAX_VALUE:b,this.windowSize=null==c?Number.MAX_VALUE:c,this.scheduler=e||hc,this.q=[],this.observers=[],this.isStopped=!1,this.isDisposed=!1,this.hasError=!1,this.error=null,a.call(this,d)}return c.prototype.dispose=function(){if(this.observer.dispose(),!this.subject.isDisposed){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1)}},Qb(e,a),Rb(e.prototype,tc,{hasObservers:function(){return this.observers.length>0},_trim:function(a){for(;this.q.length>this.bufferSize;)this.q.shift();for(;this.q.length>0&&a-this.q[0].interval>this.windowSize;)this.q.shift()},onNext:function(a){var c;if(b.call(this),!this.isStopped){var d=this.scheduler.now();this.q.push({interval:d,value:a}),this._trim(d);for(var e=this.observers.slice(0),f=0,g=e.length;g>f;f++)c=e[f],c.onNext(a),c.ensureActive()}},onError:function(a){var c;if(b.call(this),!this.isStopped){this.isStopped=!0,this.error=a,this.hasError=!0;var d=this.scheduler.now();this._trim(d);for(var e=this.observers.slice(0),f=0,g=e.length;g>f;f++)c=e[f],c.onError(a),c.ensureActive();this.observers=[]}},onCompleted:function(){var a;if(b.call(this),!this.isStopped){this.isStopped=!0;var c=this.scheduler.now();this._trim(c);for(var d=this.observers.slice(0),e=0,f=d.length;f>e;e++)a=d[e],a.onCompleted(),a.ensureActive();this.observers=[]}},dispose:function(){this.isDisposed=!0,this.observers=null}}),e}(Bc),_c=eb.ConnectableObservable=function(a){function b(b,c){var d,e=!1,f=b.asObservable();this.connect=function(){return e||(e=!0,d=new Wb(f.subscribe(c),Zb(function(){e=!1}))),d},a.call(this,c.subscribe.bind(c))}return Qb(b,a),b.prototype.refCount=function(){var a,b=0,c=this;return new hd(function(d){var e=1===++b,f=c.subscribe(d);return e&&(a=c.connect()),function(){f.dispose(),0===--b&&a.dispose()}})},b}(Bc),ad=function(){function b(a){if(a&!1)return 2===a;for(var b=Math.sqrt(a),c=3;b>=c;){if(a%c===0)return!1;c+=2}return!0}function c(a){var c,d,e;for(c=0;c=a)return d;for(e=1|a;ec;c++){var e=a.charCodeAt(c);b=(b<<5)-b+e,b&=b}return b}function e(a){var b=668265261;return a=61^a^a>>>16,a+=a<<3,a^=a>>>4,a*=b,a^=a>>>15}function f(){return{key:null,value:null,next:0,hashCode:0}}function g(a,b){if(0>a)throw new Error("out of range");a>0&&this._initialize(a),this.comparer=b||jb,this.freeCount=0,this.size=0,this.freeList=-1}var h=[1,3,7,13,31,61,127,251,509,1021,2039,4093,8191,16381,32749,65521,131071,262139,524287,1048573,2097143,4194301,8388593,16777213,33554393,67108859,134217689,268435399,536870909,1073741789,2147483647],i="no such key",j="duplicate key",k=function(){var a=0;return function(b){if(null==b)throw new Error(i);if("string"==typeof b)return d(b);if("number"==typeof b)return e(b);if("boolean"==typeof b)return b===!0?1:0;if(b instanceof Date)return e(b.valueOf());if(b instanceof RegExp)return d(b.toString());if("function"==typeof b.valueOf){var c=b.valueOf();if("number"==typeof c)return e(c);if("string"==typeof b)return d(c)}if(b.getHashCode)return b.getHashCode();var f=17*a++;return b.getHashCode=function(){return f},f}}(),l=g.prototype;return l._initialize=function(a){var b,d=c(a);for(this.buckets=new Array(d),this.entries=new Array(d),b=0;d>b;b++)this.buckets[b]=-1,this.entries[b]=f();this.freeList=-1},l.add=function(a,b){return this._insert(a,b,!0)},l._insert=function(a,b,c){this.buckets||this._initialize(0);for(var d,e=2147483647&k(a),f=e%this.buckets.length,g=this.buckets[f];g>=0;g=this.entries[g].next)if(this.entries[g].hashCode===e&&this.comparer(this.entries[g].key,a)){if(c)throw new Error(j);return void(this.entries[g].value=b)}this.freeCount>0?(d=this.freeList,this.freeList=this.entries[d].next,--this.freeCount):(this.size===this.entries.length&&(this._resize(),f=e%this.buckets.length),d=this.size,++this.size),this.entries[d].hashCode=e,this.entries[d].next=this.buckets[f],this.entries[d].key=a,this.entries[d].value=b,this.buckets[f]=d},l._resize=function(){var a=c(2*this.size),b=new Array(a);for(e=0;ee;++e)d[e]=f();for(var g=0;g=0;e=this.entries[e].next){if(this.entries[e].hashCode===b&&this.comparer(this.entries[e].key,a))return 0>d?this.buckets[c]=this.entries[e].next:this.entries[d].next=this.entries[e].next,this.entries[e].hashCode=-1,this.entries[e].next=this.freeList,this.entries[e].key=null,this.entries[e].value=null,this.freeList=e,++this.freeCount,!0;d=e}return!1},l.clear=function(){var a,b;if(!(this.size<=0)){for(a=0,b=this.buckets.length;b>a;++a)this.buckets[a]=-1;for(a=0;a=0;c=this.entries[c].next)if(this.entries[c].hashCode===b&&this.comparer(this.entries[c].key,a))return c;return-1},l.count=function(){return this.size-this.freeCount},l.tryGetValue=function(b){var c=this._findEntry(b);return c>=0?this.entries[c].value:a},l.getValues=function(){var a=0,b=[];if(this.entries)for(var c=0;c=0&&(b[a++]=this.entries[c].value);return b},l.get=function(a){var b=this._findEntry(a);if(b>=0)return this.entries[b].value;throw new Error(i)},l.set=function(a,b){this._insert(a,b,!1)},l.containskey=function(a){return this._findEntry(a)>=0},g}();vc.join=function(a,b,c,d){var e=this;return new hd(function(f){var g=new Wb,h=!1,i=!1,j=0,k=0,l=new ad,m=new ad;return g.add(e.subscribe(function(a){var c=j++,e=new _b;l.add(c,a),g.add(e);var i,k=function(){l.remove(c)&&0===l.count()&&h&&f.onCompleted(),g.remove(e)};try{i=b(a)}catch(n){return void f.onError(n)}e.setDisposable(i.take(1).subscribe(fb,f.onError.bind(f),k)),m.getValues().forEach(function(b){var c;try{c=d(a,b)}catch(e){return void f.onError(e)}f.onNext(c)})},f.onError.bind(f),function(){h=!0,(i||0===l.count())&&f.onCompleted()})),g.add(a.subscribe(function(a){var b=k++,e=new _b;m.add(b,a),g.add(e);var h,j=function(){m.remove(b)&&0===m.count()&&i&&f.onCompleted(),g.remove(e)};try{h=c(a)}catch(n){return void f.onError(n)}e.setDisposable(h.take(1).subscribe(fb,f.onError.bind(f),j)),l.getValues().forEach(function(b){var c;try{c=d(b,a)}catch(e){return void f.onError(e) +}f.onNext(c)})},f.onError.bind(f),function(){i=!0,(h||0===m.count())&&f.onCompleted()})),g})},vc.groupJoin=function(a,b,c,d){var e=this;return new hd(function(f){function g(a){return function(b){b.onError(a)}}var h=new Wb,i=new ac(h),j=new ad,k=new ad,l=0,m=0;return h.add(e.subscribe(function(a){var c=new kd,e=l++;j.add(e,c);var m;try{m=d(a,Sb(c,i))}catch(n){return j.getValues().forEach(g(n)),void f.onError(n)}f.onNext(m),k.getValues().forEach(function(a){c.onNext(a)});var o=new _b;h.add(o);var p,q=function(){j.remove(e)&&c.onCompleted(),h.remove(o)};try{p=b(a)}catch(n){return j.getValues().forEach(g(n)),void f.onError(n)}o.setDisposable(p.take(1).subscribe(fb,function(a){j.getValues().forEach(g(a)),f.onError(a)},q))},function(a){j.getValues().forEach(g(a)),f.onError(a)},f.onCompleted.bind(f))),h.add(a.subscribe(function(a){var b=m++;k.add(b,a);var d=new _b;h.add(d);var e,i=function(){k.remove(b),h.remove(d)};try{e=c(a)}catch(l){return j.getValues().forEach(g(l)),void f.onError(l)}d.setDisposable(e.take(1).subscribe(fb,function(a){j.getValues().forEach(g(a)),f.onError(a)},i)),j.getValues().forEach(function(b){b.onNext(a)})},function(a){j.getValues().forEach(g(a)),f.onError(a)})),i})},vc.buffer=function(){return this.window.apply(this,arguments).selectMany(function(a){return a.toArray()})},vc.window=function(a,b){return 1===arguments.length&&"function"!=typeof arguments[0]?M.call(this,a):"function"==typeof a?N.call(this,a):L.call(this,a,b)},vc.pairwise=function(){var a=this;return new hd(function(b){var c,d=!1;return a.subscribe(function(a){d?b.onNext([c,a]):d=!0,c=a},b.onError.bind(b),b.onCompleted.bind(b))})},vc.partition=function(a,b){var c=this.publish().refCount();return[c.filter(a,b),c.filter(function(c,d,e){return!a.call(b,c,d,e)})]},vc.letBind=vc.let=function(a){return a(this)},Bc["if"]=Bc.ifThen=function(a,b,c){return Dc(function(){return c||(c=Ec()),mb(b)&&(b=Cc(b)),mb(c)&&(c=Cc(c)),"function"==typeof c.now&&(c=Ec(c)),a()?b:c})},Bc["for"]=Bc.forIn=function(a,b){return sc(a,b).concat()};var bd=Bc["while"]=Bc.whileDo=function(a,b){return mb(b)&&(b=Cc(b)),O(a,b).concat()};vc.doWhile=function(a){return Mc([this,bd(a,this)])},Bc["case"]=Bc.switchCase=function(a,b,c){return Dc(function(){mb(c)&&(c=Cc(c)),c||(c=Ec()),"function"==typeof c.now&&(c=Ec(c));var d=b[a()];return mb(d)&&(d=Cc(d)),d||c})},vc.expand=function(a,b){gb(b)||(b=gc);var c=this;return new hd(function(d){var e=[],f=new SerialDisposable,g=new Wb(f),h=0,i=!1,j=function(){var c=!1;e.length>0&&(c=!i,i=!0),c&&f.setDisposable(b.scheduleRecursive(function(b){var c;if(!(e.length>0))return void(i=!1);c=e.shift();var f=new _b;g.add(f),f.setDisposable(c.subscribe(function(b){d.onNext(b);var c=null;try{c=a(b)}catch(f){d.onError(f)}e.push(c),h++,j()},d.onError.bind(d),function(){g.remove(f),h--,0===h&&d.onCompleted()})),b()}))};return e.push(c),h++,j(),g})},Bc.forkJoin=function(){var a=k(arguments,0);return new hd(function(b){var c=a.length;if(0===c)return b.onCompleted(),$b;for(var d=new Wb,e=!1,f=new Array(c),g=new Array(c),h=new Array(c),i=0;c>i;i++)!function(i){var j=a[i];mb(j)&&(j=Cc(j)),d.add(j.subscribe(function(a){e||(f[i]=!0,h[i]=a)},function(a){e=!0,b.onError(a),d.dispose()},function(){if(!e){if(!f[i])return void b.onCompleted();g[i]=!0;for(var a=0;c>a;a++)if(!g[a])return;e=!0,b.onNext(h),b.onCompleted()}}))}(i);return d})},vc.forkJoin=function(a,b){var c=this;return new hd(function(d){var e,f,g=!1,h=!1,i=!1,j=!1,k=new _b,l=new _b;return mb(a)&&(a=Cc(a)),k.setDisposable(c.subscribe(function(a){i=!0,e=a},function(a){l.dispose(),d.onError(a)},function(){if(g=!0,h)if(i)if(j){var a;try{a=b(e,f)}catch(c){return void d.onError(c)}d.onNext(a),d.onCompleted()}else d.onCompleted();else d.onCompleted()})),l.setDisposable(a.subscribe(function(a){j=!0,f=a},function(a){k.dispose(),d.onError(a)},function(){if(h=!0,g)if(i)if(j){var a;try{a=b(e,f)}catch(c){return void d.onError(c)}d.onNext(a),d.onCompleted()}else d.onCompleted();else d.onCompleted()})),new Wb(k,l)})},vc.manySelect=function(a,b){gb(b)||(b=gc);var c=this;return Dc(function(){var d;return c.map(function(a){var b=new cd(a);return d&&d.onNext(a),d=b,b}).tap(fb,function(a){d&&d.onError(a)},function(){d&&d.onCompleted()}).observeOn(b).map(a)})};var cd=function(a){function b(a){var b=this,c=new Wb;return c.add(hc.schedule(function(){a.onNext(b.head),c.add(b.tail.mergeObservable().subscribe(a))})),c}function c(c){a.call(this,b),this.head=c,this.tail=new ld}return Qb(c,a),Rb(c.prototype,tc,{onCompleted:function(){this.onNext(Bc.empty())},onError:function(a){this.onNext(Bc.throwException(a))},onNext:function(a){this.tail.onNext(a),this.tail.onCompleted()}}),c}(Bc),dd=function(){function a(){this.keys=[],this.values=[]}return a.prototype["delete"]=function(a){var b=this.keys.indexOf(a);return-1!==b&&(this.keys.splice(b,1),this.values.splice(b,1)),-1!==b},a.prototype.get=function(a,b){var c=this.keys.indexOf(a);return-1!==c?this.values[c]:b},a.prototype.set=function(a,b){var c=this.keys.indexOf(a);-1!==c&&(this.values[c]=b),this.values[this.keys.push(a)-1]=b},a.prototype.size=function(){return this.keys.length},a.prototype.has=function(a){return-1!==this.keys.indexOf(a)},a.prototype.getKeys=function(){return this.keys.slice(0)},a.prototype.getValues=function(){return this.values.slice(0)},a}();P.prototype.and=function(a){var b=this.patterns.slice(0);return b.push(a),new P(b)},P.prototype.thenDo=function(a){return new Q(this,a)},Q.prototype.activate=function(a,b,c){for(var d=this,e=[],f=0,g=this.expression.patterns.length;g>f;f++)e.push(R(a,this.expression.patterns[f],b.onError.bind(b)));var h=new S(e,function(){var a;try{a=d.selector.apply(d,arguments)}catch(c){return void b.onError(c)}b.onNext(a)},function(){for(var a=0,b=e.length;b>a;a++)e[a].removeActivePlan(h);c(h)});for(f=0,g=e.length;g>f;f++)e[f].addActivePlan(h);return h},S.prototype.dequeue=function(){for(var a=this.joinObservers.getValues(),b=0,c=a.length;c>b;b++)a[b].queue.shift()},S.prototype.match=function(){var a,b,c,d,e,f=!0;for(b=0,c=this.joinObserverArray.length;c>b;b++)if(0===this.joinObserverArray[b].queue.length){f=!1;break}if(f){for(a=[],d=!1,b=0,c=this.joinObserverArray.length;c>b;b++)a.push(this.joinObserverArray[b].queue[0]),"C"===this.joinObserverArray[b].queue[0].kind&&(d=!0);if(d)this.onCompleted();else{for(this.dequeue(),e=[],b=0;bc;c++)b[c].match()}},c.error=fb,c.completed=fb,c.addActivePlan=function(a){this.activePlans.push(a)},c.subscribe=function(){this.subscription.setDisposable(this.source.materialize().subscribe(this))},c.removeActivePlan=function(a){var b=this.activePlans.indexOf(a);this.activePlans.splice(b,1),0===this.activePlans.length&&this.dispose()},c.dispose=function(){a.prototype.dispose.call(this),this.isDisposed||(this.isDisposed=!0,this.subscription.dispose())},b}(wc);vc.and=function(a){return new P([this,a])},vc.thenDo=function(a){return new P([this]).thenDo(a)},Bc.when=function(){var a=k(arguments,0);return new hd(function(b){var c,d,e,f,g,h,i=[],j=new dd;h=uc(b.onNext.bind(b),function(a){for(var c=j.getValues(),d=0,e=c.length;e>d;d++)c[d].onError(a);b.onError(a)},b.onCompleted.bind(b));try{for(d=0,e=a.length;e>d;d++)i.push(a[d].activate(j,h,function(a){var b=i.indexOf(a);i.splice(b,1),0===i.length&&h.onCompleted()}))}catch(k){Jc(k).subscribe(b)}for(c=new Wb,g=j.getValues(),d=0,e=g.length;e>d;d++)f=g[d],f.subscribe(),c.add(f);return c})};var fd=Bc.interval=function(a,b){return W(a,a,gb(b)?b:jc)},gd=Bc.timer=function(b,c,d){var e;return gb(d)||(d=jc),c!==a&&"number"==typeof c?e=c:c!==a&&"object"==typeof c&&(d=c),b instanceof Date&&e===a?T(b.getTime(),d):b instanceof Date&&e!==a?(e=c,U(b.getTime(),e,d)):e===a?V(b,d):W(b,e,d)};vc.delay=function(a,b){return gb(b)||(b=jc),a instanceof Date?Y(this,a.getTime(),b):X(this,a,b)},vc.throttle=function(a,b){return gb(b)||(b=jc),this.throttleWithSelector(function(){return gd(a,b)})},vc.windowWithTime=function(a,b,c){var d,e=this;return null==b&&(d=a),gb(c)||(c=jc),"number"==typeof b?d=b:"object"==typeof b&&(d=a,c=b),new hd(function(b){function f(){var a=new _b,e=!1,g=!1;l.setDisposable(a),j===i?(e=!0,g=!0):i>j?e=!0:g=!0;var n=e?j:i,o=n-m;m=n,e&&(j+=d),g&&(i+=d),a.setDisposable(c.scheduleWithRelative(o,function(){var a;g&&(a=new kd,k.push(a),b.onNext(Sb(a,h))),e&&(a=k.shift(),a.onCompleted()),f()}))}var g,h,i=d,j=a,k=[],l=new SerialDisposable,m=0;return g=new Wb(l),h=new ac(g),k.push(new kd),b.onNext(Sb(k[0],h)),f(),g.add(e.subscribe(function(a){var b,c;for(b=0,c=k.length;c>b;b++)k[b].onNext(a)},function(a){var c,d;for(c=0,d=k.length;d>c;c++)k[c].onError(a);b.onError(a)},function(){var a,c;for(a=0,c=k.length;c>a;a++)k[a].onCompleted();b.onCompleted()})),h})},vc.windowWithTimeOrCount=function(a,b,c){var d=this;return gb(c)||(c=jc),new hd(function(e){function f(b){var d=new _b;timerD.setDisposable(d),d.setDisposable(c.scheduleWithRelative(a,function(){var a;b===windowId&&(i=0,a=++windowId,j.onCompleted(),j=new kd,e.onNext(Sb(j,h)),f(a))}))}var f,g,h,i=0,j=new kd;return timerD=new SerialDisposable,windowId=0,g=new Wb(timerD),h=new ac(g),e.onNext(Sb(j,h)),f(0),g.add(d.subscribe(function(a){var c=0,d=!1;j.onNext(a),i++,i===b&&(d=!0,i=0,c=++windowId,j.onCompleted(),j=new kd,e.onNext(Sb(j,h))),d&&f(c)},function(a){j.onError(a),e.onError(a)},function(){j.onCompleted(),e.onCompleted()})),h})},vc.bufferWithTime=function(){return this.windowWithTime.apply(this,arguments).selectMany(function(a){return a.toArray()})},vc.bufferWithTimeOrCount=function(a,b,c){return this.windowWithTimeOrCount(a,b,c).selectMany(function(a){return a.toArray()})},vc.timeInterval=function(a){var b=this;return gb(a)||(a=jc),Dc(function(){var c=a.now();return b.map(function(b){var d=a.now(),e=d-c;return c=d,{value:b,interval:e}})})},vc.timestamp=function(a){return gb(a)||(a=jc),this.map(function(b){return{value:b,timestamp:a.now()}})},vc.sample=function(a,b){return gb(b)||(b=jc),"number"==typeof a?Z(this,fd(a,b)):Z(this,a)},vc.timeout=function(a,b,c){b||(b=Jc(new Error("Timeout"))),gb(c)||(c=jc);var d=this,e=a instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new hd(function(f){var g=0,h=new _b,i=new SerialDisposable,j=!1,k=new SerialDisposable;i.setDisposable(h);var l=function(){var d=g;k.setDisposable(c[e](a,function(){g===d&&(mb(b)&&(b=Cc(b)),i.setDisposable(b.subscribe(f)))}))};return l(),h.setDisposable(d.subscribe(function(a){j||(g++,f.onNext(a),l())},function(a){j||(g++,f.onError(a))},function(){j||(g++,f.onCompleted())})),new Wb(i,k)})},Bc.generateWithAbsoluteTime=function(a,b,c,d,e,f){return gb(f)||(f=jc),new hd(function(g){var h,i,j=!0,k=!1,l=a;return f.scheduleRecursiveWithAbsolute(f.now(),function(a){k&&g.onNext(h);try{j?j=!1:l=c(l),k=b(l),k&&(h=d(l),i=e(l))}catch(f){return void g.onError(f)}k?a(i):g.onCompleted()})})},Bc.generateWithRelativeTime=function(a,b,c,d,e,f){return gb(f)||(f=jc),new hd(function(g){var h,i,j=!0,k=!1,l=a;return f.scheduleRecursiveWithRelative(0,function(a){k&&g.onNext(h);try{j?j=!1:l=c(l),k=b(l),k&&(h=d(l),i=e(l))}catch(f){return void g.onError(f)}k?a(i):g.onCompleted()})})},vc.delaySubscription=function(a,b){return this.delayWithSelector(gd(a,gb(b)?b:jc),Ec)},vc.delayWithSelector=function(a,b){var c,d,e=this;return"function"==typeof a?d=a:(c=a,d=b),new hd(function(a){var b=new Wb,f=!1,g=function(){f&&0===b.length&&a.onCompleted()},h=new SerialDisposable,i=function(){h.setDisposable(e.subscribe(function(c){var e;try{e=d(c)}catch(f){return void a.onError(f)}var h=new _b;b.add(h),h.setDisposable(e.subscribe(function(){a.onNext(c),b.remove(h),g()},a.onError.bind(a),function(){a.onNext(c),b.remove(h),g()}))},a.onError.bind(a),function(){f=!0,h.dispose(),g()}))};return c?h.setDisposable(c.subscribe(function(){i()},a.onError.bind(a),function(){i()})):i(),new Wb(h,b)})},vc.timeoutWithSelector=function(a,b,c){if(1===arguments.length){b=a;var a=Hc()}c||(c=Jc(new Error("Timeout")));var d=this;return new hd(function(e){var f=new SerialDisposable,g=new SerialDisposable,h=new _b;f.setDisposable(h);var i=0,j=!1,k=function(a){var b=i,d=function(){return i===b},h=new _b;g.setDisposable(h),h.setDisposable(a.subscribe(function(){d()&&f.setDisposable(c.subscribe(e)),h.dispose()},function(a){d()&&e.onError(a)},function(){d()&&f.setDisposable(c.subscribe(e))}))};k(a);var l=function(){var a=!j;return a&&i++,a};return h.setDisposable(d.subscribe(function(a){if(l()){e.onNext(a);var c;try{c=b(a)}catch(d){return void e.onError(d)}k(c)}},function(a){l()&&e.onError(a)},function(){l()&&e.onCompleted()})),new Wb(f,g)})},vc.throttleWithSelector=function(a){var b=this;return new hd(function(c){var d,e=!1,f=new SerialDisposable,g=0,h=b.subscribe(function(b){var h;try{h=a(b)}catch(i){return void c.onError(i)}e=!0,d=b,g++;var j=g,k=new _b;f.setDisposable(k),k.setDisposable(h.subscribe(function(){e&&g===j&&c.onNext(d),e=!1,k.dispose()},c.onError.bind(c),function(){e&&g===j&&c.onNext(d),e=!1,k.dispose()}))},function(a){f.dispose(),c.onError(a),e=!1,g++},function(){f.dispose(),e&&c.onNext(d),c.onCompleted(),e=!1,g++});return new Wb(h,f)})},vc.skipLastWithTime=function(a,b){gb(b)||(b=jc);var c=this;return new hd(function(d){var e=[];return c.subscribe(function(c){var f=b.now();for(e.push({interval:f,value:c});e.length>0&&f-e[0].interval>=a;)d.onNext(e.shift().value)},d.onError.bind(d),function(){for(var c=b.now();e.length>0&&c-e[0].interval>=a;)d.onNext(e.shift().value);d.onCompleted()})})},vc.takeLastWithTime=function(a,b){var c=this;return gb(b)||(b=jc),new hd(function(d){var e=[];return c.subscribe(function(c){var d=b.now();for(e.push({interval:d,value:c});e.length>0&&d-e[0].interval>=a;)e.shift()},d.onError.bind(d),function(){for(var c=b.now();e.length>0;){var f=e.shift();c-f.interval<=a&&d.onNext(f.value)}d.onCompleted()})})},vc.takeLastBufferWithTime=function(a,b){var c=this;return gb(b)||(b=jc),new hd(function(d){var e=[];return c.subscribe(function(c){var d=b.now();for(e.push({interval:d,value:c});e.length>0&&d-e[0].interval>=a;)e.shift()},d.onError.bind(d),function(){for(var c=b.now(),f=[];e.length>0;){var g=e.shift();c-g.interval<=a&&f.push(g.value)}d.onNext(f),d.onCompleted()})})},vc.takeWithTime=function(a,b){var c=this;return gb(b)||(b=jc),new hd(function(d){return new Wb(b.scheduleWithRelative(a,d.onCompleted.bind(d)),c.subscribe(d))})},vc.skipWithTime=function(a,b){var c=this;return gb(b)||(b=jc),new hd(function(d){var e=!1;return new Wb(b.scheduleWithRelative(a,function(){e=!0}),c.subscribe(function(a){e&&d.onNext(a)},d.onError.bind(d),d.onCompleted.bind(d)))})},vc.skipUntilWithTime=function(a,b){gb(b)||(b=jc);var c=this,d=a instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new hd(function(e){var f=!1;return new Wb(b[d](a,function(){f=!0}),c.subscribe(function(a){f&&e.onNext(a)},e.onError.bind(e),e.onCompleted.bind(e)))})},vc.takeUntilWithTime=function(a,b){gb(b)||(b=jc);var c=this,d=a instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new hd(function(e){return new Wb(b[d](a,function(){e.onCompleted()}),c.subscribe(e))})},vc.exclusive=function(){var a=this;return new hd(function(b){var c=!1,d=!1,e=new _b,f=new Wb;return f.add(e),e.setDisposable(a.subscribe(function(a){if(!c){c=!0,mb(a)&&(a=Cc(a));var e=new _b;f.add(e),e.setDisposable(a.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){f.remove(e),c=!1,d&&1===f.length&&b.onCompleted()}))}},b.onError.bind(b),function(){d=!0,c||1!==f.length||b.onCompleted()})),f})},vc.exclusiveMap=function(a,b){var c=this;return new hd(function(d){var e=0,f=!1,g=!0,h=new _b,i=new Wb;return i.add(h),h.setDisposable(c.subscribe(function(c){f||(f=!0,innerSubscription=new _b,i.add(innerSubscription),mb(c)&&(c=Cc(c)),innerSubscription.setDisposable(c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}d.onNext(g)},d.onError.bind(d),function(){i.remove(innerSubscription),f=!1,g&&1===i.length&&d.onCompleted()})))},d.onError.bind(d),function(){g=!0,1!==i.length||f||d.onCompleted()})),i})},eb.VirtualTimeScheduler=function(a){function b(){throw new Error("Not implemented")}function c(){return this.toDateTimeOffset(this.clock)}function d(a,b){return this.scheduleAbsoluteWithState(a,this.clock,b)}function e(a,b,c){return this.scheduleRelativeWithState(a,this.toRelative(b),c)}function f(a,b,c){return this.scheduleRelativeWithState(a,this.toRelative(b-this.now()),c)}function g(a,b){return b(),$b}function h(b,g){this.clock=b,this.comparer=g,this.isEnabled=!1,this.queue=new Ub(1024),a.call(this,c,d,e,f)}Qb(h,a);var i=h.prototype;return i.add=b,i.toDateTimeOffset=b,i.toRelative=b,i.schedulePeriodicWithState=function(a,b,c){var d=new fc(this,a,b,c);return d.start()},i.scheduleRelativeWithState=function(a,b,c){var d=this.add(this.clock,b);return this.scheduleAbsoluteWithState(a,d,c)},i.scheduleRelative=function(a,b){return this.scheduleRelativeWithState(b,a,g)},i.start=function(){if(!this.isEnabled){this.isEnabled=!0;do{var a=this.getNext();null!==a?(this.comparer(a.dueTime,this.clock)>0&&(this.clock=a.dueTime),a.invoke()):this.isEnabled=!1}while(this.isEnabled)}},i.stop=function(){this.isEnabled=!1},i.advanceTo=function(a){var b=this.comparer(this.clock,a);if(this.comparer(this.clock,a)>0)throw new Error(pb);if(0!==b&&!this.isEnabled){this.isEnabled=!0;do{var c=this.getNext();null!==c&&this.comparer(c.dueTime,a)<=0?(this.comparer(c.dueTime,this.clock)>0&&(this.clock=c.dueTime),c.invoke()):this.isEnabled=!1}while(this.isEnabled);this.clock=a}},i.advanceBy=function(a){var b=this.add(this.clock,a),c=this.comparer(this.clock,b);if(c>0)throw new Error(pb);0!==c&&this.advanceTo(b)},i.sleep=function(a){var b=this.add(this.clock,a);if(this.comparer(this.clock,b)>=0)throw new Error(pb);this.clock=b},i.getNext=function(){for(;this.queue.length>0;){var a=this.queue.peek();if(!a.isCancelled())return a;this.queue.dequeue()}return null},i.scheduleAbsolute=function(a,b){return this.scheduleAbsoluteWithState(b,a,g)},i.scheduleAbsoluteWithState=function(a,b,c){function d(a,b){return e.queue.remove(f),c(a,b)}var e=this,f=new bc(this,a,d,b,this.comparer);return this.queue.enqueue(f),f.disposable},h}(cc),eb.HistoricalScheduler=function(a){function b(b,c){var d=null==b?0:b,e=c||kb;a.call(this,d,e)}Qb(b,a);var c=b.prototype;return c.add=function(a,b){return a+b},c.toDateTimeOffset=function(a){return new Date(a).getTime()},c.toRelative=function(a){return a},b}(eb.VirtualTimeScheduler);var hd=eb.AnonymousObservable=function(a){function b(a){return a&&"function"==typeof a.dispose?a:"function"==typeof a?Zb(a):$b}function c(d){function e(a){var c=function(){try{e.setDisposable(b(d(e)))}catch(a){if(!e.fail(a))throw a}},e=new id(a);return hc.scheduleRequired()?hc.schedule(c):c(),e}return this instanceof c?void a.call(this,e):new c(d)}return Qb(c,a),c}(Bc),id=function(a){function b(b){a.call(this),this.observer=b,this.m=new _b}Qb(b,a);var c=b.prototype;return c.next=function(a){var b=!1;try{this.observer.onNext(a),b=!0}catch(c){throw c}finally{b||this.dispose()}},c.error=function(a){try{this.observer.onError(a)}catch(b){throw b}finally{this.dispose()}},c.completed=function(){try{this.observer.onCompleted()}catch(a){throw a}finally{this.dispose()}},c.setDisposable=function(a){this.m.setDisposable(a)},c.getDisposable=function(){return this.m.getDisposable()},c.disposable=function(a){return arguments.length?this.getDisposable():setDisposable(a)},c.dispose=function(){a.prototype.dispose.call(this),this.m.dispose()},b}(wc),jd=function(a){function b(a){return this.underlyingObservable.subscribe(a)}function c(c,d,e){a.call(this,b),this.key=c,this.underlyingObservable=e?new hd(function(a){return new Wb(e.getDisposable(),d.subscribe(a))}):d}return Qb(c,a),c}(Bc),kd=eb.Subject=function(a){function c(a){return b.call(this),this.isStopped?this.exception?(a.onError(this.exception),$b):(a.onCompleted(),$b):(this.observers.push(a),new Yc(this,a))}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return Qb(d,a),Rb(d.prototype,tc,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped)for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)},dispose:function(){this.isDisposed=!0,this.observers=null}}),d.create=function(a,b){return new md(a,b)},d}(Bc),ld=eb.AsyncSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),new Yc(this,a);var c=this.exception,d=this.hasValue,e=this.value;return c?a.onError(c):d?(a.onNext(e),a.onCompleted()):a.onCompleted(),$b}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return Qb(d,a),Rb(d.prototype,tc,{hasObservers:function(){return b.call(this),this.observers.length>0},onCompleted:function(){var a,c,d;if(b.call(this),!this.isStopped){this.isStopped=!0;var e=this.observers.slice(0),f=this.value,g=this.hasValue;if(g)for(c=0,d=e.length;d>c;c++)a=e[c],a.onNext(f),a.onCompleted();else for(c=0,d=e.length;d>c;c++)e[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){b.call(this),this.isStopped||(this.value=a,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),d}(Bc),md=eb.AnonymousSubject=function(a){function b(b,c){this.observer=b,this.observable=c,a.call(this,this.observable.subscribe.bind(this.observable))}return Qb(b,a),Rb(b.prototype,tc,{onCompleted:function(){this.observer.onCompleted()},onError:function(a){this.observer.onError(a)},onNext:function(a){this.observer.onNext(a)}}),b}(Bc);"function"==typeof define&&"object"==typeof define.amd&&define.amd?(_.Rx=eb,define(function(){return eb})):ab&&bb?cb?(bb.exports=eb).Rx=eb:ab.Rx=eb:_.Rx=eb}).call(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.async.compat.js b/ajax/libs/rxjs/2.3.9/rx.async.compat.js new file mode 100644 index 000000000..3dcf5045e --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.async.compat.js @@ -0,0 +1,413 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx.binding', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // Aliases + var Observable = Rx.Observable, + observableProto = Observable.prototype, + observableFromPromise = Observable.fromPromise, + observableThrow = Observable.throwException, + AnonymousObservable = Rx.AnonymousObservable, + AsyncSubject = Rx.AsyncSubject, + disposableCreate = Rx.Disposable.create, + CompositeDisposable= Rx.CompositeDisposable, + immediateScheduler = Rx.Scheduler.immediate, + timeoutScheduler = Rx.Scheduler.timeout, + isScheduler = Rx.helpers.isScheduler, + slice = Array.prototype.slice; + + /** + * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. + * + * @example + * var res = Rx.Observable.start(function () { console.log('hello'); }); + * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); + * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); + * + * @param {Function} func Function to run asynchronously. + * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @returns {Observable} An observable sequence exposing the function's result value, or an exception. + * + * Remarks + * * The function is called immediately, not during the subscription of the resulting sequence. + * * Multiple subscriptions to the resulting sequence can observe the function's result. + */ + Observable.start = function (func, context, scheduler) { + return observableToAsync(func, context, scheduler)(); + }; + + /** + * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. + * + * @example + * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); + * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); + * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); + * + * @param {Function} function Function to convert to an asynchronous function. + * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @returns {Function} Asynchronous function. + */ + var observableToAsync = Observable.toAsync = function (func, context, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return function () { + var args = arguments, + subject = new AsyncSubject(); + + scheduler.schedule(function () { + var result; + try { + result = func.apply(context, args); + } catch (e) { + subject.onError(e); + return; + } + subject.onNext(result); + subject.onCompleted(); + }); + return subject.asObservable(); + }; + }; + + /** + * Converts a callback function to an observable sequence. + * + * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. + * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. + * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. + */ + Observable.fromCallback = function (func, context, selector) { + return function () { + var args = slice.call(arguments, 0); + + return new AnonymousObservable(function (observer) { + function handler(e) { + var results = e; + + if (selector) { + try { + results = selector(arguments); + } catch (err) { + observer.onError(err); + return; + } + + observer.onNext(results); + } else { + if (results.length <= 1) { + observer.onNext.apply(observer, results); + } else { + observer.onNext(results); + } + } + + observer.onCompleted(); + } + + args.push(handler); + func.apply(context, args); + }).publishLast().refCount(); + }; + }; + + /** + * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. + * @param {Function} func The function to call + * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. + * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. + */ + Observable.fromNodeCallback = function (func, context, selector) { + return function () { + var args = slice.call(arguments, 0); + + return new AnonymousObservable(function (observer) { + function handler(err) { + if (err) { + observer.onError(err); + return; + } + + var results = slice.call(arguments, 1); + + if (selector) { + try { + results = selector(results); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(results); + } else { + if (results.length <= 1) { + observer.onNext.apply(observer, results); + } else { + observer.onNext(results); + } + } + + observer.onCompleted(); + } + + args.push(handler); + func.apply(context, args); + }).publishLast().refCount(); + }; + }; + + function fixEvent(event) { + var stopPropagation = function () { + this.cancelBubble = true; + }; + + var preventDefault = function () { + this.bubbledKeyCode = this.keyCode; + if (this.ctrlKey) { + try { + this.keyCode = 0; + } catch (e) { } + } + this.defaultPrevented = true; + this.returnValue = false; + this.modified = true; + }; + + event || (event = root.event); + if (!event.target) { + event.target = event.target || event.srcElement; + + if (event.type == 'mouseover') { + event.relatedTarget = event.fromElement; + } + if (event.type == 'mouseout') { + event.relatedTarget = event.toElement; + } + // Adding stopPropogation and preventDefault to IE + if (!event.stopPropagation){ + event.stopPropagation = stopPropagation; + event.preventDefault = preventDefault; + } + // Normalize key events + switch(event.type){ + case 'keypress': + var c = ('charCode' in event ? event.charCode : event.keyCode); + if (c == 10) { + c = 0; + event.keyCode = 13; + } else if (c == 13 || c == 27) { + c = 0; + } else if (c == 3) { + c = 99; + } + event.charCode = c; + event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; + break; + } + } + + return event; + } + + function createListener (element, name, handler) { + // Standards compliant + if (element.addEventListener) { + element.addEventListener(name, handler, false); + return disposableCreate(function () { + element.removeEventListener(name, handler, false); + }); + } + if (element.attachEvent) { + // IE Specific + var innerHandler = function (event) { + handler(fixEvent(event)); + }; + element.attachEvent('on' + name, innerHandler); + return disposableCreate(function () { + element.detachEvent('on' + name, innerHandler); + }); + } + // Level 1 DOM Events + element['on' + name] = handler; + return disposableCreate(function () { + element['on' + name] = null; + }); + } + + function createEventListener (el, eventName, handler) { + var disposables = new CompositeDisposable(); + + // Asume NodeList + if (Object.prototype.toString.call(el) === '[object NodeList]') { + for (var i = 0, len = el.length; i < len; i++) { + disposables.add(createEventListener(el.item(i), eventName, handler)); + } + } else if (el) { + disposables.add(createListener(el, eventName, handler)); + } + + return disposables; + } + + /** + * Configuration option to determine whether to use native events only + */ + Rx.config.useNativeEvents = false; + + // Check for Angular/jQuery/Zepto support + var jq = + !!root.angular && !!angular.element ? angular.element : + (!!root.jQuery ? root.jQuery : ( + !!root.Zepto ? root.Zepto : null)); + + // Check for ember + var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; + + // Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs + // for proper loading order! + var marionette = !!root.Backbone && !!root.Backbone.Marionette; + + /** + * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. + * + * @example + * var source = Rx.Observable.fromEvent(element, 'mouseup'); + * + * @param {Object} element The DOMElement or NodeList to attach a listener. + * @param {String} eventName The event name to attach the observable sequence. + * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. + * @returns {Observable} An observable sequence of events from the specified element and the specified event. + */ + Observable.fromEvent = function (element, eventName, selector) { + // Node.js specific + if (element.addListener) { + return fromEventPattern( + function (h) { element.addListener(eventName, h); }, + function (h) { element.removeListener(eventName, h); }, + selector); + } + + // Use only if non-native events are allowed + if (!Rx.config.useNativeEvents) { + if (marionette) { + return fromEventPattern( + function (h) { element.on(eventName, h); }, + function (h) { element.off(eventName, h); }, + selector); + } + if (ember) { + return fromEventPattern( + function (h) { Ember.addListener(element, eventName, h); }, + function (h) { Ember.removeListener(element, eventName, h); }, + selector); + } + if (jq) { + var $elem = jq(element); + return fromEventPattern( + function (h) { $elem.on(eventName, h); }, + function (h) { $elem.off(eventName, h); }, + selector); + } + } + return new AnonymousObservable(function (observer) { + return createEventListener( + element, + eventName, + function handler (e) { + var results = e; + + if (selector) { + try { + results = selector(arguments); + } catch (err) { + observer.onError(err); + return + } + } + + observer.onNext(results); + }); + }).publish().refCount(); + }; + + /** + * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. + * @param {Function} addHandler The function to add a handler to the emitter. + * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. + * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. + * @returns {Observable} An observable sequence which wraps an event from an event emitter + */ + var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { + return new AnonymousObservable(function (observer) { + function innerHandler (e) { + var result = e; + if (selector) { + try { + result = selector(arguments); + } catch (err) { + observer.onError(err); + return; + } + } + observer.onNext(result); + } + + var returnValue = addHandler(innerHandler); + return disposableCreate(function () { + if (removeHandler) { + removeHandler(innerHandler, returnValue); + } + }); + }).publish().refCount(); + }; + + /** + * Invokes the asynchronous function, surfacing the result through an observable sequence. + * @param {Function} functionAsync Asynchronous function which returns a Promise to run. + * @returns {Observable} An observable sequence exposing the function's result value, or an exception. + */ + Observable.startAsync = function (functionAsync) { + var promise; + try { + promise = functionAsync(); + } catch (e) { + return observableThrow(e); + } + return observableFromPromise(promise); + } + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.async.compat.min.js b/ajax/libs/rxjs/2.3.9/rx.async.compat.min.js new file mode 100644 index 000000000..2e54ab81e --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.async.compat.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx.binding","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c){function d(b){var c=function(){this.cancelBubble=!0},d=function(){if(this.bubbledKeyCode=this.keyCode,this.ctrlKey)try{this.keyCode=0}catch(a){}this.defaultPrevented=!0,this.returnValue=!1,this.modified=!0};if(b||(b=a.event),!b.target)switch(b.target=b.target||b.srcElement,"mouseover"==b.type&&(b.relatedTarget=b.fromElement),"mouseout"==b.type&&(b.relatedTarget=b.toElement),b.stopPropagation||(b.stopPropagation=c,b.preventDefault=d),b.type){case"keypress":var e="charCode"in b?b.charCode:b.keyCode;10==e?(e=0,b.keyCode=13):13==e||27==e?e=0:3==e&&(e=99),b.charCode=e,b.keyChar=b.charCode?String.fromCharCode(b.charCode):""}return b}function e(a,b,c){if(a.addEventListener)return a.addEventListener(b,c,!1),l(function(){a.removeEventListener(b,c,!1)});if(a.attachEvent){var e=function(a){c(d(a))};return a.attachEvent("on"+b,e),l(function(){a.detachEvent("on"+b,e)})}return a["on"+b]=c,l(function(){a["on"+b]=null})}function f(a,b,c){var d=new m;if("[object NodeList]"===Object.prototype.toString.call(a))for(var g=0,h=a.length;h>g;g++)d.add(f(a.item(g),b,c));else a&&d.add(e(a,b,c));return d}var g=c.Observable,h=(g.prototype,g.fromPromise),i=g.throwException,j=c.AnonymousObservable,k=c.AsyncSubject,l=c.Disposable.create,m=c.CompositeDisposable,n=(c.Scheduler.immediate,c.Scheduler.timeout),o=c.helpers.isScheduler,p=Array.prototype.slice;g.start=function(a,b,c){return q(a,b,c)()};var q=g.toAsync=function(a,b,c){return o(c)||(c=n),function(){var d=arguments,e=new k;return c.schedule(function(){var c;try{c=a.apply(b,d)}catch(f){return void e.onError(f)}e.onNext(c),e.onCompleted()}),e.asObservable()}};g.fromCallback=function(a,b,c){return function(){var d=p.call(arguments,0);return new j(function(e){function f(a){var b=a;if(c){try{b=c(arguments)}catch(d){return void e.onError(d)}e.onNext(b)}else b.length<=1?e.onNext.apply(e,b):e.onNext(b);e.onCompleted()}d.push(f),a.apply(b,d)}).publishLast().refCount()}},g.fromNodeCallback=function(a,b,c){return function(){var d=p.call(arguments,0);return new j(function(e){function f(a){if(a)return void e.onError(a);var b=p.call(arguments,1);if(c){try{b=c(b)}catch(d){return void e.onError(d)}e.onNext(b)}else b.length<=1?e.onNext.apply(e,b):e.onNext(b);e.onCompleted()}d.push(f),a.apply(b,d)}).publishLast().refCount()}},c.config.useNativeEvents=!1;var r=a.angular&&angular.element?angular.element:a.jQuery?a.jQuery:a.Zepto?a.Zepto:null,s=!!a.Ember&&"function"==typeof a.Ember.addListener,t=!!a.Backbone&&!!a.Backbone.Marionette;g.fromEvent=function(a,b,d){if(a.addListener)return u(function(c){a.addListener(b,c)},function(c){a.removeListener(b,c)},d);if(!c.config.useNativeEvents){if(t)return u(function(c){a.on(b,c)},function(c){a.off(b,c)},d);if(s)return u(function(c){Ember.addListener(a,b,c)},function(c){Ember.removeListener(a,b,c)},d);if(r){var e=r(a);return u(function(a){e.on(b,a)},function(a){e.off(b,a)},d)}}return new j(function(c){return f(a,b,function(a){var b=a;if(d)try{b=d(arguments)}catch(e){return void c.onError(e)}c.onNext(b)})}).publish().refCount()};var u=g.fromEventPattern=function(a,b,c){return new j(function(d){function e(a){var b=a;if(c)try{b=c(arguments)}catch(e){return void d.onError(e)}d.onNext(b)}var f=a(e);return l(function(){b&&b(e,f)})}).publish().refCount()};return g.startAsync=function(a){var b;try{b=a()}catch(c){return i(c)}return h(b)},c}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.async.js b/ajax/libs/rxjs/2.3.9/rx.async.js new file mode 100644 index 000000000..e7801955a --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.async.js @@ -0,0 +1,345 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx.binding', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // Aliases + var Observable = Rx.Observable, + observableProto = Observable.prototype, + observableFromPromise = Observable.fromPromise, + observableThrow = Observable.throwException, + AnonymousObservable = Rx.AnonymousObservable, + AsyncSubject = Rx.AsyncSubject, + disposableCreate = Rx.Disposable.create, + CompositeDisposable= Rx.CompositeDisposable, + immediateScheduler = Rx.Scheduler.immediate, + timeoutScheduler = Rx.Scheduler.timeout, + isScheduler = Rx.helpers.isScheduler, + slice = Array.prototype.slice; + + /** + * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. + * + * @example + * var res = Rx.Observable.start(function () { console.log('hello'); }); + * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); + * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); + * + * @param {Function} func Function to run asynchronously. + * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @returns {Observable} An observable sequence exposing the function's result value, or an exception. + * + * Remarks + * * The function is called immediately, not during the subscription of the resulting sequence. + * * Multiple subscriptions to the resulting sequence can observe the function's result. + */ + Observable.start = function (func, context, scheduler) { + return observableToAsync(func, context, scheduler)(); + }; + + /** + * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. + * + * @example + * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); + * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); + * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); + * + * @param {Function} function Function to convert to an asynchronous function. + * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @returns {Function} Asynchronous function. + */ + var observableToAsync = Observable.toAsync = function (func, context, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return function () { + var args = arguments, + subject = new AsyncSubject(); + + scheduler.schedule(function () { + var result; + try { + result = func.apply(context, args); + } catch (e) { + subject.onError(e); + return; + } + subject.onNext(result); + subject.onCompleted(); + }); + return subject.asObservable(); + }; + }; + + /** + * Converts a callback function to an observable sequence. + * + * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. + * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. + * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. + */ + Observable.fromCallback = function (func, context, selector) { + return function () { + var args = slice.call(arguments, 0); + + return new AnonymousObservable(function (observer) { + function handler(e) { + var results = e; + + if (selector) { + try { + results = selector(arguments); + } catch (err) { + observer.onError(err); + return; + } + + observer.onNext(results); + } else { + if (results.length <= 1) { + observer.onNext.apply(observer, results); + } else { + observer.onNext(results); + } + } + + observer.onCompleted(); + } + + args.push(handler); + func.apply(context, args); + }).publishLast().refCount(); + }; + }; + + /** + * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. + * @param {Function} func The function to call + * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. + * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. + */ + Observable.fromNodeCallback = function (func, context, selector) { + return function () { + var args = slice.call(arguments, 0); + + return new AnonymousObservable(function (observer) { + function handler(err) { + if (err) { + observer.onError(err); + return; + } + + var results = slice.call(arguments, 1); + + if (selector) { + try { + results = selector(results); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(results); + } else { + if (results.length <= 1) { + observer.onNext.apply(observer, results); + } else { + observer.onNext(results); + } + } + + observer.onCompleted(); + } + + args.push(handler); + func.apply(context, args); + }).publishLast().refCount(); + }; + }; + + function createListener (element, name, handler) { + if (element.addEventListener) { + element.addEventListener(name, handler, false); + return disposableCreate(function () { + element.removeEventListener(name, handler, false); + }); + } + throw new Error('No listener found'); + } + + function createEventListener (el, eventName, handler) { + var disposables = new CompositeDisposable(); + + // Asume NodeList + if (Object.prototype.toString.call(el) === '[object NodeList]') { + for (var i = 0, len = el.length; i < len; i++) { + disposables.add(createEventListener(el.item(i), eventName, handler)); + } + } else if (el) { + disposables.add(createListener(el, eventName, handler)); + } + + return disposables; + } + + /** + * Configuration option to determine whether to use native events only + */ + Rx.config.useNativeEvents = false; + + // Check for Angular/jQuery/Zepto support + var jq = + !!root.angular && !!angular.element ? angular.element : + (!!root.jQuery ? root.jQuery : ( + !!root.Zepto ? root.Zepto : null)); + + // Check for ember + var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; + + // Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs + // for proper loading order! + var marionette = !!root.Backbone && !!root.Backbone.Marionette; + + /** + * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. + * + * @example + * var source = Rx.Observable.fromEvent(element, 'mouseup'); + * + * @param {Object} element The DOMElement or NodeList to attach a listener. + * @param {String} eventName The event name to attach the observable sequence. + * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. + * @returns {Observable} An observable sequence of events from the specified element and the specified event. + */ + Observable.fromEvent = function (element, eventName, selector) { + // Node.js specific + if (element.addListener) { + return fromEventPattern( + function (h) { element.addListener(eventName, h); }, + function (h) { element.removeListener(eventName, h); }, + selector); + } + + // Use only if non-native events are allowed + if (!Rx.config.useNativeEvents) { + if (marionette) { + return fromEventPattern( + function (h) { element.on(eventName, h); }, + function (h) { element.off(eventName, h); }, + selector); + } + if (ember) { + return fromEventPattern( + function (h) { Ember.addListener(element, eventName, h); }, + function (h) { Ember.removeListener(element, eventName, h); }, + selector); + } + if (jq) { + var $elem = jq(element); + return fromEventPattern( + function (h) { $elem.on(eventName, h); }, + function (h) { $elem.off(eventName, h); }, + selector); + } + } + return new AnonymousObservable(function (observer) { + return createEventListener( + element, + eventName, + function handler (e) { + var results = e; + + if (selector) { + try { + results = selector(arguments); + } catch (err) { + observer.onError(err); + return + } + } + + observer.onNext(results); + }); + }).publish().refCount(); + }; + + /** + * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. + * @param {Function} addHandler The function to add a handler to the emitter. + * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. + * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. + * @returns {Observable} An observable sequence which wraps an event from an event emitter + */ + var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { + return new AnonymousObservable(function (observer) { + function innerHandler (e) { + var result = e; + if (selector) { + try { + result = selector(arguments); + } catch (err) { + observer.onError(err); + return; + } + } + observer.onNext(result); + } + + var returnValue = addHandler(innerHandler); + return disposableCreate(function () { + if (removeHandler) { + removeHandler(innerHandler, returnValue); + } + }); + }).publish().refCount(); + }; + + /** + * Invokes the asynchronous function, surfacing the result through an observable sequence. + * @param {Function} functionAsync Asynchronous function which returns a Promise to run. + * @returns {Observable} An observable sequence exposing the function's result value, or an exception. + */ + Observable.startAsync = function (functionAsync) { + var promise; + try { + promise = functionAsync(); + } catch (e) { + return observableThrow(e); + } + return observableFromPromise(promise); + } + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.async.min.js b/ajax/libs/rxjs/2.3.9/rx.async.min.js new file mode 100644 index 000000000..e318961be --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.async.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx.binding","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c){function d(a,b,c){if(a.addEventListener)return a.addEventListener(b,c,!1),k(function(){a.removeEventListener(b,c,!1)});throw new Error("No listener found")}function e(a,b,c){var f=new l;if("[object NodeList]"===Object.prototype.toString.call(a))for(var g=0,h=a.length;h>g;g++)f.add(e(a.item(g),b,c));else a&&f.add(d(a,b,c));return f}var f=c.Observable,g=(f.prototype,f.fromPromise),h=f.throwException,i=c.AnonymousObservable,j=c.AsyncSubject,k=c.Disposable.create,l=c.CompositeDisposable,m=(c.Scheduler.immediate,c.Scheduler.timeout),n=c.helpers.isScheduler,o=Array.prototype.slice;f.start=function(a,b,c){return p(a,b,c)()};var p=f.toAsync=function(a,b,c){return n(c)||(c=m),function(){var d=arguments,e=new j;return c.schedule(function(){var c;try{c=a.apply(b,d)}catch(f){return void e.onError(f)}e.onNext(c),e.onCompleted()}),e.asObservable()}};f.fromCallback=function(a,b,c){return function(){var d=o.call(arguments,0);return new i(function(e){function f(a){var b=a;if(c){try{b=c(arguments)}catch(d){return void e.onError(d)}e.onNext(b)}else b.length<=1?e.onNext.apply(e,b):e.onNext(b);e.onCompleted()}d.push(f),a.apply(b,d)}).publishLast().refCount()}},f.fromNodeCallback=function(a,b,c){return function(){var d=o.call(arguments,0);return new i(function(e){function f(a){if(a)return void e.onError(a);var b=o.call(arguments,1);if(c){try{b=c(b)}catch(d){return void e.onError(d)}e.onNext(b)}else b.length<=1?e.onNext.apply(e,b):e.onNext(b);e.onCompleted()}d.push(f),a.apply(b,d)}).publishLast().refCount()}},c.config.useNativeEvents=!1;var q=a.angular&&angular.element?angular.element:a.jQuery?a.jQuery:a.Zepto?a.Zepto:null,r=!!a.Ember&&"function"==typeof a.Ember.addListener,s=!!a.Backbone&&!!a.Backbone.Marionette;f.fromEvent=function(a,b,d){if(a.addListener)return t(function(c){a.addListener(b,c)},function(c){a.removeListener(b,c)},d);if(!c.config.useNativeEvents){if(s)return t(function(c){a.on(b,c)},function(c){a.off(b,c)},d);if(r)return t(function(c){Ember.addListener(a,b,c)},function(c){Ember.removeListener(a,b,c)},d);if(q){var f=q(a);return t(function(a){f.on(b,a)},function(a){f.off(b,a)},d)}}return new i(function(c){return e(a,b,function(a){var b=a;if(d)try{b=d(arguments)}catch(e){return void c.onError(e)}c.onNext(b)})}).publish().refCount()};var t=f.fromEventPattern=function(a,b,c){return new i(function(d){function e(a){var b=a;if(c)try{b=c(arguments)}catch(e){return void d.onError(e)}d.onNext(b)}var f=a(e);return k(function(){b&&b(e,f)})}).publish().refCount()};return f.startAsync=function(a){var b;try{b=a()}catch(c){return h(c)}return g(b)},c}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.backpressure.js b/ajax/libs/rxjs/2.3.9/rx.backpressure.js new file mode 100644 index 000000000..5b54457b8 --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.backpressure.js @@ -0,0 +1,406 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // References + var Observable = Rx.Observable, + observableProto = Observable.prototype, + AnonymousObservable = Rx.AnonymousObservable, + CompositeDisposable = Rx.CompositeDisposable, + Subject = Rx.Subject, + Observer = Rx.Observer, + disposableEmpty = Rx.Disposable.empty, + disposableCreate = Rx.Disposable.create, + inherits = Rx.internals.inherits, + addProperties = Rx.internals.addProperties, + timeoutScheduler = Rx.Scheduler.timeout, + identity = Rx.helpers.identity; + + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + var PausableObservable = (function (_super) { + + inherits(PausableObservable, _super); + + function subscribe(observer) { + var conn = this.source.publish(), + subscription = conn.subscribe(observer), + connection = disposableEmpty; + + var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { + if (b) { + connection = conn.connect(); + } else { + connection.dispose(); + connection = disposableEmpty; + } + }); + + return new CompositeDisposable(subscription, connection, pausable); + } + + function PausableObservable(source, pauser) { + this.source = source; + this.controller = new Subject(); + + if (pauser && pauser.subscribe) { + this.pauser = this.controller.merge(pauser); + } else { + this.pauser = this.controller; + } + + _super.call(this, subscribe); + } + + PausableObservable.prototype.pause = function () { + this.controller.onNext(false); + }; + + PausableObservable.prototype.resume = function () { + this.controller.onNext(true); + }; + + return PausableObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausable(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausable = function (pauser) { + return new PausableObservable(this, pauser); + }; + function combineLatestSource(source, subject, resultSelector) { + return new AnonymousObservable(function (observer) { + var n = 2, + hasValue = [false, false], + hasValueAll = false, + isDone = false, + values = new Array(n); + + function next(x, i) { + values[i] = x + var res; + hasValue[i] = true; + if (hasValueAll || (hasValueAll = hasValue.every(identity))) { + try { + res = resultSelector.apply(null, values); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe( + function (x) { + next(x, 0); + }, + observer.onError.bind(observer), + function () { + isDone = true; + observer.onCompleted(); + }), + subject.subscribe( + function (x) { + next(x, 1); + }, + observer.onError.bind(observer)) + ); + }); + } + + var PausableBufferedObservable = (function (_super) { + + inherits(PausableBufferedObservable, _super); + + function subscribe(observer) { + var q = [], previousShouldFire; + + var subscription = + combineLatestSource( + this.source, + this.pauser.distinctUntilChanged().startWith(false), + function (data, shouldFire) { + return { data: data, shouldFire: shouldFire }; + }) + .subscribe( + function (results) { + if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { + // change in shouldFire + if (results.shouldFire) { + while (q.length > 0) { + observer.onNext(q.shift()); + } + } + } else { + // new data + if (results.shouldFire) { + observer.onNext(results.data); + } else { + q.push(results.data); + } + } + previousShouldFire = results.shouldFire; + + }, + function (err) { + // Empty buffer before sending error + while (q.length > 0) { + observer.onNext(q.shift()); + } + observer.onError(err); + }, + function () { + // Empty buffer before sending completion + while (q.length > 0) { + observer.onNext(q.shift()); + } + observer.onCompleted(); + } + ); + return subscription; + } + + function PausableBufferedObservable(source, pauser) { + this.source = source; + this.controller = new Subject(); + + if (pauser && pauser.subscribe) { + this.pauser = this.controller.merge(pauser); + } else { + this.pauser = this.controller; + } + + _super.call(this, subscribe); + } + + PausableBufferedObservable.prototype.pause = function () { + this.controller.onNext(false); + }; + + PausableBufferedObservable.prototype.resume = function () { + this.controller.onNext(true); + }; + + return PausableBufferedObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, + * and yields the values that were buffered while paused. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausableBuffered(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausableBuffered = function (subject) { + return new PausableBufferedObservable(this, subject); + }; + + /** + * Attaches a controller to the observable sequence with the ability to queue. + * @example + * var source = Rx.Observable.interval(100).controlled(); + * source.request(3); // Reads 3 values + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.controlled = function (enableQueue) { + if (enableQueue == null) { enableQueue = true; } + return new ControlledObservable(this, enableQueue); + }; + var ControlledObservable = (function (_super) { + + inherits(ControlledObservable, _super); + + function subscribe (observer) { + return this.source.subscribe(observer); + } + + function ControlledObservable (source, enableQueue) { + _super.call(this, subscribe); + this.subject = new ControlledSubject(enableQueue); + this.source = source.multicast(this.subject).refCount(); + } + + ControlledObservable.prototype.request = function (numberOfItems) { + if (numberOfItems == null) { numberOfItems = -1; } + return this.subject.request(numberOfItems); + }; + + return ControlledObservable; + + }(Observable)); + + var ControlledSubject = Rx.ControlledSubject = (function (_super) { + + function subscribe (observer) { + return this.subject.subscribe(observer); + } + + inherits(ControlledSubject, _super); + + function ControlledSubject(enableQueue) { + if (enableQueue == null) { + enableQueue = true; + } + + _super.call(this, subscribe); + this.subject = new Subject(); + this.enableQueue = enableQueue; + this.queue = enableQueue ? [] : null; + this.requestedCount = 0; + this.requestedDisposable = disposableEmpty; + this.error = null; + this.hasFailed = false; + this.hasCompleted = false; + this.controlledDisposable = disposableEmpty; + } + + addProperties(ControlledSubject.prototype, Observer, { + onCompleted: function () { + checkDisposed.call(this); + this.hasCompleted = true; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onCompleted(); + } + }, + onError: function (error) { + checkDisposed.call(this); + this.hasFailed = true; + this.error = error; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onError(error); + } + }, + onNext: function (value) { + checkDisposed.call(this); + var hasRequested = false; + + if (this.requestedCount === 0) { + if (this.enableQueue) { + this.queue.push(value); + } + } else { + if (this.requestedCount !== -1) { + if (this.requestedCount-- === 0) { + this.disposeCurrentRequest(); + } + } + hasRequested = true; + } + + if (hasRequested) { + this.subject.onNext(value); + } + }, + _processRequest: function (numberOfItems) { + if (this.enableQueue) { + //console.log('queue length', this.queue.length); + + while (this.queue.length >= numberOfItems && numberOfItems > 0) { + //console.log('number of items', numberOfItems); + this.subject.onNext(this.queue.shift()); + numberOfItems--; + } + + if (this.queue.length !== 0) { + return { numberOfItems: numberOfItems, returnValue: true }; + } else { + return { numberOfItems: numberOfItems, returnValue: false }; + } + } + + if (this.hasFailed) { + this.subject.onError(this.error); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } else if (this.hasCompleted) { + this.subject.onCompleted(); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } + + return { numberOfItems: numberOfItems, returnValue: false }; + }, + request: function (number) { + checkDisposed.call(this); + this.disposeCurrentRequest(); + var self = this, + r = this._processRequest(number); + + number = r.numberOfItems; + if (!r.returnValue) { + this.requestedCount = number; + this.requestedDisposable = disposableCreate(function () { + self.requestedCount = 0; + }); + + return this.requestedDisposable + } else { + return disposableEmpty; + } + }, + disposeCurrentRequest: function () { + this.requestedDisposable.dispose(); + this.requestedDisposable = disposableEmpty; + }, + + dispose: function () { + this.isDisposed = true; + this.error = null; + this.subject.dispose(); + this.requestedDisposable.dispose(); + } + }); + + return ControlledSubject; + }(Observable)); + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.backpressure.min.js b/ajax/libs/rxjs/2.3.9/rx.backpressure.min.js new file mode 100644 index 000000000..7a4f920aa --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.backpressure.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c,d){function e(){if(this.isDisposed)throw new Error(r)}function f(a,b,c){return new i(function(d){function e(a,b){k[b]=a;var e;if(g[b]=!0,h||(h=g.every(q))){try{e=c.apply(null,k)}catch(f){return void d.onError(f)}d.onNext(e)}else i&&d.onCompleted()}var f=2,g=[!1,!1],h=!1,i=!1,k=new Array(f);return new j(a.subscribe(function(a){e(a,0)},d.onError.bind(d),function(){i=!0,d.onCompleted()}),b.subscribe(function(a){e(a,1)},d.onError.bind(d)))})}var g=c.Observable,h=g.prototype,i=c.AnonymousObservable,j=c.CompositeDisposable,k=c.Subject,l=c.Observer,m=c.Disposable.empty,n=c.Disposable.create,o=c.internals.inherits,p=c.internals.addProperties,q=(c.Scheduler.timeout,c.helpers.identity),r="Object has been disposed",s=function(a){function b(a){var b=this.source.publish(),c=b.subscribe(a),d=m,e=this.pauser.distinctUntilChanged().subscribe(function(a){a?d=b.connect():(d.dispose(),d=m)});return new j(c,d,e)}function c(c,d){this.source=c,this.controller=new k,this.pauser=d&&d.subscribe?this.controller.merge(d):this.controller,a.call(this,b)}return o(c,a),c.prototype.pause=function(){this.controller.onNext(!1)},c.prototype.resume=function(){this.controller.onNext(!0)},c}(g);h.pausable=function(a){return new s(this,a)};var t=function(a){function b(a){var b,c=[],e=f(this.source,this.pauser.distinctUntilChanged().startWith(!1),function(a,b){return{data:a,shouldFire:b}}).subscribe(function(e){if(b!==d&&e.shouldFire!=b){if(e.shouldFire)for(;c.length>0;)a.onNext(c.shift())}else e.shouldFire?a.onNext(e.data):c.push(e.data);b=e.shouldFire},function(b){for(;c.length>0;)a.onNext(c.shift());a.onError(b)},function(){for(;c.length>0;)a.onNext(c.shift());a.onCompleted()});return e}function c(c,d){this.source=c,this.controller=new k,this.pauser=d&&d.subscribe?this.controller.merge(d):this.controller,a.call(this,b)}return o(c,a),c.prototype.pause=function(){this.controller.onNext(!1)},c.prototype.resume=function(){this.controller.onNext(!0)},c}(g);h.pausableBuffered=function(a){return new t(this,a)},h.controlled=function(a){return null==a&&(a=!0),new u(this,a)};var u=function(a){function b(a){return this.source.subscribe(a)}function c(c,d){a.call(this,b),this.subject=new v(d),this.source=c.multicast(this.subject).refCount()}return o(c,a),c.prototype.request=function(a){return null==a&&(a=-1),this.subject.request(a)},c}(g),v=c.ControlledSubject=function(a){function b(a){return this.subject.subscribe(a)}function c(c){null==c&&(c=!0),a.call(this,b),this.subject=new k,this.enableQueue=c,this.queue=c?[]:null,this.requestedCount=0,this.requestedDisposable=m,this.error=null,this.hasFailed=!1,this.hasCompleted=!1,this.controlledDisposable=m}return o(c,a),p(c.prototype,l,{onCompleted:function(){e.call(this),this.hasCompleted=!0,this.enableQueue&&0!==this.queue.length||this.subject.onCompleted()},onError:function(a){e.call(this),this.hasFailed=!0,this.error=a,this.enableQueue&&0!==this.queue.length||this.subject.onError(a)},onNext:function(a){e.call(this);var b=!1;0===this.requestedCount?this.enableQueue&&this.queue.push(a):(-1!==this.requestedCount&&0===this.requestedCount--&&this.disposeCurrentRequest(),b=!0),b&&this.subject.onNext(a)},_processRequest:function(a){if(this.enableQueue){for(;this.queue.length>=a&&a>0;)this.subject.onNext(this.queue.shift()),a--;return 0!==this.queue.length?{numberOfItems:a,returnValue:!0}:{numberOfItems:a,returnValue:!1}}return this.hasFailed?(this.subject.onError(this.error),this.controlledDisposable.dispose(),this.controlledDisposable=m):this.hasCompleted&&(this.subject.onCompleted(),this.controlledDisposable.dispose(),this.controlledDisposable=m),{numberOfItems:a,returnValue:!1}},request:function(a){e.call(this),this.disposeCurrentRequest();var b=this,c=this._processRequest(a);return a=c.numberOfItems,c.returnValue?m:(this.requestedCount=a,this.requestedDisposable=n(function(){b.requestedCount=0}),this.requestedDisposable)},disposeCurrentRequest:function(){this.requestedDisposable.dispose(),this.requestedDisposable=m},dispose:function(){this.isDisposed=!0,this.error=null,this.subject.dispose(),this.requestedDisposable.dispose()}}),c}(g);return c}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.binding.js b/ajax/libs/rxjs/2.3.9/rx.binding.js new file mode 100644 index 000000000..3d0abd490 --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.binding.js @@ -0,0 +1,531 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + var Observable = Rx.Observable, + observableProto = Observable.prototype, + AnonymousObservable = Rx.AnonymousObservable, + Subject = Rx.Subject, + AsyncSubject = Rx.AsyncSubject, + Observer = Rx.Observer, + ScheduledObserver = Rx.internals.ScheduledObserver, + disposableCreate = Rx.Disposable.create, + disposableEmpty = Rx.Disposable.empty, + CompositeDisposable = Rx.CompositeDisposable, + currentThreadScheduler = Rx.Scheduler.currentThread, + inherits = Rx.internals.inherits, + addProperties = Rx.internals.addProperties; + + // Utilities + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { + if (this.isDisposed) { + throw new Error(objectDisposed); + } + } + + /** + * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each + * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's + * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. + * + * @example + * 1 - res = source.multicast(observable); + * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); + * + * @param {Function|Subject} subjectOrSubjectSelector + * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. + * Or: + * Subject to push source elements into. + * + * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.exception = null; + } + }); + + return BehaviorSubject; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. + */ + var ReplaySubject = Rx.ReplaySubject = (function (_super) { + + function RemovableDisposable (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + RemovableDisposable.prototype.dispose = function () { + this.observer.dispose(); + if (!this.subject.isDisposed) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + } + }; + + function subscribe(observer) { + var so = new ScheduledObserver(this.scheduler, observer), + subscription = new RemovableDisposable(this, so); + checkDisposed.call(this); + this._trim(this.scheduler.now()); + this.observers.push(so); + + var n = this.q.length; + + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } + + if (this.hasError) { + n++; + so.onError(this.error); + } else if (this.isStopped) { + n++; + so.onCompleted(); + } + + so.ensureActive(n); + return subscription; + } + + inherits(ReplaySubject, _super); + + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; + this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + _super.call(this, subscribe); + } + + addProperties(ReplaySubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /* @private */ + _trim: function (now) { + while (this.q.length > this.bufferSize) { + this.q.shift(); + } + while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { + this.q.shift(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); + + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onNext(value); + observer.ensureActive(); + } + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { + inherits(ConnectableObservable, __super__); + + function ConnectableObservable(source, subject) { + var hasSubscription = false, + subscription, + sourceObservable = source.asObservable(); + + this.connect = function () { + if (!hasSubscription) { + hasSubscription = true; + subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { + hasSubscription = false; + })); + } + return subscription; + }; + + __super__.call(this, subject.subscribe.bind(subject)); + } + + ConnectableObservable.prototype.refCount = function () { + var connectableSubscription, count = 0, source = this; + return new AnonymousObservable(function (observer) { + var shouldConnect = ++count === 1, + subscription = source.subscribe(observer); + shouldConnect && (connectableSubscription = source.connect()); + return function () { + subscription.dispose(); + --count === 0 && connectableSubscription.dispose(); + }; + }); + }; + + return ConnectableObservable; + }(Observable)); + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.binding.min.js b/ajax/libs/rxjs/2.3.9/rx.binding.min.js new file mode 100644 index 000000000..04b33542c --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.binding.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c){function d(){if(this.isDisposed)throw new Error(r)}var e=c.Observable,f=e.prototype,g=c.AnonymousObservable,h=c.Subject,i=c.AsyncSubject,j=c.Observer,k=c.internals.ScheduledObserver,l=c.Disposable.create,m=c.Disposable.empty,n=c.CompositeDisposable,o=c.Scheduler.currentThread,p=c.internals.inherits,q=c.internals.addProperties,r="Object has been disposed";f.multicast=function(a,b){var c=this;return"function"==typeof a?new g(function(d){var e=c.multicast(a());return new n(b(e).subscribe(d),e.connect())}):new v(c,a)},f.publish=function(a){return a?this.multicast(function(){return new h},a):this.multicast(new h)},f.share=function(){return this.publish(null).refCount()},f.publishLast=function(a){return a?this.multicast(function(){return new i},a):this.multicast(new i)},f.publishValue=function(a,b){return 2===arguments.length?this.multicast(function(){return new t(b)},a):this.multicast(new t(a))},f.shareValue=function(a){return this.publishValue(a).refCount()},f.replay=function(a,b,c,d){return a?this.multicast(function(){return new u(b,c,d)},a):this.multicast(new u(b,c,d))},f.shareReplay=function(a,b,c){return this.replay(null,a,b,c).refCount()};var s=function(a,b){this.subject=a,this.observer=b};s.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1),this.observer=null}};var t=c.BehaviorSubject=function(a){function b(a){if(d.call(this),!this.isStopped)return this.observers.push(a),a.onNext(this.value),new s(this,a);var b=this.exception;return b?a.onError(b):a.onCompleted(),m}function c(c){a.call(this,b),this.value=c,this.observers=[],this.isDisposed=!1,this.isStopped=!1,this.exception=null}return p(c,a),q(c.prototype,j,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(d.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var b=0,c=a.length;c>b;b++)a[b].onCompleted();this.observers=[]}},onError:function(a){if(d.call(this),!this.isStopped){var b=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var c=0,e=b.length;e>c;c++)b[c].onError(a);this.observers=[]}},onNext:function(a){if(d.call(this),!this.isStopped){this.value=a;for(var b=this.observers.slice(0),c=0,e=b.length;e>c;c++)b[c].onNext(a)}},dispose:function(){this.isDisposed=!0,this.observers=null,this.value=null,this.exception=null}}),c}(e),u=c.ReplaySubject=function(a){function b(a,b){this.subject=a,this.observer=b}function c(a){var c=new k(this.scheduler,a),e=new b(this,c);d.call(this),this._trim(this.scheduler.now()),this.observers.push(c);for(var f=this.q.length,g=0,h=this.q.length;h>g;g++)c.onNext(this.q[g].value);return this.hasError?(f++,c.onError(this.error)):this.isStopped&&(f++,c.onCompleted()),c.ensureActive(f),e}function e(b,d,e){this.bufferSize=null==b?Number.MAX_VALUE:b,this.windowSize=null==d?Number.MAX_VALUE:d,this.scheduler=e||o,this.q=[],this.observers=[],this.isStopped=!1,this.isDisposed=!1,this.hasError=!1,this.error=null,a.call(this,c)}return b.prototype.dispose=function(){if(this.observer.dispose(),!this.subject.isDisposed){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1)}},p(e,a),q(e.prototype,j,{hasObservers:function(){return this.observers.length>0},_trim:function(a){for(;this.q.length>this.bufferSize;)this.q.shift();for(;this.q.length>0&&a-this.q[0].interval>this.windowSize;)this.q.shift()},onNext:function(a){var b;if(d.call(this),!this.isStopped){var c=this.scheduler.now();this.q.push({interval:c,value:a}),this._trim(c);for(var e=this.observers.slice(0),f=0,g=e.length;g>f;f++)b=e[f],b.onNext(a),b.ensureActive()}},onError:function(a){var b;if(d.call(this),!this.isStopped){this.isStopped=!0,this.error=a,this.hasError=!0;var c=this.scheduler.now();this._trim(c);for(var e=this.observers.slice(0),f=0,g=e.length;g>f;f++)b=e[f],b.onError(a),b.ensureActive();this.observers=[]}},onCompleted:function(){var a;if(d.call(this),!this.isStopped){this.isStopped=!0;var b=this.scheduler.now();this._trim(b);for(var c=this.observers.slice(0),e=0,f=c.length;f>e;e++)a=c[e],a.onCompleted(),a.ensureActive();this.observers=[]}},dispose:function(){this.isDisposed=!0,this.observers=null}}),e}(e),v=c.ConnectableObservable=function(a){function b(b,c){var d,e=!1,f=b.asObservable();this.connect=function(){return e||(e=!0,d=new n(f.subscribe(c),l(function(){e=!1}))),d},a.call(this,c.subscribe.bind(c))}return p(b,a),b.prototype.refCount=function(){var a,b=0,c=this;return new g(function(d){var e=1===++b,f=c.subscribe(d);return e&&(a=c.connect()),function(){f.dispose(),0===--b&&a.dispose()}})},b}(e);return c}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.coincidence.js b/ajax/libs/rxjs/2.3.9/rx.coincidence.js new file mode 100644 index 000000000..2a62ac2ee --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.coincidence.js @@ -0,0 +1,814 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + var Observable = Rx.Observable, + CompositeDisposable = Rx.CompositeDisposable, + RefCountDisposable = Rx.RefCountDisposable, + SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, + SerialDisposable = Rx.SerialDisposable, + Subject = Rx.Subject, + observableProto = Observable.prototype, + observableEmpty = Observable.empty, + observableNever = Observable.never, + AnonymousObservable = Rx.AnonymousObservable, + observerCreate = Rx.Observer.create, + addRef = Rx.internals.addRef, + defaultComparer = Rx.internals.isEqual, + noop = Rx.helpers.noop, + identity = Rx.helpers.identity; + + + var Dictionary = (function () { + + var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], + noSuchkey = "no such key", + duplicatekey = "duplicate key"; + + function isPrime(candidate) { + if (candidate & 1 === 0) { return candidate === 2; } + var num1 = Math.sqrt(candidate), + num2 = 3; + while (num2 <= num1) { + if (candidate % num2 === 0) { return false; } + num2 += 2; + } + return true; + } + + function getPrime(min) { + var index, num, candidate; + for (index = 0; index < primes.length; ++index) { + num = primes[index]; + if (num >= min) { return num; } + } + candidate = min | 1; + while (candidate < primes[primes.length - 1]) { + if (isPrime(candidate)) { return candidate; } + candidate += 2; + } + return min; + } + + function stringHashFn(str) { + var hash = 757602046; + if (!str.length) { return hash; } + for (var i = 0, len = str.length; i < len; i++) { + var character = str.charCodeAt(i); + hash = ((hash<<5)-hash)+character; + hash = hash & hash; + } + return hash; + } + + function numberHashFn(key) { + var c2 = 0x27d4eb2d; + key = (key ^ 61) ^ (key >>> 16); + key = key + (key << 3); + key = key ^ (key >>> 4); + key = key * c2; + key = key ^ (key >>> 15); + return key; + } + + var getHashCode = (function () { + var uniqueIdCounter = 0; + + return function (obj) { + if (obj == null) { throw new Error(noSuchkey); } + + // Check for built-ins before tacking on our own for any object + if (typeof obj === 'string') { return stringHashFn(obj); } + if (typeof obj === 'number') { return numberHashFn(obj); } + if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } + if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } + if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } + if (typeof obj.valueOf === 'function') { + // Hack check for valueOf + var valueOf = obj.valueOf(); + if (typeof valueOf === 'number') { return numberHashFn(valueOf); } + if (typeof obj === 'string') { return stringHashFn(valueOf); } + } + if (obj.getHashCode) { return obj.getHashCode(); } + + var id = 17 * uniqueIdCounter++; + obj.getHashCode = function () { return id; }; + return id; + }; + }()); + + function newEntry() { + return { key: null, value: null, next: 0, hashCode: 0 }; + } + + function Dictionary(capacity, comparer) { + if (capacity < 0) { throw new Error('out of range'); } + if (capacity > 0) { this._initialize(capacity); } + + this.comparer = comparer || defaultComparer; + this.freeCount = 0; + this.size = 0; + this.freeList = -1; + } + + var dictionaryProto = Dictionary.prototype; + + dictionaryProto._initialize = function (capacity) { + var prime = getPrime(capacity), i; + this.buckets = new Array(prime); + this.entries = new Array(prime); + for (i = 0; i < prime; i++) { + this.buckets[i] = -1; + this.entries[i] = newEntry(); + } + this.freeList = -1; + }; + + dictionaryProto.add = function (key, value) { + return this._insert(key, value, true); + }; + + dictionaryProto._insert = function (key, value, add) { + if (!this.buckets) { this._initialize(0); } + var index3, + num = getHashCode(key) & 2147483647, + index1 = num % this.buckets.length; + for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { + if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { + if (add) { throw new Error(duplicatekey); } + this.entries[index2].value = value; + return; + } + } + if (this.freeCount > 0) { + index3 = this.freeList; + this.freeList = this.entries[index3].next; + --this.freeCount; + } else { + if (this.size === this.entries.length) { + this._resize(); + index1 = num % this.buckets.length; + } + index3 = this.size; + ++this.size; + } + this.entries[index3].hashCode = num; + this.entries[index3].next = this.buckets[index1]; + this.entries[index3].key = key; + this.entries[index3].value = value; + this.buckets[index1] = index3; + }; + + dictionaryProto._resize = function () { + var prime = getPrime(this.size * 2), + numArray = new Array(prime); + for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } + var entryArray = new Array(prime); + for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } + for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } + for (var index1 = 0; index1 < this.size; ++index1) { + var index2 = entryArray[index1].hashCode % prime; + entryArray[index1].next = numArray[index2]; + numArray[index2] = index1; + } + this.buckets = numArray; + this.entries = entryArray; + }; + + dictionaryProto.remove = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647, + index1 = num % this.buckets.length, + index2 = -1; + for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { + if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { + if (index2 < 0) { + this.buckets[index1] = this.entries[index3].next; + } else { + this.entries[index2].next = this.entries[index3].next; + } + this.entries[index3].hashCode = -1; + this.entries[index3].next = this.freeList; + this.entries[index3].key = null; + this.entries[index3].value = null; + this.freeList = index3; + ++this.freeCount; + return true; + } else { + index2 = index3; + } + } + } + return false; + }; + + dictionaryProto.clear = function () { + var index, len; + if (this.size <= 0) { return; } + for (index = 0, len = this.buckets.length; index < len; ++index) { + this.buckets[index] = -1; + } + for (index = 0; index < this.size; ++index) { + this.entries[index] = newEntry(); + } + this.freeList = -1; + this.size = 0; + }; + + dictionaryProto._findEntry = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647; + for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { + if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { + return index; + } + } + } + return -1; + }; + + dictionaryProto.count = function () { + return this.size - this.freeCount; + }; + + dictionaryProto.tryGetValue = function (key) { + var entry = this._findEntry(key); + return entry >= 0 ? + this.entries[entry].value : + undefined; + }; + + dictionaryProto.getValues = function () { + var index = 0, results = []; + if (this.entries) { + for (var index1 = 0; index1 < this.size; index1++) { + if (this.entries[index1].hashCode >= 0) { + results[index++] = this.entries[index1].value; + } + } + } + return results; + }; + + dictionaryProto.get = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { return this.entries[entry].value; } + throw new Error(noSuchkey); + }; + + dictionaryProto.set = function (key, value) { + this._insert(key, value, false); + }; + + dictionaryProto.containskey = function (key) { + return this._findEntry(key) >= 0; + }; + + return Dictionary; + }()); + + /** + * Correlates the elements of two sequences based on overlapping durations. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(); + var leftDone = false, rightDone = false; + var leftId = 0, rightId = 0; + var leftMap = new Dictionary(), rightMap = new Dictionary(); + + group.add(left.subscribe( + function (value) { + var id = leftId++; + var md = new SingleAssignmentDisposable(); + + leftMap.add(id, value); + group.add(md); + + var expire = function () { + leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); + + rightMap.getValues().forEach(function (v) { + var result; + try { + result = resultSelector(value, v); + } catch (exn) { + observer.onError(exn); + return; + } + + observer.onNext(result); + }); + }, + observer.onError.bind(observer), + function () { + leftDone = true; + (rightDone || leftMap.count() === 0) && observer.onCompleted(); + }) + ); + + group.add(right.subscribe( + function (value) { + var id = rightId++; + var md = new SingleAssignmentDisposable(); + + rightMap.add(id, value); + group.add(md); + + var expire = function () { + rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = rightDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); + + leftMap.getValues().forEach(function (v) { + var result; + try { + result = resultSelector(v, value); + } catch(exn) { + observer.onError(exn); + return; + } + + observer.onNext(result); + }); + }, + observer.onError.bind(observer), + function () { + rightDone = true; + (leftDone || rightMap.count() === 0) && observer.onCompleted(); + }) + ); + return group; + }); + }; + + /** + * Correlates the elements of two sequences based on overlapping durations, and groups the results. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(); + var r = new RefCountDisposable(group); + var leftMap = new Dictionary(), rightMap = new Dictionary(); + var leftId = 0, rightId = 0; + + function handleError(e) { return function (v) { v.onError(e); }; }; + + group.add(left.subscribe( + function (value) { + var s = new Subject(); + var id = leftId++; + leftMap.add(id, s); + + var result; + try { + result = resultSelector(value, addRef(s, r)); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + observer.onNext(result); + + rightMap.getValues().forEach(function (v) { s.onNext(v); }); + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + leftMap.remove(id) && s.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe( + noop, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + expire) + ); + }, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + observer.onCompleted.bind(observer)) + ); + + group.add(right.subscribe( + function (value) { + var id = rightId++; + rightMap.add(id, value); + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + rightMap.remove(id); + group.remove(md); + }; + + var duration; + try { + duration = rightDurationSelector(value); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + md.setDisposable(duration.take(1).subscribe( + noop, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + expire) + ); + + leftMap.getValues().forEach(function (v) { v.onNext(value); }); + }, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }) + ); + + return r; + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers. + * + * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { + return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows. + * + * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { + if (arguments.length === 1 && typeof arguments[0] !== 'function') { + return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector); + } + return typeof windowOpeningsOrClosingSelector === 'function' ? + observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : + observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); + }; + + function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { + return windowOpenings.groupJoin(this, windowClosingSelector, function () { + return observableEmpty(); + }, function (_, window) { + return window; + }); + } + + function observableWindowWithBounaries(windowBoundaries) { + var source = this; + return new AnonymousObservable(function (observer) { + var window = new Subject(), + d = new CompositeDisposable(), + r = new RefCountDisposable(d); + + observer.onNext(addRef(window, r)); + + d.add(source.subscribe(function (x) { + window.onNext(x); + }, function (err) { + window.onError(err); + observer.onError(err); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + + d.add(windowBoundaries.subscribe(function (w) { + window.onCompleted(); + window = new Subject(); + observer.onNext(addRef(window, r)); + }, function (err) { + window.onError(err); + observer.onError(err); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + + return r; + }); + } + + function observableWindowWithClosingSelector(windowClosingSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var createWindowClose, + m = new SerialDisposable(), + d = new CompositeDisposable(m), + r = new RefCountDisposable(d), + window = new Subject(); + observer.onNext(addRef(window, r)); + d.add(source.subscribe(function (x) { + window.onNext(x); + }, function (ex) { + window.onError(ex); + observer.onError(ex); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + createWindowClose = function () { + var m1, windowClose; + try { + windowClose = windowClosingSelector(); + } catch (exception) { + observer.onError(exception); + return; + } + m1 = new SingleAssignmentDisposable(); + m.setDisposable(m1); + m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) { + window.onError(ex); + observer.onError(ex); + }, function () { + window.onCompleted(); + window = new Subject(); + observer.onNext(addRef(window, r)); + createWindowClose(); + })); + }; + createWindowClose(); + return r; + }); + } + + /** + * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. + * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. + * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. + * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. + */ + observableProto.pairwise = function () { + var source = this; + return new AnonymousObservable(function (observer) { + var previous, hasPrevious = false; + return source.subscribe( + function (x) { + if (hasPrevious) { + observer.onNext([previous, x]); + } else { + hasPrevious = true; + } + previous = x; + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer)); + }); + }; + /** + * Returns two observables which partition the observations of the source by the given function. + * The first will trigger observations for those values for which the predicate returns true. + * The second will trigger observations for those values where the predicate returns false. + * The predicate is executed once for each subscribed observer. + * Both also propagate all error observations arising from the source and each completes + * when the source completes. + * @param {Function} predicate + * The function to determine which output Observable will trigger a particular observation. + * @returns {Array} + * An array of observables. The first triggers when the predicate returns true, + * and the second triggers when the predicate returns false. + */ + observableProto.partition = function(predicate, thisArg) { + var published = this.publish().refCount(); + return [ + published.filter(predicate, thisArg), + published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) + ]; + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. + * + * @example + * var res = observable.groupBy(function (x) { return x.id; }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. + * @param {Function} [comparer] Used to determine whether the objects are equal. + * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + observableProto.groupBy = function (keySelector, elementSelector, comparer) { + return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function. + * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same + * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. + * + * @example + * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} durationSelector A function to signal the expiration of a group. + * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. + * @returns {Observable} + * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. + * + */ + observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { + var source = this; + elementSelector || (elementSelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + function handleError(e) { return function (item) { item.onError(e); }; } + var map = new Dictionary(0, comparer), + groupDisposable = new CompositeDisposable(), + refCountDisposable = new RefCountDisposable(groupDisposable); + + groupDisposable.add(source.subscribe(function (x) { + var key; + try { + key = keySelector(x); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + var fireNewMapEntry = false, + writer = map.tryGetValue(key); + if (!writer) { + writer = new Subject(); + map.set(key, writer); + fireNewMapEntry = true; + } + + if (fireNewMapEntry) { + var group = new GroupedObservable(key, writer, refCountDisposable), + durationGroup = new GroupedObservable(key, writer); + try { + duration = durationSelector(durationGroup); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + observer.onNext(group); + + var md = new SingleAssignmentDisposable(); + groupDisposable.add(md); + + var expire = function () { + map.remove(key) && writer.onCompleted(); + groupDisposable.remove(md); + }; + + md.setDisposable(duration.take(1).subscribe( + noop, + function (exn) { + map.getValues().forEach(handleError(exn)); + observer.onError(exn); + }, + expire) + ); + } + + var element; + try { + element = elementSelector(x); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + writer.onNext(element); + }, function (ex) { + map.getValues().forEach(handleError(ex)); + observer.onError(ex); + }, function () { + map.getValues().forEach(function (item) { item.onCompleted(); }); + observer.onCompleted(); + })); + + return refCountDisposable; + }); + }; + + /** @private */ + var GroupedObservable = (function (_super) { + inherits(GroupedObservable, _super); + + function subscribe(observer) { + return this.underlyingObservable.subscribe(observer); + } + + /** + * @constructor + * @private + */ + function GroupedObservable(key, underlyingObservable, mergedDisposable) { + _super.call(this, subscribe); + this.key = key; + this.underlyingObservable = !mergedDisposable ? + underlyingObservable : + new AnonymousObservable(function (observer) { + return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); + }); + } + + return GroupedObservable; + }(Observable)); + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.coincidence.min.js b/ajax/libs/rxjs/2.3.9/rx.coincidence.min.js new file mode 100644 index 000000000..62c24603d --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.coincidence.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c,d){function e(a,b){return a.groupJoin(this,b,function(){return o()},function(a,b){return b})}function f(a){var b=this;return new q(function(c){var d=new m,e=new i,f=new j(e);return c.onNext(r(d,f)),e.add(b.subscribe(function(a){d.onNext(a)},function(a){d.onError(a),c.onError(a)},function(){d.onCompleted(),c.onCompleted()})),e.add(a.subscribe(function(){d.onCompleted(),d=new m,c.onNext(r(d,f))},function(a){d.onError(a),c.onError(a)},function(){d.onCompleted(),c.onCompleted()})),f})}function g(a){var b=this;return new q(function(c){var d,e=new l,f=new i(e),g=new j(f),h=new m;return c.onNext(r(h,g)),f.add(b.subscribe(function(a){h.onNext(a)},function(a){h.onError(a),c.onError(a)},function(){h.onCompleted(),c.onCompleted()})),d=function(){var b,f;try{f=a()}catch(i){return void c.onError(i)}b=new k,e.setDisposable(b),b.setDisposable(f.take(1).subscribe(t,function(a){h.onError(a),c.onError(a)},function(){h.onCompleted(),h=new m,c.onNext(r(h,g)),d()}))},d(),g})}var h=c.Observable,i=c.CompositeDisposable,j=c.RefCountDisposable,k=c.SingleAssignmentDisposable,l=c.SerialDisposable,m=c.Subject,n=h.prototype,o=h.empty,p=h.never,q=c.AnonymousObservable,r=(c.Observer.create,c.internals.addRef),s=c.internals.isEqual,t=c.helpers.noop,u=c.helpers.identity,v=function(){function a(a){if(a&!1)return 2===a;for(var b=Math.sqrt(a),c=3;b>=c;){if(a%c===0)return!1;c+=2}return!0}function b(b){var c,d,e;for(c=0;c=b)return d;for(e=1|b;ec;c++){var e=a.charCodeAt(c);b=(b<<5)-b+e,b&=b}return b}function e(a){var b=668265261;return a=61^a^a>>>16,a+=a<<3,a^=a>>>4,a*=b,a^=a>>>15}function f(){return{key:null,value:null,next:0,hashCode:0}}function g(a,b){if(0>a)throw new Error("out of range");a>0&&this._initialize(a),this.comparer=b||s,this.freeCount=0,this.size=0,this.freeList=-1}var h=[1,3,7,13,31,61,127,251,509,1021,2039,4093,8191,16381,32749,65521,131071,262139,524287,1048573,2097143,4194301,8388593,16777213,33554393,67108859,134217689,268435399,536870909,1073741789,2147483647],i="no such key",j="duplicate key",k=function(){var a=0;return function(b){if(null==b)throw new Error(i);if("string"==typeof b)return c(b);if("number"==typeof b)return e(b);if("boolean"==typeof b)return b===!0?1:0;if(b instanceof Date)return e(b.valueOf());if(b instanceof RegExp)return c(b.toString());if("function"==typeof b.valueOf){var d=b.valueOf();if("number"==typeof d)return e(d);if("string"==typeof b)return c(d)}if(b.getHashCode)return b.getHashCode();var f=17*a++;return b.getHashCode=function(){return f},f}}(),l=g.prototype;return l._initialize=function(a){var c,d=b(a);for(this.buckets=new Array(d),this.entries=new Array(d),c=0;d>c;c++)this.buckets[c]=-1,this.entries[c]=f();this.freeList=-1},l.add=function(a,b){return this._insert(a,b,!0)},l._insert=function(a,b,c){this.buckets||this._initialize(0);for(var d,e=2147483647&k(a),f=e%this.buckets.length,g=this.buckets[f];g>=0;g=this.entries[g].next)if(this.entries[g].hashCode===e&&this.comparer(this.entries[g].key,a)){if(c)throw new Error(j);return void(this.entries[g].value=b)}this.freeCount>0?(d=this.freeList,this.freeList=this.entries[d].next,--this.freeCount):(this.size===this.entries.length&&(this._resize(),f=e%this.buckets.length),d=this.size,++this.size),this.entries[d].hashCode=e,this.entries[d].next=this.buckets[f],this.entries[d].key=a,this.entries[d].value=b,this.buckets[f]=d},l._resize=function(){var a=b(2*this.size),c=new Array(a);for(e=0;ee;++e)d[e]=f();for(var g=0;g=0;e=this.entries[e].next){if(this.entries[e].hashCode===b&&this.comparer(this.entries[e].key,a))return 0>d?this.buckets[c]=this.entries[e].next:this.entries[d].next=this.entries[e].next,this.entries[e].hashCode=-1,this.entries[e].next=this.freeList,this.entries[e].key=null,this.entries[e].value=null,this.freeList=e,++this.freeCount,!0;d=e}return!1},l.clear=function(){var a,b;if(!(this.size<=0)){for(a=0,b=this.buckets.length;b>a;++a)this.buckets[a]=-1;for(a=0;a=0;c=this.entries[c].next)if(this.entries[c].hashCode===b&&this.comparer(this.entries[c].key,a))return c;return-1},l.count=function(){return this.size-this.freeCount},l.tryGetValue=function(a){var b=this._findEntry(a);return b>=0?this.entries[b].value:d},l.getValues=function(){var a=0,b=[];if(this.entries)for(var c=0;c=0&&(b[a++]=this.entries[c].value);return b},l.get=function(a){var b=this._findEntry(a);if(b>=0)return this.entries[b].value;throw new Error(i)},l.set=function(a,b){this._insert(a,b,!1)},l.containskey=function(a){return this._findEntry(a)>=0},g}();n.join=function(a,b,c,d){var e=this;return new q(function(f){var g=new i,h=!1,j=!1,l=0,m=0,n=new v,o=new v;return g.add(e.subscribe(function(a){var c=l++,e=new k;n.add(c,a),g.add(e);var i,j=function(){n.remove(c)&&0===n.count()&&h&&f.onCompleted(),g.remove(e)};try{i=b(a)}catch(m){return void f.onError(m)}e.setDisposable(i.take(1).subscribe(t,f.onError.bind(f),j)),o.getValues().forEach(function(b){var c;try{c=d(a,b)}catch(e){return void f.onError(e)}f.onNext(c)})},f.onError.bind(f),function(){h=!0,(j||0===n.count())&&f.onCompleted()})),g.add(a.subscribe(function(a){var b=m++,e=new k;o.add(b,a),g.add(e);var h,i=function(){o.remove(b)&&0===o.count()&&j&&f.onCompleted(),g.remove(e)};try{h=c(a)}catch(l){return void f.onError(l)}e.setDisposable(h.take(1).subscribe(t,f.onError.bind(f),i)),n.getValues().forEach(function(b){var c;try{c=d(b,a)}catch(e){return void f.onError(e)}f.onNext(c)})},f.onError.bind(f),function(){j=!0,(h||0===o.count())&&f.onCompleted()})),g})},n.groupJoin=function(a,b,c,d){var e=this;return new q(function(f){function g(a){return function(b){b.onError(a)}}var h=new i,l=new j(h),n=new v,o=new v,p=0,q=0;return h.add(e.subscribe(function(a){var c=new m,e=p++;n.add(e,c);var i;try{i=d(a,r(c,l))}catch(j){return n.getValues().forEach(g(j)),void f.onError(j)}f.onNext(i),o.getValues().forEach(function(a){c.onNext(a)});var q=new k;h.add(q);var s,u=function(){n.remove(e)&&c.onCompleted(),h.remove(q)};try{s=b(a)}catch(j){return n.getValues().forEach(g(j)),void f.onError(j)}q.setDisposable(s.take(1).subscribe(t,function(a){n.getValues().forEach(g(a)),f.onError(a)},u))},function(a){n.getValues().forEach(g(a)),f.onError(a)},f.onCompleted.bind(f))),h.add(a.subscribe(function(a){var b=q++;o.add(b,a);var d=new k;h.add(d);var e,i=function(){o.remove(b),h.remove(d)};try{e=c(a)}catch(j){return n.getValues().forEach(g(j)),void f.onError(j)}d.setDisposable(e.take(1).subscribe(t,function(a){n.getValues().forEach(g(a)),f.onError(a)},i)),n.getValues().forEach(function(b){b.onNext(a)})},function(a){n.getValues().forEach(g(a)),f.onError(a)})),l})},n.buffer=function(){return this.window.apply(this,arguments).selectMany(function(a){return a.toArray()})},n.window=function(a,b){return 1===arguments.length&&"function"!=typeof arguments[0]?f.call(this,a):"function"==typeof a?g.call(this,a):e.call(this,a,b)},n.pairwise=function(){var a=this;return new q(function(b){var c,d=!1;return a.subscribe(function(a){d?b.onNext([c,a]):d=!0,c=a},b.onError.bind(b),b.onCompleted.bind(b))})},n.partition=function(a,b){var c=this.publish().refCount();return[c.filter(a,b),c.filter(function(c,d,e){return!a.call(b,c,d,e)})]},n.groupBy=function(a,b,c){return this.groupByUntil(a,b,p,c)},n.groupByUntil=function(a,b,c,d){var e=this;return b||(b=u),d||(d=s),new q(function(f){function g(a){return function(b){b.onError(a)}}var h=new v(0,d),l=new i,n=new j(l);return l.add(e.subscribe(function(d){var e;try{e=a(d)}catch(i){return h.getValues().forEach(g(i)),void f.onError(i)}var j=!1,o=h.tryGetValue(e);if(o||(o=new m,h.set(e,o),j=!0),j){var p=new w(e,o,n),q=new w(e,o);try{duration=c(q)}catch(i){return h.getValues().forEach(g(i)),void f.onError(i)}f.onNext(p);var r=new k;l.add(r);var s=function(){h.remove(e)&&o.onCompleted(),l.remove(r)};r.setDisposable(duration.take(1).subscribe(t,function(a){h.getValues().forEach(g(a)),f.onError(a)},s))}var u;try{u=b(d)}catch(i){return h.getValues().forEach(g(i)),void f.onError(i)}o.onNext(u)},function(a){h.getValues().forEach(g(a)),f.onError(a)},function(){h.getValues().forEach(function(a){a.onCompleted()}),f.onCompleted()})),n})};var w=function(a){function b(a){return this.underlyingObservable.subscribe(a)}function c(c,d,e){a.call(this,b),this.key=c,this.underlyingObservable=e?new q(function(a){return new i(e.getDisposable(),d.subscribe(a))}):d}return inherits(c,a),c}(h);return c}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.compat.js b/ajax/libs/rxjs/2.3.9/rx.compat.js new file mode 100644 index 000000000..31ba3ddd8 --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.compat.js @@ -0,0 +1,4676 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { + + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, + isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || + '_es6shim_iterator_'; + // Bug for mozilla version + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Utilities + if (!Function.prototype.bind) { + Function.prototype.bind = function (that) { + var target = this, + args = slice.call(arguments, 1); + var bound = function () { + if (this instanceof bound) { + function F() { } + F.prototype = target.prototype; + var self = new F(); + var result = target.apply(self, args.concat(slice.call(arguments))); + if (Object(result) === result) { + return result; + } + return self; + } else { + return target.apply(that, args.concat(slice.call(arguments))); + } + }; + + return bound; + }; + } + +if (!Array.prototype.forEach) { + + Array.prototype.forEach = function (callback, thisArg) { + var T, k; + + if (this == null) { + throw new TypeError(" this is null or not defined"); + } + + var O = Object(this); + var len = O.length >>> 0; + + if (typeof callback !== "function") { + throw new TypeError(callback + " is not a function"); + } + + if (arguments.length > 1) { + T = thisArg; + } + + k = 0; + while (k < len) { + var kValue; + if (k in O) { + kValue = O[k]; + callback.call(T, kValue, k, O); + } + k++; + } + }; +} + + var boxedString = Object("a"), + splitString = boxedString[0] != "a" || !(0 in boxedString); + if (!Array.prototype.every) { + Array.prototype.every = function every(fun /*, thisp */) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self && !fun.call(thisp, self[i], i, object)) { + return false; + } + } + return true; + }; + } + + if (!Array.prototype.map) { + Array.prototype.map = function map(fun /*, thisp*/) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + result = Array(length), + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self) { + result[i] = fun.call(thisp, self[i], i, object); + } + } + return result; + }; + } + + if (!Array.prototype.filter) { + Array.prototype.filter = function (predicate) { + var results = [], item, t = new Object(this); + for (var i = 0, len = t.length >>> 0; i < len; i++) { + item = t[i]; + if (i in t && predicate.call(arguments[1], item, i, t)) { + results.push(item); + } + } + return results; + }; + } + + if (!Array.isArray) { + Array.isArray = function (arg) { + return {}.toString.call(arg) == arrayClass; + }; + } + + if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function indexOf(searchElement) { + var t = Object(this); + var len = t.length >>> 0; + if (len === 0) { + return -1; + } + var n = 0; + if (arguments.length > 1) { + n = Number(arguments[1]); + if (n !== n) { + n = 0; + } else if (n !== 0 && n != Infinity && n !== -Infinity) { + n = (n > 0 || -1) * Math.floor(Math.abs(n)); + } + } + if (n >= len) { + return -1; + } + var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); + for (; k < len; k++) { + if (k in t && t[k] === searchElement) { + return k; + } + } + return -1; + }; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { + return; + } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { + return; + } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = + SerialDisposable = Rx.SerialDisposable = (function () { + function BooleanDisposable () { + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + old && old.dispose(); + shouldDispose && value && value.dispose(); + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + old && old.dispose(); + }; + + return BooleanDisposable; + }()); + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + timeSpan < 0 && (timeSpan = 0); + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + (function (schedulerProto) { + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function scheduleInnerRecursive(action, self) { + action(function(dt) { self(action, dt); }); + } + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { self(_action); }); }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + }(Scheduler.prototype)); + + (function (schedulerProto) { + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, action); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var s = state; + + var id = setInterval(function () { + s = action(s); + }, period); + + return disposableCreate(function () { + clearInterval(id); + }); + }; + }(Scheduler.prototype)); + + (function (schedulerProto) { + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchError = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + }(Scheduler.prototype)); + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt); + + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + + currentScheduler.scheduleRequired = function () { return !queue; }; + currentScheduler.ensureTrampoline = function (action) { + if (!queue) { this.schedule(action); } else { action(); } + }; + + return currentScheduler; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, + dt = Scheduler.normalize(dueTime); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** @private */ + var CatchScheduler = (function (_super) { + + function localNow() { + return this._scheduler.now(); + } + + function scheduleNow(state, action) { + return this._scheduler.scheduleWithState(state, this._wrap(action)); + } + + function scheduleRelative(state, dueTime, action) { + return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); + } + + function scheduleAbsolute(state, dueTime, action) { + return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); + } + + inherits(CatchScheduler, _super); + + /** @private */ + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + /** @private */ + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + /** @private */ + CatchScheduler.prototype._wrap = function (action) { + var parent = this; + return function (self, state) { + try { + return action(parent._getRecursiveWrapper(self), state); + } catch (e) { + if (!parent._handler(e)) { throw e; } + return disposableEmpty; + } + }; + }; + + /** @private */ + CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { + if (this._recursiveOriginal !== scheduler) { + this._recursiveOriginal = scheduler; + var wrapper = this._clone(scheduler); + wrapper._recursiveOriginal = scheduler; + wrapper._recursiveWrapper = wrapper; + this._recursiveWrapper = wrapper; + } + return this._recursiveWrapper; + }; + + /** @private */ + CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var self = this, failed = false, d = new SingleAssignmentDisposable(); + + d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { + if (failed) { return null; } + try { + return action(state1); + } catch (e) { + failed = true; + if (!self._handler(e)) { throw e; } + d.dispose(); + return null; + } + })); + + return d; + }; + + return CatchScheduler; + }(Scheduler)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { + return observerOrOnNext && typeof observerOrOnNext === 'object' ? + this._acceptObservable(observerOrOnNext) : + this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notifications + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + Notification.prototype.toObservable = function (scheduler) { + var notification = this; + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + notification.kind === 'N' && observer.onCompleted(); + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + + function _accept (onNext) { return onNext(this.value); } + function _acceptObservable(observer) { return observer.onNext(this.value); } + function toString () { return 'OnNext(' + this.value + ')'; } + + return function (value) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + + function _accept (onNext, onError) { return onError(this.exception); } + function _acceptObservable(observer) { return observer.onError(this.exception); } + function toString () { return 'OnError(' + this.exception + ')'; } + + return function (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { return onCompleted(); } + function _acceptObservable(observer) { return observer.onCompleted(); } + function toString () { return 'OnCompleted()'; } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var CheckedObserver = (function (_super) { + inherits(CheckedObserver, _super); + + function CheckedObserver(observer) { + _super.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + try { + this._observer.onNext(value); + } catch (e) { + throw e; + } finally { + this._state = 0; + } + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + try { + this._observer.onError(err); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + try { + this._observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { + inherits(ScheduledObserver, _super); + + function ScheduledObserver(scheduler, observer) { + _super.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + /** @private */ + var ObserveOnObserver = (function (_super) { + inherits(ObserveOnObserver, _super); + + /** @private */ + function ObserveOnObserver() { + _super.apply(this, arguments); + } + + /** @private */ + ObserveOnObserver.prototype.next = function (value) { + _super.prototype.next.call(this, value); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.error = function (e) { + _super.prototype.error.call(this, e); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.completed = function () { + _super.prototype.completed.call(this); + this.ensureActive(); + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber = typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted); + + return this._subscribe(subscriber); + }; + + return Observable; + })(); + + /** + * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + * + * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects + * that require to be run on a scheduler, use subscribeOn. + * + * @param {Scheduler} scheduler Scheduler to notify observers on. + * @returns {Observable} The source sequence whose observations happen on the specified scheduler. + */ + observableProto.observeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(new ObserveOnObserver(scheduler, observer)); + }); + }; + + /** + * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; + * see the remarks section for more information on the distinction between subscribeOn and observeOn. + + * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer + * callbacks on a scheduler, use observeOn. + + * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. + * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); + d.setDisposable(m); + m.setDisposable(scheduler.schedule(function () { + d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); + })); + return d; + }); + }; + + /** + * Converts a Promise to an Observable sequence + * @param {Promise} An ES6 Compliant promise. + * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. + */ + var observableFromPromise = Observable.fromPromise = function (promise) { + return observableDefer(function () { + var subject = new Rx.AsyncSubject(); + + promise.then( + function (value) { + if (!subject.isDisposed) { + subject.onNext(value); + subject.onCompleted(); + } + }, + subject.onError.bind(subject)); + + return subject; + }); + }; + /* + * Converts an existing observable sequence to an ES6 Compatible Promise + * @example + * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); + * + * // With config + * Rx.config.Promise = RSVP.Promise; + * var promise = Rx.Observable.return(42).toPromise(); + * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. + * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. + */ + observableProto.toPromise = function (promiseCtor) { + promiseCtor || (promiseCtor = Rx.config.Promise); + if (!promiseCtor) { + throw new Error('Promise type not provided nor in Rx.config.Promise'); + } + var source = this; + return new promiseCtor(function (resolve, reject) { + // No cancellation can be done + var value, hasValue = false; + source.subscribe(function (v) { + value = v; + hasValue = true; + }, function (err) { + reject(err); + }, function () { + if (hasValue) { + resolve(value); + } + }); + }); + }; + /** + * Creates a list from an observable sequence. + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + var self = this; + return new AnonymousObservable(function(observer) { + var arr = []; + return self.subscribe( + arr.push.bind(arr), + observer.onError.bind(observer), + function () { + observer.onNext(arr); + observer.onCompleted(); + }); + }); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.create = Observable.createWithDisposable = function (subscribe) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + var maxSafeInteger = Math.pow(2, 53) - 1; + + function numberIsFinite(value) { + return typeof value === 'number' && root.isFinite(value); + } + + function isNan(n) { + return n !== n; + } + + function isIterable(o) { + return o[$iterator$] !== undefined; + } + + function sign(value) { + var number = +value; + if (number === 0) { return number; } + if (isNaN(number)) { return number; } + return number < 0 ? -1 : 1; + } + + function toLength(o) { + var len = +o.length; + if (isNaN(len)) { return 0; } + if (len === 0 || !numberIsFinite(len)) { return len; } + len = sign(len) * Math.floor(Math.abs(len)); + if (len <= 0) { return 0; } + if (len > maxSafeInteger) { return maxSafeInteger; } + return len; + } + + function isCallable(f) { + return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; + } + + /** + * This method creates a new Observable sequence from an array-like or iterable object. + * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. + * @param {Function} [mapFn] Map function to call on every element of the array. + * @param {Any} [thisArg] The context to use calling the mapFn if provided. + * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + Observable.from = function (iterable, mapFn, thisArg, scheduler) { + if (iterable == null) { + throw new Error('iterable cannot be null.') + } + if (mapFn && !isCallable(mapFn)) { + throw new Error('mapFn when provided must be a function'); + } + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var list = Object(iterable), + objIsIterable = isIterable(list), + len = objIsIterable ? 0 : toLength(list), + it = objIsIterable ? list[$iterator$]() : null, + i = 0; + return scheduler.scheduleRecursive(function (self) { + if (i < len || objIsIterable) { + var result; + if (objIsIterable) { + var next = it.next(); + if (next.done) { + observer.onCompleted(); + return; + } + + result = next.value; + } else { + result = list[i]; + } + + if (mapFn && isCallable(mapFn)) { + try { + result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); + } catch (e) { + observer.onError(e); + return; + } + } + + observer.onNext(result); + i++; + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * var res = Rx.Observable.fromArray([1,2,3]); + * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0, len = array.length; + return scheduler.scheduleRecursive(function (self) { + if (count < len) { + observer.onNext(array[count++]); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. + * @returns {Observable} The generated sequence. + */ + Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var first = true, state = initialState; + return scheduler.scheduleRecursive(function (self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + } + } catch (exception) { + observer.onError(exception); + return; + } + if (hasResult) { + observer.onNext(result); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). + * @returns {Observable} An observable sequence whose observers will never get called. + */ + var observableNever = Observable.never = function () { + return new AnonymousObservable(function () { + return disposableEmpty; + }); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.of = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return observableFromArray(args); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + var observableOf = Observable.ofWithScheduler = function (scheduler) { + var len = arguments.length - 1, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } + return observableFromArray(args, scheduler); + }; + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.range(0, 10); + * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleRecursiveWithState(0, function (i, self) { + if (i < count) { + observer.onNext(start + i); + self(i + 1); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.repeat(42); + * var res = Rx.Observable.repeat(42, 4); + * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'just', and 'returnValue' for browsers 0) { + subscribe(q.shift()); + } else { + activeCount--; + isStopped && activeCount === 0 && observer.onCompleted(); + } + })); + } + group.add(sources.subscribe(function (innerSource) { + if (activeCount < maxConcurrentOrOther) { + activeCount++; + subscribe(innerSource); + } else { + q.push(innerSource); + } + }, observer.onError.bind(observer), function () { + isStopped = true; + activeCount === 0 && observer.onCompleted(); + })); + return group; + }); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * + * @example + * 1 - merged = Rx.Observable.merge(xs, ys, zs); + * 2 - merged = Rx.Observable.merge([xs, ys, zs]); + * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); + * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources; + if (!arguments[0]) { + scheduler = immediateScheduler; + sources = slice.call(arguments, 1); + } else if (arguments[0].now) { + scheduler = arguments[0]; + sources = slice.call(arguments, 1); + } else { + scheduler = immediateScheduler; + sources = slice.call(arguments, 0); + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableFromArray(sources, scheduler).mergeObservable(); + }; + + /** + * Merges an observable sequence of observable sequences into an observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.mergeObservable = observableProto.mergeAll =function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + isStopped = false, + m = new SingleAssignmentDisposable(); + + group.add(m); + m.setDisposable(sources.subscribe(function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + innerSubscription.setDisposable(innerSource.subscribe(function (x) { + observer.onNext(x); + }, observer.onError.bind(observer), function () { + group.remove(innerSubscription); + if (isStopped && group.length === 1) { observer.onCompleted(); } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (group.length === 1) { observer.onCompleted(); } + })); + return group; + }); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. + * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. + */ + observableProto.onErrorResumeNext = function (second) { + if (!second) { + throw new Error('Second observable is required'); + } + return onErrorResumeNext([this, second]); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * + * @example + * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); + * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); + * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. + */ + var onErrorResumeNext = Observable.onErrorResumeNext = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var pos = 0, subscription = new SerialDisposable(), + cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, d; + if (pos < sources.length) { + current = sources[pos++]; + isPromise(current) && (current = observableFromPromise(current)); + d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { + self(); + }, function () { + self(); + })); + } else { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + isOpen && observer.onNext(left); + }, observer.onError.bind(observer), function () { + isOpen && observer.onCompleted(); + })); + + isPromise(other) && (other = observableFromPromise(other)); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, observer.onError.bind(observer), function () { + rightSubscription.dispose(); + })); + + return disposables; + }); + }; + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasLatest = false, + innerSubscription = new SerialDisposable(), + isStopped = false, + latest = 0, + subscription = sources.subscribe(function (innerSource) { + var d = new SingleAssignmentDisposable(), id = ++latest; + hasLatest = true; + innerSubscription.setDisposable(d); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + d.setDisposable(innerSource.subscribe(function (x) { + if (latest === id) { + observer.onNext(x); + } + }, function (e) { + if (latest === id) { + observer.onError(e); + } + }, function () { + if (latest === id) { + hasLatest = false; + if (isStopped) { + observer.onCompleted(); + } + } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (!hasLatest) { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, innerSubscription); + }); + }; + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + isPromise(other) && (other = observableFromPromise(other)); + return new CompositeDisposable( + source.subscribe(observer), + other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) + ); + }); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], result; + try { + result = resultSelector(left, right); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + } else { + observer.onCompleted(); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. + * + * @example + * 1 - res = obs1.zip(obs2, fn); + * 1 - res = x1.zip([1,2,3], fn); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { + return zipArray.apply(this, arguments); + } + var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); + sources.unshift(parent); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + var res, queuedValues; + if (queues.every(function (x) { return x.length > 0; })) { + try { + queuedValues = queues.map(function (x) { return x.shift(); }); + res = resultSelector.apply(parent, queuedValues); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(function (x) { return x; })) { + observer.onCompleted(); + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = sources[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + * @param arguments Observable sources. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var args = slice.call(arguments, 0), + first = args.shift(); + return first.zip.apply(first, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + return; + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(identity)) { + observer.onCompleted(); + return; + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + })(idx); + } + + var compositeDisposable = new CompositeDisposable(subscriptions); + compositeDisposable.add(disposableCreate(function () { + for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { + queues[qIdx] = []; + } + })); + return compositeDisposable; + }); + }; + + /** + * Hides the identity of an observable sequence. + * @returns {Observable} An observable sequence that hides the identity of the source sequence. + */ + observableProto.asObservable = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(observer); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. + * + * @example + * var res = xs.bufferWithCount(10); + * var res = xs.bufferWithCount(10, 1); + * @param {Number} count Length of each buffer. + * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithCount = function (count, skip) { + if (typeof skip !== 'number') { + skip = count; + } + return this.windowWithCount(count, skip).selectMany(function (x) { + return x.toArray(); + }).where(function (x) { + return x.length > 0; + }); + }; + + /** + * Dematerializes the explicit notification values of an observable sequence as implicit notifications. + * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + return x.accept(observer); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + * + * var obs = observable.distinctUntilChanged(); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. + * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. + * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + observableProto.distinctUntilChanged = function (keySelector, comparer) { + var source = this; + keySelector || (keySelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var comparerEquals = false, key; + try { + key = keySelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + if (hasCurrentKey) { + try { + comparerEquals = comparer(currentKey, key); + } catch (exception) { + observer.onError(exception); + return; + } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + observer.onNext(value); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * + * @example + * var res = observable.do(observer); + * var res = observable.do(onNext); + * var res = observable.do(onNext, onError); + * var res = observable.do(onNext, onError, onCompleted); + * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { + var source = this, onNextFunc; + if (typeof observerOrOnNext === 'function') { + onNextFunc = observerOrOnNext; + } else { + onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); + onError = observerOrOnNext.onError.bind(observerOrOnNext); + onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); + } + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + try { + onNextFunc(x); + } catch (e) { + observer.onError(e); + } + observer.onNext(x); + }, function (err) { + if (!onError) { + observer.onError(err); + } else { + try { + onError(err); + } catch (e) { + observer.onError(e); + } + observer.onError(err); + } + }, function () { + if (!onCompleted) { + observer.onCompleted(); + } else { + try { + onCompleted(); + } catch (e) { + observer.onError(e); + } + observer.onCompleted(); + } + }); + }); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * + * @example + * var res = observable.finallyAction(function () { console.log('sequence ended'; }); + * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. + * @returns {Observable} Source sequence with the action-invoking termination behavior applied. + */ + observableProto['finally'] = observableProto.finallyAction = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription; + try { + subscription = source.subscribe(observer); + } catch (e) { + action(); + throw e; + } + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Materializes the implicit notifications of an observable sequence as explicit notification values. + * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. + */ + observableProto.materialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (value) { + observer.onNext(notificationCreateOnNext(value)); + }, function (e) { + observer.onNext(notificationCreateOnError(e)); + observer.onCompleted(); + }, function () { + observer.onNext(notificationCreateOnCompleted()); + observer.onCompleted(); + }); + }); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * + * @example + * var res = repeated = source.repeat(); + * var res = repeated = source.repeat(42); + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + observableProto.repeat = function (repeatCount) { + return enumerableRepeat(this, repeatCount).concat(); + }; + + /** + * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. + * Note if you encounter an error and want it to retry once, then you must use .retry(2); + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(2); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchException(); + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @example + * var res = source.scan(function (acc, x) { return acc + x; }); + * var res = source.scan(0, function (acc, x) { return acc + x; }); + * @param {Mixed} [seed] The initial accumulator value. + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @returns {Observable} An observable sequence containing the accumulated values. + */ + observableProto.scan = function () { + var hasSeed = false, seed, accumulator, source = this; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[0]; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return new AnonymousObservable(function (observer) { + var hasAccumulation, accumulation, hasValue; + return source.subscribe ( + function (x) { + try { + if (!hasValue) { + hasValue = true; + } + + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(accumulation); + }, + observer.onError.bind(observer), + function () { + if (!hasValue && hasSeed) { + observer.onNext(seed); + } + observer.onCompleted(); + } + ); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + observer.onNext(q.shift()); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * + * @memberOf Observable# + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && 'now' in Object(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + values = slice.call(arguments, start); + return enumerableFor([observableFromArray(values, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence. + * + * @example + * var res = source.takeLast(5); + * + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, observer.onError.bind(observer), function () { + while(q.length > 0) { observer.onNext(q.shift()); } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, observer.onError.bind(observer), function () { + observer.onNext(q); + observer.onCompleted(); + }); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. + * + * var res = xs.windowWithCount(10); + * var res = xs.windowWithCount(10, 1); + * @param {Number} count Length of each window. + * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithCount = function (count, skip) { + var source = this; + if (count <= 0) { + throw new Error(argumentOutOfRange); + } + if (arguments.length === 1) { + skip = count; + } + if (skip <= 0) { + throw new Error(argumentOutOfRange); + } + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), + refCountDisposable = new RefCountDisposable(m), + n = 0, + q = [], + createWindow = function () { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + }; + createWindow(); + m.setDisposable(source.subscribe(function (x) { + var s; + for (var i = 0, len = q.length; i < len; i++) { + q[i].onNext(x); + } + var c = n - count + 1; + if (c >= 0 && c % skip === 0) { + s = q.shift(); + s.onCompleted(); + } + n++; + if (n % skip === 0) { + createWindow(); + } + }, function (exception) { + while (q.length > 0) { + q.shift().onError(exception); + } + observer.onError(exception); + }, function () { + while (q.length > 0) { + q.shift().onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + function concatMap(source, selector, thisArg) { + return source.map(function (x, i) { + var result = selector.call(thisArg, x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).concatAll(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { + if (resultSelector) { + return this.concatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }); + } + return typeof selector === 'function' ? + concatMap(this, selector, thisArg) : + concatMap(this, function () { return selector; }); + }; + + /** + * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. + * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. + * @param {Function} onError A transform function to apply when an error occurs in the source sequence. + * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. + * @param {Any} [thisArg] An optional "this" to use to invoke each transform. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. + */ + observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + var result; + try { + result = onNext.call(thisArg, x, index++); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + }, + function (err) { + var result; + try { + result = onError.call(thisArg, err); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }, + function () { + var result; + try { + result = onCompleted.call(thisArg); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }); + }).concatAll(); + }; + /** + * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * var res = obs = xs.defaultIfEmpty(); + * 2 - obs = xs.defaultIfEmpty(false); + * + * @memberOf Observable# + * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. + * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. + */ + observableProto.defaultIfEmpty = function (defaultValue) { + var source = this; + if (defaultValue === undefined) { + defaultValue = null; + } + return new AnonymousObservable(function (observer) { + var found = false; + return source.subscribe(function (x) { + found = true; + observer.onNext(x); + }, observer.onError.bind(observer), function () { + if (!found) { + observer.onNext(defaultValue); + } + observer.onCompleted(); + }); + }); + }; + + // Swap out for Array.findIndex + function arrayIndexOfComparer(array, item, comparer) { + for (var i = 0, len = array.length; i < len; i++) { + if (comparer(array[i], item)) { return i; } + } + return -1; + } + + function HashSet(comparer) { + this.comparer = comparer; + this.set = []; + } + HashSet.prototype.push = function(value) { + var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; + retValue && this.set.push(value); + return retValue; + }; + + /** + * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. + * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. + * + * @example + * var res = obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [comparer] Used to compare items in the collection. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, comparer) { + var source = this; + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hashSet = new HashSet(comparer); + return source.subscribe(function (x) { + var key = x; + + if (keySelector) { + try { + key = keySelector(x); + } catch (e) { + observer.onError(e); + return; + } + } + hashSet.push(key) && observer.onNext(x); + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer)); + }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + observableProto.select = observableProto.map = function (selector, thisArg) { + var parent = this; + return new AnonymousObservable(function (observer) { + var count = 0; + return parent.subscribe(function (value) { + var result; + try { + result = selector.call(thisArg, value, count++, parent); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Retrieves the value of a specified property from all elements in the Observable sequence. + * @param {String} property The property to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function (property) { + return this.select(function (x) { return x[property]; }); + }; + + function flatMap(source, selector, thisArg) { + return source.map(function (x, i) { + var result = selector.call(thisArg, x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).mergeObservable(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { + if (resultSelector) { + return this.flatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }, thisArg); + } + return typeof selector === 'function' ? + flatMap(this, selector, thisArg) : + flatMap(this, function () { return selector; }); + }; + + /** + * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. + * @param {Function} onError A transform function to apply when an error occurs in the source sequence. + * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. + * @param {Any} [thisArg] An optional "this" to use to invoke each transform. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. + */ + observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + var result; + try { + result = onNext.call(thisArg, x, index++); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + }, + function (err) { + var result; + try { + result = onError.call(thisArg, err); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }, + function () { + var result; + try { + result = onCompleted.call(thisArg); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }); + }).mergeAll(); + }; + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { + throw new Error(argumentOutOfRange); + } + var observable = this; + return new AnonymousObservable(function (observer) { + var remaining = count; + return observable.subscribe(function (x) { + if (remaining <= 0) { + observer.onNext(x); + } else { + remaining--; + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + * The element's index is used in the logic of the predicate function. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !predicate.call(thisArg, x, i++, source); + } catch (e) { + observer.onError(e); + return; + } + } + if (running) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case -1:void 0});return c.pop(),d.pop(),result}function k(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:lb.call(a)}function l(a,b){for(var c=new Array(a),d=0;a>d;d++)c[d]=b();return c}function m(a,b){this.scheduler=a,this.disposable=b,this.isDisposed=!1}function n(a){return"number"==typeof a&&z.isFinite(a)}function o(b){return b[P]!==a}function p(a){var b=+a;return 0===b?b:isNaN(b)?b:0>b?-1:1}function q(a){var b=+a.length;return isNaN(b)?0:0!==b&&n(b)?(b=p(b)*Math.floor(Math.abs(b)),0>=b?0:b>bc?bc:b):b}function r(a){return"[object Function]"===Object.prototype.toString.call(a)&&"function"==typeof a}function s(a,b){return new lc(function(c){var d=new zb,e=new SerialDisposable;return e.setDisposable(d),d.setDisposable(a.subscribe(c.onNext.bind(c),function(a){var d,f;try{f=b(a)}catch(g){return void c.onError(g)}M(f)&&(f=$b(f)),d=new zb,e.setDisposable(d),d.setDisposable(f.subscribe(c))},c.onCompleted.bind(c))),e})}function t(a,b){var c=this;return new lc(function(d){var e=0,f=a.length;return c.subscribe(function(c){if(f>e){var g,h=a[e++];try{g=b(c,h)}catch(i){return void d.onError(i)}d.onNext(g)}else d.onCompleted()},d.onError.bind(d),d.onCompleted.bind(d))})}function u(a,b,c){return a.map(function(a,d){var e=b.call(c,a,d);return M(e)?$b(e):e}).concatAll()}function v(a,b,c){for(var d=0,e=a.length;e>d;d++)if(c(a[d],b))return d;return-1}function w(a){this.comparer=a,this.set=[]}function x(a,b,c){return a.map(function(a,d){var e=b.call(c,a,d);return M(e)?$b(e):e}).mergeObservable()}var y={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},z=y[typeof window]&&window||this,A=y[typeof exports]&&exports&&!exports.nodeType&&exports,B=y[typeof module]&&module&&!module.nodeType&&module,C=B&&B.exports===A&&A,D=y[typeof global]&&global;!D||D.global!==D&&D.window!==D||(z=D);var E={internals:{},config:{Promise:z.Promise},helpers:{}},F=E.helpers.noop=function(){},G=(E.helpers.notDefined=function(a){return"undefined"==typeof a},E.helpers.isScheduler=function(a){return a instanceof E.Scheduler}),H=E.helpers.identity=function(a){return a},I=(E.helpers.pluck=function(a){return function(b){return b[a]}},E.helpers.just=function(a){return function(){return a}},E.helpers.defaultNow=function(){return Date.now?Date.now:function(){return+new Date}}()),J=E.helpers.defaultComparer=function(a,b){return kb(a,b)},K=E.helpers.defaultSubComparer=function(a,b){return a>b?1:b>a?-1:0},L=(E.helpers.defaultKeySerializer=function(a){return a.toString()},E.helpers.defaultError=function(a){throw a}),M=E.helpers.isPromise=function(a){return!!a&&"function"==typeof a.then},N=(E.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},E.helpers.not=function(a){return!a},"Argument out of range"),O="Object has been disposed",P="function"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";z.Set&&"function"==typeof(new z.Set)["@@iterator"]&&(P="@@iterator");var Q,R={done:!0,value:a},S="[object Arguments]",T="[object Array]",U="[object Boolean]",V="[object Date]",W="[object Error]",X="[object Function]",Y="[object Number]",Z="[object Object]",$="[object RegExp]",_="[object String]",ab=Object.prototype.toString,bb=Object.prototype.hasOwnProperty,cb=ab.call(arguments)==S,db=Error.prototype,eb=Object.prototype,fb=eb.propertyIsEnumerable;try{Q=!(ab.call(document)==Z&&!({toString:0}+""))}catch(gb){Q=!0}var hb=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ib={};ib[T]=ib[V]=ib[Y]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},ib[U]=ib[_]={constructor:!0,toString:!0,valueOf:!0},ib[W]=ib[X]=ib[$]={constructor:!0,toString:!0},ib[Z]={constructor:!0};var jb={};!function(){var a=function(){this.x=1},b=[];a.prototype={valueOf:1,y:1};for(var c in new a)b.push(c);for(c in arguments);jb.enumErrorProps=fb.call(db,"message")||fb.call(db,"name"),jb.enumPrototypes=fb.call(a,"prototype"),jb.nonEnumArgs=0!=c,jb.nonEnumShadows=!/valueOf/.test(b)}(1),cb||(h=function(a){return a&&"object"==typeof a?bb.call(a,"callee"):!1}),i(/x/)&&(i=function(a){return"function"==typeof a&&ab.call(a)==X});var kb=E.internals.isEqual=function(a,b){return j(a,b,[],[])},lb=Array.prototype.slice,mb=({}.hasOwnProperty,this.inherits=E.internals.inherits=function(a,b){function c(){this.constructor=a}c.prototype=b.prototype,a.prototype=new c}),nb=E.internals.addProperties=function(a){for(var b=lb.call(arguments,1),c=0,d=b.length;d>c;c++){var e=b[c];for(var f in e)a[f]=e[f]}},ob=E.internals.addRef=function(a,b){return new lc(function(c){return new ub(b.getDisposable(),a.subscribe(c))})};Function.prototype.bind||(Function.prototype.bind=function(a){var b=this,c=lb.call(arguments,1),d=function(){function e(){}if(this instanceof d){e.prototype=b.prototype;var f=new e,g=b.apply(f,c.concat(lb.call(arguments)));return Object(g)===g?g:f}return b.apply(a,c.concat(lb.call(arguments)))};return d}),Array.prototype.forEach||(Array.prototype.forEach=function(a,b){var c,d;if(null==this)throw new TypeError(" this is null or not defined");var e=Object(this),f=e.length>>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(arguments.length>1&&(c=b),d=0;f>d;){var g;d in e&&(g=e[d],a.call(c,g,d,e)),d++}});var pb=Object("a"),qb="a"!=pb[0]||!(0 in pb);Array.prototype.every||(Array.prototype.every=function(a){var b=Object(this),c=qb&&{}.toString.call(this)==_?this.split(""):b,d=c.length>>>0,e=arguments[1];if({}.toString.call(a)!=X)throw new TypeError(a+" is not a function");for(var f=0;d>f;f++)if(f in c&&!a.call(e,c[f],f,b))return!1;return!0}),Array.prototype.map||(Array.prototype.map=function(a){var b=Object(this),c=qb&&{}.toString.call(this)==_?this.split(""):b,d=c.length>>>0,e=Array(d),f=arguments[1];if({}.toString.call(a)!=X)throw new TypeError(a+" is not a function");for(var g=0;d>g;g++)g in c&&(e[g]=a.call(f,c[g],g,b));return e}),Array.prototype.filter||(Array.prototype.filter=function(a){for(var b,c=[],d=new Object(this),e=0,f=d.length>>>0;f>e;e++)b=d[e],e in d&&a.call(arguments[1],b,e,d)&&c.push(b);return c}),Array.isArray||(Array.isArray=function(a){return{}.toString.call(a)==T}),Array.prototype.indexOf||(Array.prototype.indexOf=function(a){var b=Object(this),c=b.length>>>0;if(0===c)return-1;var d=0;if(arguments.length>1&&(d=Number(arguments[1]),d!==d?d=0:0!==d&&1/0!=d&&d!==-1/0&&(d=(d>0||-1)*Math.floor(Math.abs(d)))),d>=c)return-1;for(var e=d>=0?d:Math.max(c-Math.abs(d),0);c>e;e++)if(e in b&&b[e]===a)return e;return-1});var rb=function(a,b){this.id=a,this.value=b};rb.prototype.compareTo=function(a){var b=this.value.compareTo(a.value);return 0===b&&(b=this.id-a.id),b};var sb=E.internals.PriorityQueue=function(a){this.items=new Array(a),this.length=0},tb=sb.prototype;tb.isHigherPriority=function(a,b){return this.items[a].compareTo(this.items[b])<0},tb.percolate=function(a){if(!(a>=this.length||0>a)){var b=a-1>>1;if(!(0>b||b===a)&&this.isHigherPriority(a,b)){var c=this.items[a];this.items[a]=this.items[b],this.items[b]=c,this.percolate(b)}}},tb.heapify=function(b){if(b===a&&(b=0),!(b>=this.length||0>b)){var c=2*b+1,d=2*b+2,e=b;if(cb;b++)a[b].dispose()}},vb.toArray=function(){return this.disposables.slice(0)};var wb=E.Disposable=function(a){this.isDisposed=!1,this.action=a||F};wb.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var xb=wb.create=function(a){return new wb(a)},yb=wb.empty={dispose:F},zb=E.SingleAssignmentDisposable=SerialDisposable=E.SerialDisposable=function(){function a(){this.isDisposed=!1,this.current=null}var b=a.prototype;return b.getDisposable=function(){return this.current},b.setDisposable=function(a){var b,c=this.isDisposed;c||(b=this.current,this.current=a),b&&b.dispose(),c&&a&&a.dispose()},b.dispose=function(){var a;this.isDisposed||(this.isDisposed=!0,a=this.current,this.current=null),a&&a.dispose()},a}(),Ab=E.RefCountDisposable=function(){function a(a){this.disposable=a,this.disposable.count++,this.isInnerDisposed=!1}function b(a){this.underlyingDisposable=a,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return a.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},b.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},b.prototype.getDisposable=function(){return this.isDisposed?yb:new a(this)},b}();m.prototype.dispose=function(){var a=this;this.scheduler.schedule(function(){a.isDisposed||(a.isDisposed=!0,a.disposable.dispose())})};var Bb=E.internals.ScheduledItem=function(a,b,c,d,e){this.scheduler=a,this.state=b,this.action=c,this.dueTime=d,this.comparer=e||K,this.disposable=new zb};Bb.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},Bb.prototype.compareTo=function(a){return this.comparer(this.dueTime,a.dueTime)},Bb.prototype.isCancelled=function(){return this.disposable.isDisposed},Bb.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var Cb=E.Scheduler=function(){function a(a,b,c,d){this.now=a,this._schedule=b,this._scheduleRelative=c,this._scheduleAbsolute=d}function b(a,b){return b(),yb}var c=a.prototype;return c.schedule=function(a){return this._schedule(a,b)},c.scheduleWithState=function(a,b){return this._schedule(a,b)},c.scheduleWithRelative=function(a,c){return this._scheduleRelative(c,a,b)},c.scheduleWithRelativeAndState=function(a,b,c){return this._scheduleRelative(a,b,c)},c.scheduleWithAbsolute=function(a,c){return this._scheduleAbsolute(c,a,b)},c.scheduleWithAbsoluteAndState=function(a,b,c){return this._scheduleAbsolute(a,b,c)},a.now=I,a.normalize=function(a){return 0>a&&(a=0),a},a}(),Db=Cb.normalize;!function(a){function b(a,b){var c=b.first,d=b.second,e=new ub,f=function(b){d(b,function(b){var c=!1,d=!1,g=a.scheduleWithState(b,function(a,b){return c?e.remove(g):d=!0,f(b),yb});d||(e.add(g),c=!0)})};return f(c),e}function c(a,b,c){var d=b.first,e=b.second,f=new ub,g=function(b){e(b,function(b,d){var e=!1,h=!1,i=a[c].call(a,b,d,function(a,b){return e?f.remove(i):h=!0,g(b),yb});h||(f.add(i),e=!0)})};return g(d),f}function d(a,b){a(function(c){b(a,c)})}a.scheduleRecursive=function(a){return this.scheduleRecursiveWithState(a,function(a,b){a(function(){b(a)})})},a.scheduleRecursiveWithState=function(a,c){return this.scheduleWithState({first:a,second:c},b)},a.scheduleRecursiveWithRelative=function(a,b){return this.scheduleRecursiveWithRelativeAndState(b,a,d)},a.scheduleRecursiveWithRelativeAndState=function(a,b,d){return this._scheduleRelative({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithRelativeAndState")})},a.scheduleRecursiveWithAbsolute=function(a,b){return this.scheduleRecursiveWithAbsoluteAndState(b,a,d)},a.scheduleRecursiveWithAbsoluteAndState=function(a,b,d){return this._scheduleAbsolute({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithAbsoluteAndState")})}}(Cb.prototype),function(){Cb.prototype.schedulePeriodic=function(a,b){return this.schedulePeriodicWithState(null,a,b)},Cb.prototype.schedulePeriodicWithState=function(a,b,c){var d=a,e=setInterval(function(){d=c(d)},b);return xb(function(){clearInterval(e)})}}(Cb.prototype),function(a){a.catchError=a["catch"]=function(a){return new Ib(this,a)}}(Cb.prototype);var Eb,Fb=(E.internals.SchedulePeriodicRecursive=function(){function a(a,b){b(0,this._period);try{this._state=this._action(this._state)}catch(c){throw this._cancel.dispose(),c}}function b(a,b,c,d){this._scheduler=a,this._state=b,this._period=c,this._action=d}return b.prototype.start=function(){var b=new zb;return this._cancel=b,b.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,a.bind(this))),b},b}(),Cb.immediate=function(){function a(a,b){return b(this,a)}function b(a,b,c){for(var d=Db(d);d-this.now()>0;);return c(this,a)}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new Cb(I,a,b,c)}()),Gb=Cb.currentThread=function(){function a(a){for(var b;a.length>0;)if(b=a.dequeue(),!b.isCancelled()){for(;b.dueTime-Cb.now()>0;);b.isCancelled()||b.invoke()}}function b(a,b){return this.scheduleWithRelativeAndState(a,0,b)}function c(b,c,d){var f=this.now()+Cb.normalize(c),g=new Bb(this,b,d,f);if(e)e.enqueue(g);else{e=new sb(4),e.enqueue(g);try{a(e)}catch(h){throw h}finally{e=null}}return g.disposable}function d(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}var e,f=new Cb(I,b,c,d);return f.scheduleRequired=function(){return!e},f.ensureTrampoline=function(a){e?a():this.schedule(a)},f}(),Hb=F;!function(){function a(){if(!z.postMessage||z.importScripts)return!1;var a=!1,b=z.onmessage;return z.onmessage=function(){a=!0},z.postMessage("","*"),z.onmessage=b,a}function b(a){if("string"==typeof a.data&&a.data.substring(0,f.length)===f){var b=a.data.substring(f.length),c=g[b];c(),delete g[b]}}var c=RegExp("^"+String(ab).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),d="function"==typeof(d=D&&C&&D.setImmediate)&&!c.test(d)&&d,e="function"==typeof(e=D&&C&&D.clearImmediate)&&!c.test(e)&&e;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))Eb=process.nextTick;else if("function"==typeof d)Eb=d,Hb=e;else if(a()){var f="ms.rx.schedule"+Math.random(),g={},h=0;z.addEventListener?z.addEventListener("message",b,!1):z.attachEvent("onmessage",b,!1),Eb=function(a){var b=h++;g[b]=a,z.postMessage(f+b,"*")}}else if(z.MessageChannel){var i=new z.MessageChannel,j={},k=0;i.port1.onmessage=function(a){var b=a.data,c=j[b];c(),delete j[b]},Eb=function(a){var b=k++;j[b]=a,i.port2.postMessage(b)}}else"document"in z&&"onreadystatechange"in z.document.createElement("script")?Eb=function(a){var b=z.document.createElement("script");b.onreadystatechange=function(){a(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},z.document.documentElement.appendChild(b)}:(Eb=function(a){return setTimeout(a,0)},Hb=clearTimeout)}();var Ib=(Cb.timeout=function(){function a(a,b){var c=this,d=new zb,e=Eb(function(){d.isDisposed||d.setDisposable(b(c,a))});return new ub(d,xb(function(){Hb(e)}))}function b(a,b,c){var d=this,e=Cb.normalize(b);if(0===e)return d.scheduleWithState(a,c);var f=new zb,g=setTimeout(function(){f.isDisposed||f.setDisposable(c(d,a))},e);return new ub(f,xb(function(){clearTimeout(g)}))}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new Cb(I,a,b,c)}(),function(a){function b(){return this._scheduler.now()}function c(a,b){return this._scheduler.scheduleWithState(a,this._wrap(b))}function d(a,b,c){return this._scheduler.scheduleWithRelativeAndState(a,b,this._wrap(c))}function e(a,b,c){return this._scheduler.scheduleWithAbsoluteAndState(a,b,this._wrap(c))}function f(f,g){this._scheduler=f,this._handler=g,this._recursiveOriginal=null,this._recursiveWrapper=null,a.call(this,b,c,d,e)}return mb(f,a),f.prototype._clone=function(a){return new f(a,this._handler)},f.prototype._wrap=function(a){var b=this;return function(c,d){try{return a(b._getRecursiveWrapper(c),d)}catch(e){if(!b._handler(e))throw e;return yb}}},f.prototype._getRecursiveWrapper=function(a){if(this._recursiveOriginal!==a){this._recursiveOriginal=a;var b=this._clone(a);b._recursiveOriginal=a,b._recursiveWrapper=b,this._recursiveWrapper=b}return this._recursiveWrapper},f.prototype.schedulePeriodicWithState=function(a,b,c){var d=this,e=!1,f=new zb;return f.setDisposable(this._scheduler.schedulePeriodicWithState(a,b,function(a){if(e)return null;try{return c(a)}catch(b){if(e=!0,!d._handler(b))throw b;return f.dispose(),null}})),f},f}(Cb)),Jb=E.Notification=function(){function a(a,b){this.hasValue=null==b?!1:b,this.kind=a}return a.prototype.accept=function(a,b,c){return a&&"object"==typeof a?this._acceptObservable(a):this._accept(a,b,c)},a.prototype.toObservable=function(a){var b=this;return G(a)||(a=Fb),new lc(function(c){return a.schedule(function(){b._acceptObservable(c),"N"===b.kind&&c.onCompleted()})})},a}(),Kb=Jb.createOnNext=function(){function a(a){return a(this.value)}function b(a){return a.onNext(this.value)}function c(){return"OnNext("+this.value+")"}return function(d){var e=new Jb("N",!0);return e.value=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),Lb=Jb.createOnError=function(){function a(a,b){return b(this.exception)}function b(a){return a.onError(this.exception)}function c(){return"OnError("+this.exception+")"}return function(d){var e=new Jb("E");return e.exception=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),Mb=Jb.createOnCompleted=function(){function a(a,b,c){return c()}function b(a){return a.onCompleted()}function c(){return"OnCompleted()"}return function(){var d=new Jb("C");return d._accept=a,d._acceptObservable=b,d.toString=c,d}}(),Nb=E.internals.Enumerator=function(a){this._next=a};Nb.prototype.next=function(){return this._next()},Nb.prototype[P]=function(){return this};var Ob=E.internals.Enumerable=function(a){this._iterator=a};Ob.prototype[P]=function(){return this._iterator()},Ob.prototype.concat=function(){var a=this;return new lc(function(b){var c;try{c=a[P]()}catch(d){return void b.onError()}var e,f=new SerialDisposable,g=Fb.scheduleRecursive(function(a){var d;if(!e){try{d=c.next()}catch(g){return void b.onError(g)}if(d.done)return void b.onCompleted();var h=d.value;M(h)&&(h=$b(h));var i=new zb;f.setDisposable(i),i.setDisposable(h.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){a()}))}});return new ub(f,g,xb(function(){e=!0}))})},Ob.prototype.catchException=function(){var a=this;return new lc(function(b){var c;try{c=a[P]()}catch(d){return void b.onError()}var e,f,g=new SerialDisposable,h=Fb.scheduleRecursive(function(a){if(!e){var d;try{d=c.next()}catch(h){return void b.onError(h)}if(d.done)return void(f?b.onError(f):b.onCompleted());var i=d.value;M(i)&&(i=$b(i));var j=new zb;g.setDisposable(j),j.setDisposable(i.subscribe(b.onNext.bind(b),function(b){f=b,a()},b.onCompleted.bind(b)))}});return new ub(g,h,xb(function(){e=!0}))})};var Pb=Ob.repeat=function(a,b){return null==b&&(b=-1),new Ob(function(){var c=b;return new Nb(function(){return 0===c?R:(c>0&&c--,{done:!1,value:a})})})},Qb=Ob.forEach=function(a,b,c){return b||(b=H),new Ob(function(){var d=-1;return new Nb(function(){return++d0&&(a=!this.isAcquired,this.isAcquired=!0),a&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(a){var c;if(!(b.queue.length>0))return void(b.isAcquired=!1);c=b.queue.shift();try{c()}catch(d){throw b.queue=[],b.hasFaulted=!0,d}a()}))},b.prototype.dispose=function(){a.prototype.dispose.call(this),this.disposable.dispose()},b}(Ub),Yb=function(a){function b(){a.apply(this,arguments)}return mb(b,a),b.prototype.next=function(b){a.prototype.next.call(this,b),this.ensureActive()},b.prototype.error=function(b){a.prototype.error.call(this,b),this.ensureActive()},b.prototype.completed=function(){a.prototype.completed.call(this),this.ensureActive()},b}(Xb),Zb=E.Observable=function(){function a(a){this._subscribe=a}return Tb=a.prototype,Tb.subscribe=Tb.forEach=function(a,b,c){var d="object"==typeof a?a:Sb(a,b,c);return this._subscribe(d)},a}();Tb.observeOn=function(a){var b=this;return new lc(function(c){return b.subscribe(new Yb(a,c))})},Tb.subscribeOn=function(a){var b=this;return new lc(function(c){var d=new zb,e=new SerialDisposable;return e.setDisposable(d),d.setDisposable(a.schedule(function(){e.setDisposable(new m(a,b.subscribe(c)))})),e})};var $b=Zb.fromPromise=function(a){return _b(function(){var b=new E.AsyncSubject;return a.then(function(a){b.isDisposed||(b.onNext(a),b.onCompleted())},b.onError.bind(b)),b})};Tb.toPromise=function(a){if(a||(a=E.config.Promise),!a)throw new Error("Promise type not provided nor in Rx.config.Promise");var b=this;return new a(function(a,c){var d,e=!1;b.subscribe(function(a){d=a,e=!0},function(a){c(a)},function(){e&&a(d)})})},Tb.toArray=function(){var a=this;return new lc(function(b){var c=[];return a.subscribe(c.push.bind(c),b.onError.bind(b),function(){b.onNext(c),b.onCompleted()})})},Zb.create=Zb.createWithDisposable=function(a){return new lc(a)};var _b=Zb.defer=function(a){return new lc(function(b){var c;try{c=a()}catch(d){return fc(d).subscribe(b)}return M(c)&&(c=$b(c)),c.subscribe(b)})},ac=Zb.empty=function(a){return G(a)||(a=Fb),new lc(function(b){return a.schedule(function(){b.onCompleted()})})},bc=Math.pow(2,53)-1;Zb.from=function(a,b,c,d){if(null==a)throw new Error("iterable cannot be null.");if(b&&!r(b))throw new Error("mapFn when provided must be a function");return G(d)||(d=Gb),new lc(function(e){var f=Object(a),g=o(f),h=g?0:q(f),i=g?f[P]():null,j=0;return d.scheduleRecursive(function(a){if(h>j||g){var d;if(g){var k=i.next();if(k.done)return void e.onCompleted();d=k.value}else d=f[j];if(b&&r(b))try{d=c?b.call(c,d,j):b(d,j)}catch(l){return void e.onError(l)}e.onNext(d),j++,a()}else e.onCompleted()})})};var cc=Zb.fromArray=function(a,b){return G(b)||(b=Gb),new lc(function(c){var d=0,e=a.length;return b.scheduleRecursive(function(b){e>d?(c.onNext(a[d++]),b()):c.onCompleted()})})};Zb.generate=function(a,b,c,d,e){return G(e)||(e=Gb),new lc(function(f){var g=!0,h=a;return e.scheduleRecursive(function(a){var e,i;try{g?g=!1:h=c(h),e=b(h),e&&(i=d(h))}catch(j){return void f.onError(j)}e?(f.onNext(i),a()):f.onCompleted()})})};var dc=Zb.never=function(){return new lc(function(){return yb})};Zb.of=function(){for(var a=arguments.length,b=new Array(a),c=0;a>c;c++)b[c]=arguments[c];return cc(b)};Zb.ofWithScheduler=function(a){for(var b=arguments.length-1,c=new Array(b),d=0;b>d;d++)c[d]=arguments[d+1];return cc(c,a)};Zb.range=function(a,b,c){return G(c)||(c=Gb),new lc(function(d){return c.scheduleRecursiveWithState(0,function(c,e){b>c?(d.onNext(a+c),e(c+1)):d.onCompleted()})})},Zb.repeat=function(a,b,c){return G(c)||(c=Gb),ec(a,c).repeat(null==b?-1:b)};var ec=Zb["return"]=Zb.returnValue=Zb.just=function(a,b){return G(b)||(b=Fb),new lc(function(c){return b.schedule(function(){c.onNext(a),c.onCompleted()})})},fc=Zb["throw"]=Zb.throwException=function(a,b){return G(b)||(b=Fb),new lc(function(c){return b.schedule(function(){c.onError(a)})})};Zb.using=function(a,b){return new lc(function(c){var d,e,f=yb;try{d=a(),d&&(f=d),e=b(d)}catch(g){return new ub(fc(g).subscribe(c),f)}return new ub(e.subscribe(c),f)})},Tb.amb=function(a){var b=this;return new lc(function(c){function d(){f||(f=g,j.dispose())}function e(){f||(f=h,i.dispose())}var f,g="L",h="R",i=new zb,j=new zb;return M(a)&&(a=$b(a)),i.setDisposable(b.subscribe(function(a){d(),f===g&&c.onNext(a)},function(a){d(),f===g&&c.onError(a)},function(){d(),f===g&&c.onCompleted()})),j.setDisposable(a.subscribe(function(a){e(),f===h&&c.onNext(a)},function(a){e(),f===h&&c.onError(a)},function(){e(),f===h&&c.onCompleted()})),new ub(i,j)})},Zb.amb=function(){function a(a,b){return a.amb(b)}for(var b=dc(),c=k(arguments,0),d=0,e=c.length;e>d;d++)b=a(b,c[d]);return b},Tb["catch"]=Tb.catchException=function(a){return"function"==typeof a?s(this,a):gc([this,a])};var gc=Zb.catchException=Zb["catch"]=function(){var a=k(arguments,0);return Qb(a).catchException()};Tb.combineLatest=function(){var a=lb.call(arguments);return Array.isArray(a[0])?a[0].unshift(this):a.unshift(this),hc.apply(this,a)};var hc=Zb.combineLatest=function(){var a=lb.call(arguments),b=a.pop();return Array.isArray(a[0])&&(a=a[0]),new lc(function(c){function d(a){var d;if(h[a]=!0,i||(i=h.every(H))){try{d=b.apply(null,k)}catch(e){return void c.onError(e)}c.onNext(d)}else j.filter(function(b,c){return c!==a}).every(H)&&c.onCompleted()}function e(a){j[a]=!0,j.every(H)&&c.onCompleted()}for(var f=function(){return!1},g=a.length,h=l(g,f),i=!1,j=l(g,f),k=new Array(g),m=new Array(g),n=0;g>n;n++)!function(b){var f=a[b],g=new zb;M(f)&&(f=$b(f)),g.setDisposable(f.subscribe(function(a){k[b]=a,d(b)},c.onError.bind(c),function(){e(b)})),m[b]=g}(n);return new ub(m)})};Tb.concat=function(){var a=lb.call(arguments,0);return a.unshift(this),ic.apply(this,a)};var ic=Zb.concat=function(){var a=k(arguments,0);return Qb(a).concat()};Tb.concatObservable=Tb.concatAll=function(){return this.merge(1)},Tb.merge=function(a){if("number"!=typeof a)return jc(this,a);var b=this;return new lc(function(c){function d(a){var b=new zb;f.add(b),M(a)&&(a=$b(a)),b.setDisposable(a.subscribe(c.onNext.bind(c),c.onError.bind(c),function(){f.remove(b),h.length>0?d(h.shift()):(e--,g&&0===e&&c.onCompleted())}))}var e=0,f=new ub,g=!1,h=[];return f.add(b.subscribe(function(b){a>e?(e++,d(b)):h.push(b)},c.onError.bind(c),function(){g=!0,0===e&&c.onCompleted()})),f})};var jc=Zb.merge=function(){var a,b;return arguments[0]?arguments[0].now?(a=arguments[0],b=lb.call(arguments,1)):(a=Fb,b=lb.call(arguments,0)):(a=Fb,b=lb.call(arguments,1)),Array.isArray(b[0])&&(b=b[0]),cc(b,a).mergeObservable()};Tb.mergeObservable=Tb.mergeAll=function(){var a=this;return new lc(function(b){var c=new ub,d=!1,e=new zb;return c.add(e),e.setDisposable(a.subscribe(function(a){var e=new zb;c.add(e),M(a)&&(a=$b(a)),e.setDisposable(a.subscribe(function(a){b.onNext(a)},b.onError.bind(b),function(){c.remove(e),d&&1===c.length&&b.onCompleted()}))},b.onError.bind(b),function(){d=!0,1===c.length&&b.onCompleted()})),c})},Tb.onErrorResumeNext=function(a){if(!a)throw new Error("Second observable is required");return kc([this,a])};var kc=Zb.onErrorResumeNext=function(){var a=k(arguments,0);return new lc(function(b){var c=0,d=new SerialDisposable,e=Fb.scheduleRecursive(function(e){var f,g;c0})){try{f=h.map(function(a){return a.shift()}),e=c.apply(a,f)}catch(g){return void d.onError(g)}d.onNext(e)}else i.filter(function(a,c){return c!==b}).every(H)&&d.onCompleted()}function f(a){i[a]=!0,i.every(function(a){return a})&&d.onCompleted()}for(var g=b.length,h=l(g,function(){return[]}),i=l(g,function(){return!1}),j=new Array(g),k=0;g>k;k++)!function(a){var c=b[a],g=new zb;M(c)&&(c=$b(c)),g.setDisposable(c.subscribe(function(b){h[a].push(b),e(a)},d.onError.bind(d),function(){f(a)})),j[a]=g}(k);return new ub(j)})},Zb.zip=function(){var a=lb.call(arguments,0),b=a.shift();return b.zip.apply(b,a)},Zb.zipArray=function(){var a=k(arguments,0);return new lc(function(b){function c(a){if(f.every(function(a){return a.length>0})){var c=f.map(function(a){return a.shift()});b.onNext(c)}else if(g.filter(function(b,c){return c!==a}).every(H))return void b.onCompleted()}function d(a){return g[a]=!0,g.every(H)?void b.onCompleted():void 0}for(var e=a.length,f=l(e,function(){return[]}),g=l(e,function(){return!1}),h=new Array(e),i=0;e>i;i++)!function(e){h[e]=new zb,h[e].setDisposable(a[e].subscribe(function(a){f[e].push(a),c(e)},b.onError.bind(b),function(){d(e)}))}(i);var j=new ub(h);return j.add(xb(function(){for(var a=0,b=f.length;b>a;a++)f[a]=[]})),j})},Tb.asObservable=function(){var a=this;return new lc(function(b){return a.subscribe(b)})},Tb.bufferWithCount=function(a,b){return"number"!=typeof b&&(b=a),this.windowWithCount(a,b).selectMany(function(a){return a.toArray()}).where(function(a){return a.length>0})},Tb.dematerialize=function(){var a=this;return new lc(function(b){return a.subscribe(function(a){return a.accept(b)},b.onError.bind(b),b.onCompleted.bind(b))})},Tb.distinctUntilChanged=function(a,b){var c=this;return a||(a=H),b||(b=J),new lc(function(d){var e,f=!1;return c.subscribe(function(c){var g,h=!1;try{g=a(c)}catch(i){return void d.onError(i)}if(f)try{h=b(e,g)}catch(i){return void d.onError(i)}f&&h||(f=!0,e=g,d.onNext(c))},d.onError.bind(d),d.onCompleted.bind(d))})},Tb["do"]=Tb.doAction=Tb.tap=function(a,b,c){var d,e=this;return"function"==typeof a?d=a:(d=a.onNext.bind(a),b=a.onError.bind(a),c=a.onCompleted.bind(a)),new lc(function(a){return e.subscribe(function(b){try{d(b)}catch(c){a.onError(c)}a.onNext(b)},function(c){if(b){try{b(c)}catch(d){a.onError(d)}a.onError(c)}else a.onError(c)},function(){if(c){try{c()}catch(b){a.onError(b)}a.onCompleted()}else a.onCompleted()})})},Tb["finally"]=Tb.finallyAction=function(a){var b=this;return new lc(function(c){var d;try{d=b.subscribe(c)}catch(e){throw a(),e}return xb(function(){try{d.dispose()}catch(b){throw b}finally{a()}})})},Tb.ignoreElements=function(){var a=this;return new lc(function(b){return a.subscribe(F,b.onError.bind(b),b.onCompleted.bind(b))})},Tb.materialize=function(){var a=this;return new lc(function(b){return a.subscribe(function(a){b.onNext(Kb(a))},function(a){b.onNext(Lb(a)),b.onCompleted()},function(){b.onNext(Mb()),b.onCompleted()})})},Tb.repeat=function(a){return Pb(this,a).concat()},Tb.retry=function(a){return Pb(this,a).catchException()},Tb.scan=function(){var a,b,c=!1,d=this;return 2===arguments.length?(c=!0,a=arguments[0],b=arguments[1]):b=arguments[0],new lc(function(e){var f,g,h;return d.subscribe(function(d){try{h||(h=!0),f?g=b(g,d):(g=c?b(a,d):d,f=!0)}catch(i){return void e.onError(i)}e.onNext(g)},e.onError.bind(e),function(){!h&&c&&e.onNext(a),e.onCompleted()})})},Tb.skipLast=function(a){var b=this;return new lc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&c.onNext(d.shift())},c.onError.bind(c),c.onCompleted.bind(c))})},Tb.startWith=function(){var a,b,c=0;return arguments.length&&"now"in Object(arguments[0])?(b=arguments[0],c=1):b=Fb,a=lb.call(arguments,c),Qb([cc(a,b),this]).concat()},Tb.takeLast=function(a){var b=this;return new lc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&d.shift()},c.onError.bind(c),function(){for(;d.length>0;)c.onNext(d.shift());c.onCompleted()})})},Tb.takeLastBuffer=function(a){var b=this;return new lc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&d.shift()},c.onError.bind(c),function(){c.onNext(d),c.onCompleted()})})},Tb.windowWithCount=function(a,b){var c=this;if(0>=a)throw new Error(N);if(1===arguments.length&&(b=a),0>=b)throw new Error(N);return new lc(function(d){var e=new zb,f=new Ab(e),g=0,h=[],i=function(){var a=new oc;h.push(a),d.onNext(ob(a,f))};return i(),e.setDisposable(c.subscribe(function(c){for(var d,e=0,f=h.length;f>e;e++)h[e].onNext(c);var j=g-a+1;j>=0&&j%b===0&&(d=h.shift(),d.onCompleted()),g++,g%b===0&&i()},function(a){for(;h.length>0;)h.shift().onError(a);d.onError(a)},function(){for(;h.length>0;)h.shift().onCompleted();d.onCompleted()})),f})},Tb.selectConcat=Tb.concatMap=function(a,b,c){return b?this.concatMap(function(c,d){var e=a(c,d),f=M(e)?$b(e):e;return f.map(function(a){return b(c,a,d)})}):"function"==typeof a?u(this,a,c):u(this,function(){return a})},Tb.concatMapObserver=Tb.selectConcatObserver=function(a,b,c,d){var e=this;return new lc(function(f){var g=0;return e.subscribe(function(b){var c;try{c=a.call(d,b,g++)}catch(e){return void f.onError(e)}M(c)&&(c=$b(c)),f.onNext(c)},function(a){var c;try{c=b.call(d,a)}catch(e){return void f.onError(e)}M(c)&&(c=$b(c)),f.onNext(c),f.onCompleted()},function(){var a;try{a=c.call(d)}catch(b){return void f.onError(b)}M(a)&&(a=$b(a)),f.onNext(a),f.onCompleted()})}).concatAll()},Tb.defaultIfEmpty=function(b){var c=this;return b===a&&(b=null),new lc(function(a){var d=!1;return c.subscribe(function(b){d=!0,a.onNext(b)},a.onError.bind(a),function(){d||a.onNext(b),a.onCompleted()})})},w.prototype.push=function(a){var b=-1===v(this.set,a,this.comparer);return b&&this.set.push(a),b},Tb.distinct=function(a,b){var c=this;return b||(b=J),new lc(function(d){var e=new w(b);return c.subscribe(function(b){var c=b;if(a)try{c=a(b)}catch(f){return void d.onError(f)}e.push(c)&&d.onNext(b)},d.onError.bind(d),d.onCompleted.bind(d))})},Tb.select=Tb.map=function(a,b){var c=this;return new lc(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},Tb.pluck=function(a){return this.select(function(b){return b[a]})},Tb.selectMany=Tb.flatMap=function(a,b,c){return b?this.flatMap(function(c,d){var e=a(c,d),f=M(e)?$b(e):e;return f.map(function(a){return b(c,a,d)})},c):"function"==typeof a?x(this,a,c):x(this,function(){return a})},Tb.flatMapObserver=Tb.selectManyObserver=function(a,b,c,d){var e=this;return new lc(function(f){var g=0;return e.subscribe(function(b){var c;try{c=a.call(d,b,g++)}catch(e){return void f.onError(e)}M(c)&&(c=$b(c)),f.onNext(c)},function(a){var c;try{c=b.call(d,a)}catch(e){return void f.onError(e)}M(c)&&(c=$b(c)),f.onNext(c),f.onCompleted()},function(){var a;try{a=c.call(d)}catch(b){return void f.onError(b)}M(a)&&(a=$b(a)),f.onNext(a),f.onCompleted()})}).mergeAll()},Tb.selectSwitch=Tb.flatMapLatest=Tb.switchMap=function(a,b){return this.select(a,b).switchLatest()},Tb.skip=function(a){if(0>a)throw new Error(N);var b=this;return new lc(function(c){var d=a;return b.subscribe(function(a){0>=d?c.onNext(a):d--},c.onError.bind(c),c.onCompleted.bind(c))})},Tb.skipWhile=function(a,b){var c=this;return new lc(function(d){var e=0,f=!1;return c.subscribe(function(g){if(!f)try{f=!a.call(b,g,e++,c)}catch(h){return void d.onError(h)}f&&d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},Tb.take=function(a,b){if(0>a)throw new Error(N);if(0===a)return ac(b);var c=this;return new lc(function(b){var d=a;return c.subscribe(function(a){d>0&&(d--,b.onNext(a),0===d&&b.onCompleted())},b.onError.bind(b),b.onCompleted.bind(b))})},Tb.takeWhile=function(a,b){var c=this;return new lc(function(d){var e=0,f=!0;return c.subscribe(function(g){if(f){try{f=a.call(b,g,e++,c)}catch(h){return void d.onError(h)}f?d.onNext(g):d.onCompleted()}},d.onError.bind(d),d.onCompleted.bind(d))})},Tb.where=Tb.filter=function(a,b){var c=this;return new lc(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}g&&d.onNext(f)},d.onError.bind(d),d.onCompleted.bind(d))})},Tb.exclusive=function(){var a=this;return new lc(function(b){var c=!1,d=!1,e=new zb,f=new ub;return f.add(e),e.setDisposable(a.subscribe(function(a){if(!c){c=!0,M(a)&&(a=$b(a));var e=new zb;f.add(e),e.setDisposable(a.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){f.remove(e),c=!1,d&&1===f.length&&b.onCompleted()}))}},b.onError.bind(b),function(){d=!0,c||1!==f.length||b.onCompleted()})),f})},Tb.exclusiveMap=function(a,b){var c=this;return new lc(function(d){var e=0,f=!1,g=!0,h=new zb,i=new ub;return i.add(h),h.setDisposable(c.subscribe(function(c){f||(f=!0,innerSubscription=new zb,i.add(innerSubscription),M(c)&&(c=$b(c)),innerSubscription.setDisposable(c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}d.onNext(g)},d.onError.bind(d),function(){i.remove(innerSubscription),f=!1,g&&1===i.length&&d.onCompleted()})))},d.onError.bind(d),function(){g=!0,1!==i.length||f||d.onCompleted()})),i})};var lc=E.AnonymousObservable=function(a){function b(a){return a&&"function"==typeof a.dispose?a:"function"==typeof a?xb(a):yb}function c(d){function e(a){var c=function(){try{e.setDisposable(b(d(e)))}catch(a){if(!e.fail(a))throw a}},e=new mc(a);return Gb.scheduleRequired()?Gb.schedule(c):c(),e}return this instanceof c?void a.call(this,e):new c(d)}return mb(c,a),c}(Zb),mc=function(a){function b(b){a.call(this),this.observer=b,this.m=new zb}mb(b,a);var c=b.prototype;return c.next=function(a){var b=!1;try{this.observer.onNext(a),b=!0}catch(c){throw c}finally{b||this.dispose()}},c.error=function(a){try{this.observer.onError(a)}catch(b){throw b}finally{this.dispose()}},c.completed=function(){try{this.observer.onCompleted()}catch(a){throw a}finally{this.dispose()}},c.setDisposable=function(a){this.m.setDisposable(a)},c.getDisposable=function(){return this.m.getDisposable()},c.disposable=function(a){return arguments.length?this.getDisposable():setDisposable(a)},c.dispose=function(){a.prototype.dispose.call(this),this.m.dispose()},b}(Ub),nc=function(a,b){this.subject=a,this.observer=b};nc.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1),this.observer=null}};var oc=E.Subject=function(a){function c(a){return b.call(this),this.isStopped?this.exception?(a.onError(this.exception),yb):(a.onCompleted(),yb):(this.observers.push(a),new nc(this,a))}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return mb(d,a),nb(d.prototype,Rb,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped)for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)},dispose:function(){this.isDisposed=!0,this.observers=null}}),d.create=function(a,b){return new pc(a,b)},d}(Zb),pc=(E.AsyncSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),new nc(this,a);var c=this.exception,d=this.hasValue,e=this.value;return c?a.onError(c):d?(a.onNext(e),a.onCompleted()):a.onCompleted(),yb}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return mb(d,a),nb(d.prototype,Rb,{hasObservers:function(){return b.call(this),this.observers.length>0},onCompleted:function(){var a,c,d;if(b.call(this),!this.isStopped){this.isStopped=!0;var e=this.observers.slice(0),f=this.value,g=this.hasValue;if(g)for(c=0,d=e.length;d>c;c++)a=e[c],a.onNext(f),a.onCompleted();else for(c=0,d=e.length;d>c;c++)e[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){b.call(this),this.isStopped||(this.value=a,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),d}(Zb),E.AnonymousSubject=function(a){function b(b,c){this.observer=b,this.observable=c,a.call(this,this.observable.subscribe.bind(this.observable))}return mb(b,a),nb(b.prototype,Rb,{onCompleted:function(){this.observer.onCompleted()},onError:function(a){this.observer.onError(a)},onNext:function(a){this.observer.onNext(a)}}),b}(Zb));"function"==typeof define&&"object"==typeof define.amd&&define.amd?(z.Rx=E,define(function(){return E})):A&&B?C?(B.exports=E).Rx=E:A.Rx=E:z.Rx=E}).call(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.core.compat.js b/ajax/libs/rxjs/2.3.9/rx.core.compat.js new file mode 100644 index 000000000..8f1ea5b32 --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.core.compat.js @@ -0,0 +1,2548 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { + + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, + isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || + '_es6shim_iterator_'; + // Bug for mozilla version + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Utilities + if (!Function.prototype.bind) { + Function.prototype.bind = function (that) { + var target = this, + args = slice.call(arguments, 1); + var bound = function () { + if (this instanceof bound) { + function F() { } + F.prototype = target.prototype; + var self = new F(); + var result = target.apply(self, args.concat(slice.call(arguments))); + if (Object(result) === result) { + return result; + } + return self; + } else { + return target.apply(that, args.concat(slice.call(arguments))); + } + }; + + return bound; + }; + } + + var boxedString = Object("a"), + splitString = boxedString[0] != "a" || !(0 in boxedString); + if (!Array.prototype.every) { + Array.prototype.every = function every(fun /*, thisp */) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self && !fun.call(thisp, self[i], i, object)) { + return false; + } + } + return true; + }; + } + + if (!Array.prototype.map) { + Array.prototype.map = function map(fun /*, thisp*/) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + result = Array(length), + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self) + result[i] = fun.call(thisp, self[i], i, object); + } + return result; + }; + } + + if (!Array.prototype.filter) { + Array.prototype.filter = function (predicate) { + var results = [], item, t = new Object(this); + for (var i = 0, len = t.length >>> 0; i < len; i++) { + item = t[i]; + if (i in t && predicate.call(arguments[1], item, i, t)) { + results.push(item); + } + } + return results; + }; + } + + if (!Array.isArray) { + Array.isArray = function (arg) { + return Object.prototype.toString.call(arg) == arrayClass; + }; + } + + if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function indexOf(searchElement) { + var t = Object(this); + var len = t.length >>> 0; + if (len === 0) { + return -1; + } + var n = 0; + if (arguments.length > 1) { + n = Number(arguments[1]); + if (n !== n) { + n = 0; + } else if (n !== 0 && n != Infinity && n !== -Infinity) { + n = (n > 0 || -1) * Math.floor(Math.abs(n)); + } + } + if (n >= len) { + return -1; + } + var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); + for (; k < len; k++) { + if (k in t && t[k] === searchElement) { + return k; + } + } + return -1; + }; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { + return; + } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { + return; + } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. + */ + CompositeDisposablePrototype.clear = function () { + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + }; + + /** + * Determines whether the CompositeDisposable contains a specific disposable. + * @param {Mixed} item Disposable to search for. + * @returns {Boolean} true if the disposable was found; otherwise, false. + */ + CompositeDisposablePrototype.contains = function (item) { + return this.disposables.indexOf(item) !== -1; + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var BooleanDisposable = (function () { + function BooleanDisposable (isSingle) { + this.isSingle = isSingle; + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + if (this.current && this.isSingle) { + throw new Error('Disposable has already been assigned'); + } + + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + if (old) { + old.dispose(); + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + return BooleanDisposable; + }()); + + /** + * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. + */ + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { + inherits(SingleAssignmentDisposable, super_); + + function SingleAssignmentDisposable() { + super_.call(this, true); + } + + return SingleAssignmentDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. + */ + var SerialDisposable = Rx.SerialDisposable = (function (super_) { + inherits(SerialDisposable, super_); + + function SerialDisposable() { + super_.call(this, false); + } + + return SerialDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + /** + * @constructor + * @private + */ + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchException = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, function () { + action(); + }); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodicWithState = function (state, period, action) { + var s = state, id = setInterval(function () { + s = action(s); + }, period); + return disposableCreate(function () { + clearInterval(id); + }); + }; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { + self(_action); + }); + }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, function (s, p) { + return invokeRecImmediate(s, p); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + if (timeSpan < 0) { + timeSpan = 0; + } + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt); + + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + + currentScheduler.scheduleRequired = function () { return !queue; }; + currentScheduler.ensureTrampoline = function (action) { + if (!queue) { this.schedule(action); } else { action(); } + }; + + return currentScheduler; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, + dt = Scheduler.normalize(dueTime); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** @private */ + var CatchScheduler = (function (_super) { + + function localNow() { + return this._scheduler.now(); + } + + function scheduleNow(state, action) { + return this._scheduler.scheduleWithState(state, this._wrap(action)); + } + + function scheduleRelative(state, dueTime, action) { + return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); + } + + function scheduleAbsolute(state, dueTime, action) { + return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); + } + + inherits(CatchScheduler, _super); + + /** @private */ + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + /** @private */ + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + /** @private */ + CatchScheduler.prototype._wrap = function (action) { + var parent = this; + return function (self, state) { + try { + return action(parent._getRecursiveWrapper(self), state); + } catch (e) { + if (!parent._handler(e)) { throw e; } + return disposableEmpty; + } + }; + }; + + /** @private */ + CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { + if (this._recursiveOriginal !== scheduler) { + this._recursiveOriginal = scheduler; + var wrapper = this._clone(scheduler); + wrapper._recursiveOriginal = scheduler; + wrapper._recursiveWrapper = wrapper; + this._recursiveWrapper = wrapper; + } + return this._recursiveWrapper; + }; + + /** @private */ + CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var self = this, failed = false, d = new SingleAssignmentDisposable(); + + d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { + if (failed) { return null; } + try { + return action(state1); + } catch (e) { + failed = true; + if (!self._handler(e)) { throw e; } + d.dispose(); + return null; + } + })); + + return d; + }; + + return CatchScheduler; + }(Scheduler)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { + return observerOrOnNext && typeof observerOrOnNext === 'object' ? + this._acceptObservable(observerOrOnNext) : + this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notifications + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + Notification.prototype.toObservable = function (scheduler) { + var notification = this; + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + notification.kind === 'N' && observer.onCompleted(); + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + + function _accept (onNext) { return onNext(this.value); } + function _acceptObservable(observer) { return observer.onNext(this.value); } + function toString () { return 'OnNext(' + this.value + ')'; } + + return function (value) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + + function _accept (onNext, onError) { return onError(this.exception); } + function _acceptObservable(observer) { return observer.onError(this.exception); } + function toString () { return 'OnError(' + this.exception + ')'; } + + return function (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { return onCompleted(); } + function _acceptObservable(observer) { return observer.onCompleted(); } + function toString () { return 'OnCompleted()'; } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var CheckedObserver = (function (_super) { + inherits(CheckedObserver, _super); + + function CheckedObserver(observer) { + _super.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + try { + this._observer.onNext(value); + } catch (e) { + throw e; + } finally { + this._state = 0; + } + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + try { + this._observer.onError(err); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + try { + this._observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { + inherits(ScheduledObserver, _super); + + function ScheduledObserver(scheduler, observer) { + _super.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + /** @private */ + var ObserveOnObserver = (function (_super) { + inherits(ObserveOnObserver, _super); + + /** @private */ + function ObserveOnObserver() { + _super.apply(this, arguments); + } + + /** @private */ + ObserveOnObserver.prototype.next = function (value) { + _super.prototype.next.call(this, value); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.error = function (e) { + _super.prototype.error.call(this, e); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.completed = function () { + _super.prototype.completed.call(this); + this.ensureActive(); + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber = typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted); + + return this._subscribe(subscriber); + }; + + return Observable; + })(); + + var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { + inherits(AnonymousObservable, __super__); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } + + return typeof subscriber === 'function' ? + disposableCreate(subscriber) : + disposableEmpty; + } + + function AnonymousObservable(subscribe) { + if (!(this instanceof AnonymousObservable)) { + return new AnonymousObservable(subscribe); + } + + function s(observer) { + var setDisposable = function () { + try { + autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); + } catch (e) { + if (!autoDetachObserver.fail(e)) { + throw e; + } + } + }; + + var autoDetachObserver = new AutoDetachObserver(observer); + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.schedule(setDisposable); + } else { + setDisposable(); + } + + return autoDetachObserver; + } + + __super__.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + /** @private */ + var AutoDetachObserver = (function (_super) { + inherits(AutoDetachObserver, _super); + + function AutoDetachObserver(observer) { + _super.call(this); + this.observer = observer; + this.m = new SingleAssignmentDisposable(); + } + + var AutoDetachObserverPrototype = AutoDetachObserver.prototype; + + AutoDetachObserverPrototype.next = function (value) { + var noError = false; + try { + this.observer.onNext(value); + noError = true; + } catch (e) { + throw e; + } finally { + if (!noError) { + this.dispose(); + } + } + }; + + AutoDetachObserverPrototype.error = function (exn) { + try { + this.observer.onError(exn); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.completed = function () { + try { + this.observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; + /* @private */ + AutoDetachObserverPrototype.disposable = function (value) { + return arguments.length ? this.getDisposable() : setDisposable(value); + }; + + AutoDetachObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + /** @private */ + var InnerSubscription = function (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + /** + * @private + * @memberOf InnerSubscription + */ + InnerSubscription.prototype.dispose = function () { + if (!this.subject.isDisposed && this.observer !== null) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + this.observer = null; + } + }; + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.exception) { + observer.onError(this.exception); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, _super); + + /** + * Creates a subject. + * @constructor + */ + function Subject() { + _super.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + } + + addProperties(Subject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (_super) { + + function subscribe(observer) { + checkDisposed.call(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + var ex = this.exception, + hv = this.hasValue, + v = this.value; + + if (ex) { + observer.onError(ex); + } else if (hv) { + observer.onNext(v); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, _super); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + _super.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.value = null; + this.hasValue = false; + this.observers = []; + this.exception = null; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed.call(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var o, i, len; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var os = this.observers.slice(0), + v = this.value, + hv = this.hasValue; + + if (hv) { + for (i = 0, len = os.length; i < len; i++) { + o = os[i]; + o.onNext(v); + o.onCompleted(); + } + } else { + for (i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + this.hasValue = true; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { + inherits(AnonymousSubject, __super__); + + function AnonymousSubject(observer, observable) { + this.observer = observer; + this.observable = observable; + __super__.call(this, this.observable.subscribe.bind(this.observable)); + } + + addProperties(AnonymousSubject.prototype, Observer, { + onCompleted: function () { + this.observer.onCompleted(); + }, + onError: function (exception) { + this.observer.onError(exception); + }, + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } +}.call(this)); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.core.compat.min.js b/ajax/libs/rxjs/2.3.9/rx.core.compat.min.js new file mode 100644 index 000000000..dcbd925f6 --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.core.compat.min.js @@ -0,0 +1 @@ +(function(a){function b(){if(this.isDisposed)throw new Error(A)}function c(a){var b=typeof a;return a&&("function"==b||"object"==b)||!1}function d(a){var b=[];if(!c(a))return b;X.nonEnumArgs&&a.length&&h(a)&&(a=Z.call(a));var d=X.enumPrototypes&&"function"==typeof a,e=X.enumErrorProps&&(a===R||a instanceof Error);for(var f in a)d&&"prototype"==f||e&&("message"==f||"name"==f)||b.push(f);if(X.nonEnumShadows&&a!==S){var g=a.constructor,i=-1,j=V.length;if(a===(g&&g.prototype))var k=a===stringProto?N:a===R?I:O.call(a),l=W[k];for(;++i-1:void 0});return c.pop(),d.pop(),result}function k(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:Z.call(a)}function l(a,b){this.scheduler=a,this.disposable=b,this.isDisposed=!1}var m={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},n=m[typeof window]&&window||this,o=m[typeof exports]&&exports&&!exports.nodeType&&exports,p=m[typeof module]&&module&&!module.nodeType&&module,q=p&&p.exports===o&&o,r=m[typeof global]&&global;!r||r.global!==r&&r.window!==r||(n=r);var s={internals:{},config:{Promise:n.Promise},helpers:{}},t=s.helpers.noop=function(){},u=(s.helpers.notDefined=function(a){return"undefined"==typeof a},s.helpers.isScheduler=function(a){return a instanceof s.Scheduler}),v=s.helpers.identity=function(a){return a},w=(s.helpers.pluck=function(a){return function(b){return b[a]}},s.helpers.just=function(a){return function(){return a}},s.helpers.defaultNow=function(){return Date.now?Date.now:function(){return+new Date}}()),x=(s.helpers.defaultComparer=function(a,b){return Y(a,b)},s.helpers.defaultSubComparer=function(a,b){return a>b?1:b>a?-1:0}),y=(s.helpers.defaultKeySerializer=function(a){return a.toString()},s.helpers.defaultError=function(a){throw a}),z=s.helpers.isPromise=function(a){return!!a&&"function"==typeof a.then},A=(s.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},s.helpers.not=function(a){return!a},"Object has been disposed"),B="function"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";n.Set&&"function"==typeof(new n.Set)["@@iterator"]&&(B="@@iterator");var C,D={done:!0,value:a},E="[object Arguments]",F="[object Array]",G="[object Boolean]",H="[object Date]",I="[object Error]",J="[object Function]",K="[object Number]",L="[object Object]",M="[object RegExp]",N="[object String]",O=Object.prototype.toString,P=Object.prototype.hasOwnProperty,Q=O.call(arguments)==E,R=Error.prototype,S=Object.prototype,T=S.propertyIsEnumerable;try{C=!(O.call(document)==L&&!({toString:0}+""))}catch(U){C=!0}var V=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],W={};W[F]=W[H]=W[K]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},W[G]=W[N]={constructor:!0,toString:!0,valueOf:!0},W[I]=W[J]=W[M]={constructor:!0,toString:!0},W[L]={constructor:!0};var X={};!function(){var a=function(){this.x=1},b=[];a.prototype={valueOf:1,y:1};for(var c in new a)b.push(c);for(c in arguments);X.enumErrorProps=T.call(R,"message")||T.call(R,"name"),X.enumPrototypes=T.call(a,"prototype"),X.nonEnumArgs=0!=c,X.nonEnumShadows=!/valueOf/.test(b)}(1),Q||(h=function(a){return a&&"object"==typeof a?P.call(a,"callee"):!1}),i(/x/)&&(i=function(a){return"function"==typeof a&&O.call(a)==J});{var Y=s.internals.isEqual=function(a,b){return j(a,b,[],[])},Z=Array.prototype.slice,$=({}.hasOwnProperty,this.inherits=s.internals.inherits=function(a,b){function c(){this.constructor=a}c.prototype=b.prototype,a.prototype=new c}),_=s.internals.addProperties=function(a){for(var b=Z.call(arguments,1),c=0,d=b.length;d>c;c++){var e=b[c];for(var f in e)a[f]=e[f]}};s.internals.addRef=function(a,b){return new Kb(function(c){return new fb(b.getDisposable(),a.subscribe(c))})}}Function.prototype.bind||(Function.prototype.bind=function(a){var b=this,c=Z.call(arguments,1),d=function(){function e(){}if(this instanceof d){e.prototype=b.prototype;var f=new e,g=b.apply(f,c.concat(Z.call(arguments)));return Object(g)===g?g:f}return b.apply(a,c.concat(Z.call(arguments)))};return d});var ab=Object("a"),bb="a"!=ab[0]||!(0 in ab);Array.prototype.every||(Array.prototype.every=function(a){var b=Object(this),c=bb&&{}.toString.call(this)==N?this.split(""):b,d=c.length>>>0,e=arguments[1];if({}.toString.call(a)!=J)throw new TypeError(a+" is not a function");for(var f=0;d>f;f++)if(f in c&&!a.call(e,c[f],f,b))return!1;return!0}),Array.prototype.map||(Array.prototype.map=function(a){var b=Object(this),c=bb&&{}.toString.call(this)==N?this.split(""):b,d=c.length>>>0,e=Array(d),f=arguments[1];if({}.toString.call(a)!=J)throw new TypeError(a+" is not a function");for(var g=0;d>g;g++)g in c&&(e[g]=a.call(f,c[g],g,b));return e}),Array.prototype.filter||(Array.prototype.filter=function(a){for(var b,c=[],d=new Object(this),e=0,f=d.length>>>0;f>e;e++)b=d[e],e in d&&a.call(arguments[1],b,e,d)&&c.push(b);return c}),Array.isArray||(Array.isArray=function(a){return Object.prototype.toString.call(a)==F}),Array.prototype.indexOf||(Array.prototype.indexOf=function(a){var b=Object(this),c=b.length>>>0;if(0===c)return-1;var d=0;if(arguments.length>1&&(d=Number(arguments[1]),d!==d?d=0:0!==d&&1/0!=d&&d!==-1/0&&(d=(d>0||-1)*Math.floor(Math.abs(d)))),d>=c)return-1;for(var e=d>=0?d:Math.max(c-Math.abs(d),0);c>e;e++)if(e in b&&b[e]===a)return e;return-1});var cb=function(a,b){this.id=a,this.value=b};cb.prototype.compareTo=function(a){var b=this.value.compareTo(a.value);return 0===b&&(b=this.id-a.id),b};var db=s.internals.PriorityQueue=function(a){this.items=new Array(a),this.length=0},eb=db.prototype;eb.isHigherPriority=function(a,b){return this.items[a].compareTo(this.items[b])<0},eb.percolate=function(a){if(!(a>=this.length||0>a)){var b=a-1>>1;if(!(0>b||b===a)&&this.isHigherPriority(a,b)){var c=this.items[a];this.items[a]=this.items[b],this.items[b]=c,this.percolate(b)}}},eb.heapify=function(b){if(b===a&&(b=0),!(b>=this.length||0>b)){var c=2*b+1,d=2*b+2,e=b;if(cb;b++)a[b].dispose()}},gb.clear=function(){var a=this.disposables.slice(0);this.disposables=[],this.length=0;for(var b=0,c=a.length;c>b;b++)a[b].dispose()},gb.contains=function(a){return-1!==this.disposables.indexOf(a)},gb.toArray=function(){return this.disposables.slice(0)};var hb=s.Disposable=function(a){this.isDisposed=!1,this.action=a||t};hb.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};{var ib=hb.create=function(a){return new hb(a)},jb=hb.empty={dispose:t},kb=function(){function a(a){this.isSingle=a,this.isDisposed=!1,this.current=null}var b=a.prototype;return b.getDisposable=function(){return this.current},b.setDisposable=function(a){if(this.current&&this.isSingle)throw new Error("Disposable has already been assigned");var b,c=this.isDisposed;c||(b=this.current,this.current=a),b&&b.dispose(),c&&a&&a.dispose()},b.dispose=function(){var a;this.isDisposed||(this.isDisposed=!0,a=this.current,this.current=null),a&&a.dispose()},a}(),lb=s.SingleAssignmentDisposable=function(a){function b(){a.call(this,!0)}return $(b,a),b}(kb),mb=s.SerialDisposable=function(a){function b(){a.call(this,!1)}return $(b,a),b}(kb);s.RefCountDisposable=function(){function a(a){this.disposable=a,this.disposable.count++,this.isInnerDisposed=!1}function b(a){this.underlyingDisposable=a,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return a.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},b.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},b.prototype.getDisposable=function(){return this.isDisposed?jb:new a(this)},b}()}l.prototype.dispose=function(){var a=this;this.scheduler.schedule(function(){a.isDisposed||(a.isDisposed=!0,a.disposable.dispose())})};var nb=s.internals.ScheduledItem=function(a,b,c,d,e){this.scheduler=a,this.state=b,this.action=c,this.dueTime=d,this.comparer=e||x,this.disposable=new lb};nb.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},nb.prototype.compareTo=function(a){return this.comparer(this.dueTime,a.dueTime)},nb.prototype.isCancelled=function(){return this.disposable.isDisposed},nb.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var ob,pb=s.Scheduler=function(){function a(a,b,c,d){this.now=a,this._schedule=b,this._scheduleRelative=c,this._scheduleAbsolute=d}function b(a,b){var c=b.first,d=b.second,e=new fb,f=function(b){d(b,function(b){var c=!1,d=!1,g=a.scheduleWithState(b,function(a,b){return c?e.remove(g):d=!0,f(b),jb});d||(e.add(g),c=!0)})};return f(c),e}function c(a,b,c){var d=b.first,e=b.second,f=new fb,g=function(b){e(b,function(b,d){var e=!1,h=!1,i=a[c].call(a,b,d,function(a,b){return e?f.remove(i):h=!0,g(b),jb});h||(f.add(i),e=!0)})};return g(d),f}function d(a,b){return b(),jb}var e=a.prototype;return e.catchException=e["catch"]=function(a){return new ub(this,a)},e.schedulePeriodic=function(a,b){return this.schedulePeriodicWithState(null,a,function(){b()})},e.schedulePeriodicWithState=function(a,b,c){var d=a,e=setInterval(function(){d=c(d)},b);return ib(function(){clearInterval(e)})},e.schedule=function(a){return this._schedule(a,d)},e.scheduleWithState=function(a,b){return this._schedule(a,b)},e.scheduleWithRelative=function(a,b){return this._scheduleRelative(b,a,d)},e.scheduleWithRelativeAndState=function(a,b,c){return this._scheduleRelative(a,b,c)},e.scheduleWithAbsolute=function(a,b){return this._scheduleAbsolute(b,a,d)},e.scheduleWithAbsoluteAndState=function(a,b,c){return this._scheduleAbsolute(a,b,c)},e.scheduleRecursive=function(a){return this.scheduleRecursiveWithState(a,function(a,b){a(function(){b(a)})})},e.scheduleRecursiveWithState=function(a,c){return this.scheduleWithState({first:a,second:c},function(a,c){return b(a,c)})},e.scheduleRecursiveWithRelative=function(a,b){return this.scheduleRecursiveWithRelativeAndState(b,a,function(a,b){a(function(c){b(a,c)})})},e.scheduleRecursiveWithRelativeAndState=function(a,b,d){return this._scheduleRelative({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithRelativeAndState")})},e.scheduleRecursiveWithAbsolute=function(a,b){return this.scheduleRecursiveWithAbsoluteAndState(b,a,function(a,b){a(function(c){b(a,c)})})},e.scheduleRecursiveWithAbsoluteAndState=function(a,b,d){return this._scheduleAbsolute({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithAbsoluteAndState")})},a.now=w,a.normalize=function(a){return 0>a&&(a=0),a},a}(),qb=pb.normalize,rb=(s.internals.SchedulePeriodicRecursive=function(){function a(a,b){b(0,this._period);try{this._state=this._action(this._state)}catch(c){throw this._cancel.dispose(),c}}function b(a,b,c,d){this._scheduler=a,this._state=b,this._period=c,this._action=d}return b.prototype.start=function(){var b=new lb;return this._cancel=b,b.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,a.bind(this))),b},b}(),pb.immediate=function(){function a(a,b){return b(this,a)}function b(a,b,c){for(var d=qb(d);d-this.now()>0;);return c(this,a)}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new pb(w,a,b,c)}()),sb=pb.currentThread=function(){function a(a){for(var b;a.length>0;)if(b=a.dequeue(),!b.isCancelled()){for(;b.dueTime-pb.now()>0;);b.isCancelled()||b.invoke()}}function b(a,b){return this.scheduleWithRelativeAndState(a,0,b)}function c(b,c,d){var f=this.now()+pb.normalize(c),g=new nb(this,b,d,f);if(e)e.enqueue(g);else{e=new db(4),e.enqueue(g);try{a(e)}catch(h){throw h}finally{e=null}}return g.disposable}function d(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}var e,f=new pb(w,b,c,d);return f.scheduleRequired=function(){return!e},f.ensureTrampoline=function(a){e?a():this.schedule(a)},f}(),tb=t;!function(){function a(){if(!n.postMessage||n.importScripts)return!1;var a=!1,b=n.onmessage;return n.onmessage=function(){a=!0},n.postMessage("","*"),n.onmessage=b,a}function b(a){if("string"==typeof a.data&&a.data.substring(0,f.length)===f){var b=a.data.substring(f.length),c=g[b];c(),delete g[b]}}var c=RegExp("^"+String(O).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),d="function"==typeof(d=r&&q&&r.setImmediate)&&!c.test(d)&&d,e="function"==typeof(e=r&&q&&r.clearImmediate)&&!c.test(e)&&e;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))ob=process.nextTick;else if("function"==typeof d)ob=d,tb=e;else if(a()){var f="ms.rx.schedule"+Math.random(),g={},h=0;n.addEventListener?n.addEventListener("message",b,!1):n.attachEvent("onmessage",b,!1),ob=function(a){var b=h++;g[b]=a,n.postMessage(f+b,"*")}}else if(n.MessageChannel){var i=new n.MessageChannel,j={},k=0;i.port1.onmessage=function(a){var b=a.data,c=j[b];c(),delete j[b]},ob=function(a){var b=k++;j[b]=a,i.port2.postMessage(b)}}else"document"in n&&"onreadystatechange"in n.document.createElement("script")?ob=function(a){var b=n.document.createElement("script");b.onreadystatechange=function(){a(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},n.document.documentElement.appendChild(b)}:(ob=function(a){return setTimeout(a,0)},tb=clearTimeout)}();var ub=(pb.timeout=function(){function a(a,b){var c=this,d=new lb,e=ob(function(){d.isDisposed||d.setDisposable(b(c,a))});return new fb(d,ib(function(){tb(e)}))}function b(a,b,c){var d=this,e=pb.normalize(b);if(0===e)return d.scheduleWithState(a,c);var f=new lb,g=setTimeout(function(){f.isDisposed||f.setDisposable(c(d,a))},e);return new fb(f,ib(function(){clearTimeout(g)}))}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new pb(w,a,b,c)}(),function(a){function b(){return this._scheduler.now()}function c(a,b){return this._scheduler.scheduleWithState(a,this._wrap(b))}function d(a,b,c){return this._scheduler.scheduleWithRelativeAndState(a,b,this._wrap(c))}function e(a,b,c){return this._scheduler.scheduleWithAbsoluteAndState(a,b,this._wrap(c))}function f(f,g){this._scheduler=f,this._handler=g,this._recursiveOriginal=null,this._recursiveWrapper=null,a.call(this,b,c,d,e)}return $(f,a),f.prototype._clone=function(a){return new f(a,this._handler)},f.prototype._wrap=function(a){var b=this;return function(c,d){try{return a(b._getRecursiveWrapper(c),d)}catch(e){if(!b._handler(e))throw e;return jb}}},f.prototype._getRecursiveWrapper=function(a){if(this._recursiveOriginal!==a){this._recursiveOriginal=a;var b=this._clone(a);b._recursiveOriginal=a,b._recursiveWrapper=b,this._recursiveWrapper=b}return this._recursiveWrapper},f.prototype.schedulePeriodicWithState=function(a,b,c){var d=this,e=!1,f=new lb;return f.setDisposable(this._scheduler.schedulePeriodicWithState(a,b,function(a){if(e)return null;try{return c(a)}catch(b){if(e=!0,!d._handler(b))throw b;return f.dispose(),null}})),f},f}(pb)),vb=s.Notification=function(){function a(a,b){this.hasValue=null==b?!1:b,this.kind=a}return a.prototype.accept=function(a,b,c){return a&&"object"==typeof a?this._acceptObservable(a):this._accept(a,b,c)},a.prototype.toObservable=function(a){var b=this;return u(a)||(a=rb),new Kb(function(c){return a.schedule(function(){b._acceptObservable(c),"N"===b.kind&&c.onCompleted()})})},a}(),wb=vb.createOnNext=function(){function a(a){return a(this.value)}function b(a){return a.onNext(this.value)}function c(){return"OnNext("+this.value+")"}return function(d){var e=new vb("N",!0);return e.value=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),xb=vb.createOnError=function(){function a(a,b){return b(this.exception)}function b(a){return a.onError(this.exception)}function c(){return"OnError("+this.exception+")"}return function(d){var e=new vb("E");return e.exception=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),yb=vb.createOnCompleted=function(){function a(a,b,c){return c()}function b(a){return a.onCompleted()}function c(){return"OnCompleted()"}return function(){var d=new vb("C");return d._accept=a,d._acceptObservable=b,d.toString=c,d}}(),zb=s.internals.Enumerator=function(a){this._next=a};zb.prototype.next=function(){return this._next()},zb.prototype[B]=function(){return this};var Ab=s.internals.Enumerable=function(a){this._iterator=a};Ab.prototype[B]=function(){return this._iterator()},Ab.prototype.concat=function(){var a=this;return new Kb(function(b){var c;try{c=a[B]()}catch(d){return void b.onError()}var e,f=new mb,g=rb.scheduleRecursive(function(a){var d;if(!e){try{d=c.next()}catch(g){return void b.onError(g)}if(d.done)return void b.onCompleted();var h=d.value;z(h)&&(h=observableFromPromise(h));var i=new lb;f.setDisposable(i),i.setDisposable(h.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){a()}))}});return new fb(f,g,ib(function(){e=!0}))})},Ab.prototype.catchException=function(){var a=this;return new Kb(function(b){var c;try{c=a[B]()}catch(d){return void b.onError()}var e,f,g=new mb,h=rb.scheduleRecursive(function(a){if(!e){var d;try{d=c.next()}catch(h){return void b.onError(h)}if(d.done)return void(f?b.onError(f):b.onCompleted());var i=d.value;z(i)&&(i=observableFromPromise(i));var j=new lb;g.setDisposable(j),j.setDisposable(i.subscribe(b.onNext.bind(b),function(b){f=b,a()},b.onCompleted.bind(b)))}});return new fb(g,h,ib(function(){e=!0}))})};var Bb=(Ab.repeat=function(a,b){return null==b&&(b=-1),new Ab(function(){var c=b;return new zb(function(){return 0===c?D:(c>0&&c--,{done:!1,value:a})})})},Ab.forEach=function(a,b,c){return b||(b=v),new Ab(function(){var d=-1;return new zb(function(){return++d0&&(a=!this.isAcquired,this.isAcquired=!0),a&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(a){var c;if(!(b.queue.length>0))return void(b.isAcquired=!1);c=b.queue.shift();try{c()}catch(d){throw b.queue=[],b.hasFaulted=!0,d}a()}))},b.prototype.dispose=function(){a.prototype.dispose.call(this),this.disposable.dispose()},b}(Eb),Ib=function(a){function b(){a.apply(this,arguments)}return $(b,a),b.prototype.next=function(b){a.prototype.next.call(this,b),this.ensureActive()},b.prototype.error=function(b){a.prototype.error.call(this,b),this.ensureActive()},b.prototype.completed=function(){a.prototype.completed.call(this),this.ensureActive()},b}(Hb),Jb=s.Observable=function(){function a(a){this._subscribe=a}return Db=a.prototype,Db.subscribe=Db.forEach=function(a,b,c){var d="object"==typeof a?a:Cb(a,b,c);return this._subscribe(d)},a}(),Kb=s.AnonymousObservable=function(a){function b(a){return a&&"function"==typeof a.dispose?a:"function"==typeof a?ib(a):jb}function c(d){function e(a){var c=function(){try{e.setDisposable(b(d(e)))}catch(a){if(!e.fail(a))throw a}},e=new Lb(a);return sb.scheduleRequired()?sb.schedule(c):c(),e}return this instanceof c?void a.call(this,e):new c(d)}return $(c,a),c}(Jb),Lb=function(a){function b(b){a.call(this),this.observer=b,this.m=new lb}$(b,a);var c=b.prototype;return c.next=function(a){var b=!1;try{this.observer.onNext(a),b=!0}catch(c){throw c}finally{b||this.dispose()}},c.error=function(a){try{this.observer.onError(a)}catch(b){throw b}finally{this.dispose()}},c.completed=function(){try{this.observer.onCompleted()}catch(a){throw a}finally{this.dispose()}},c.setDisposable=function(a){this.m.setDisposable(a)},c.getDisposable=function(){return this.m.getDisposable()},c.disposable=function(a){return arguments.length?this.getDisposable():setDisposable(a)},c.dispose=function(){a.prototype.dispose.call(this),this.m.dispose()},b}(Eb),Mb=function(a,b){this.subject=a,this.observer=b};Mb.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1),this.observer=null}};var Nb=(s.Subject=function(a){function c(a){return b.call(this),this.isStopped?this.exception?(a.onError(this.exception),jb):(a.onCompleted(),jb):(this.observers.push(a),new Mb(this,a))}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return $(d,a),_(d.prototype,Bb,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped)for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)},dispose:function(){this.isDisposed=!0,this.observers=null}}),d.create=function(a,b){return new Nb(a,b)},d}(Jb),s.AsyncSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),new Mb(this,a);var c=this.exception,d=this.hasValue,e=this.value;return c?a.onError(c):d?(a.onNext(e),a.onCompleted()):a.onCompleted(),jb}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return $(d,a),_(d.prototype,Bb,{hasObservers:function(){return b.call(this),this.observers.length>0},onCompleted:function(){var a,c,d;if(b.call(this),!this.isStopped){this.isStopped=!0;var e=this.observers.slice(0),f=this.value,g=this.hasValue;if(g)for(c=0,d=e.length;d>c;c++)a=e[c],a.onNext(f),a.onCompleted();else for(c=0,d=e.length;d>c;c++)e[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){b.call(this),this.isStopped||(this.value=a,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),d}(Jb),s.AnonymousSubject=function(a){function b(b,c){this.observer=b,this.observable=c,a.call(this,this.observable.subscribe.bind(this.observable))}return $(b,a),_(b.prototype,Bb,{onCompleted:function(){this.observer.onCompleted()},onError:function(a){this.observer.onError(a)},onNext:function(a){this.observer.onNext(a)}}),b}(Jb));"function"==typeof define&&"object"==typeof define.amd&&define.amd?(n.Rx=s,define(function(){return s})):o&&p?q?(p.exports=s).Rx=s:o.Rx=s:n.Rx=s}).call(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.core.js b/ajax/libs/rxjs/2.3.9/rx.core.js new file mode 100644 index 000000000..bfdb5b3cf --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.core.js @@ -0,0 +1,2430 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { + + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, + isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = Date.now, + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || + '_es6shim_iterator_'; + // Bug for mozilla version + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { + return; + } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { + return; + } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. + */ + CompositeDisposablePrototype.clear = function () { + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + }; + + /** + * Determines whether the CompositeDisposable contains a specific disposable. + * @param {Mixed} item Disposable to search for. + * @returns {Boolean} true if the disposable was found; otherwise, false. + */ + CompositeDisposablePrototype.contains = function (item) { + return this.disposables.indexOf(item) !== -1; + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var BooleanDisposable = (function () { + function BooleanDisposable (isSingle) { + this.isSingle = isSingle; + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + if (this.current && this.isSingle) { + throw new Error('Disposable has already been assigned'); + } + + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + if (old) { + old.dispose(); + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + return BooleanDisposable; + }()); + + /** + * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. + */ + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { + inherits(SingleAssignmentDisposable, super_); + + function SingleAssignmentDisposable() { + super_.call(this, true); + } + + return SingleAssignmentDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. + */ + var SerialDisposable = Rx.SerialDisposable = (function (super_) { + inherits(SerialDisposable, super_); + + function SerialDisposable() { + super_.call(this, false); + } + + return SerialDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + /** + * @constructor + * @private + */ + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchException = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, function () { + action(); + }); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodicWithState = function (state, period, action) { + var s = state, id = setInterval(function () { + s = action(s); + }, period); + return disposableCreate(function () { + clearInterval(id); + }); + }; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { + self(_action); + }); + }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, function (s, p) { + return invokeRecImmediate(s, p); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + if (timeSpan < 0) { + timeSpan = 0; + } + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt); + + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + + currentScheduler.scheduleRequired = function () { return !queue; }; + currentScheduler.ensureTrampoline = function (action) { + if (!queue) { this.schedule(action); } else { action(); } + }; + + return currentScheduler; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, + dt = Scheduler.normalize(dueTime); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** @private */ + var CatchScheduler = (function (_super) { + + function localNow() { + return this._scheduler.now(); + } + + function scheduleNow(state, action) { + return this._scheduler.scheduleWithState(state, this._wrap(action)); + } + + function scheduleRelative(state, dueTime, action) { + return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); + } + + function scheduleAbsolute(state, dueTime, action) { + return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); + } + + inherits(CatchScheduler, _super); + + /** @private */ + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + /** @private */ + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + /** @private */ + CatchScheduler.prototype._wrap = function (action) { + var parent = this; + return function (self, state) { + try { + return action(parent._getRecursiveWrapper(self), state); + } catch (e) { + if (!parent._handler(e)) { throw e; } + return disposableEmpty; + } + }; + }; + + /** @private */ + CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { + if (this._recursiveOriginal !== scheduler) { + this._recursiveOriginal = scheduler; + var wrapper = this._clone(scheduler); + wrapper._recursiveOriginal = scheduler; + wrapper._recursiveWrapper = wrapper; + this._recursiveWrapper = wrapper; + } + return this._recursiveWrapper; + }; + + /** @private */ + CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var self = this, failed = false, d = new SingleAssignmentDisposable(); + + d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { + if (failed) { return null; } + try { + return action(state1); + } catch (e) { + failed = true; + if (!self._handler(e)) { throw e; } + d.dispose(); + return null; + } + })); + + return d; + }; + + return CatchScheduler; + }(Scheduler)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { + return observerOrOnNext && typeof observerOrOnNext === 'object' ? + this._acceptObservable(observerOrOnNext) : + this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notifications + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + Notification.prototype.toObservable = function (scheduler) { + var notification = this; + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + notification.kind === 'N' && observer.onCompleted(); + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + + function _accept (onNext) { return onNext(this.value); } + function _acceptObservable(observer) { return observer.onNext(this.value); } + function toString () { return 'OnNext(' + this.value + ')'; } + + return function (value) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + + function _accept (onNext, onError) { return onError(this.exception); } + function _acceptObservable(observer) { return observer.onError(this.exception); } + function toString () { return 'OnError(' + this.exception + ')'; } + + return function (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { return onCompleted(); } + function _acceptObservable(observer) { return observer.onCompleted(); } + function toString () { return 'OnCompleted()'; } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var CheckedObserver = (function (_super) { + inherits(CheckedObserver, _super); + + function CheckedObserver(observer) { + _super.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + try { + this._observer.onNext(value); + } catch (e) { + throw e; + } finally { + this._state = 0; + } + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + try { + this._observer.onError(err); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + try { + this._observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { + inherits(ScheduledObserver, _super); + + function ScheduledObserver(scheduler, observer) { + _super.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + /** @private */ + var ObserveOnObserver = (function (_super) { + inherits(ObserveOnObserver, _super); + + /** @private */ + function ObserveOnObserver() { + _super.apply(this, arguments); + } + + /** @private */ + ObserveOnObserver.prototype.next = function (value) { + _super.prototype.next.call(this, value); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.error = function (e) { + _super.prototype.error.call(this, e); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.completed = function () { + _super.prototype.completed.call(this); + this.ensureActive(); + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber = typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted); + + return this._subscribe(subscriber); + }; + + return Observable; + })(); + + var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { + inherits(AnonymousObservable, __super__); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } + + return typeof subscriber === 'function' ? + disposableCreate(subscriber) : + disposableEmpty; + } + + function AnonymousObservable(subscribe) { + if (!(this instanceof AnonymousObservable)) { + return new AnonymousObservable(subscribe); + } + + function s(observer) { + var setDisposable = function () { + try { + autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); + } catch (e) { + if (!autoDetachObserver.fail(e)) { + throw e; + } + } + }; + + var autoDetachObserver = new AutoDetachObserver(observer); + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.schedule(setDisposable); + } else { + setDisposable(); + } + + return autoDetachObserver; + } + + __super__.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + /** @private */ + var AutoDetachObserver = (function (_super) { + inherits(AutoDetachObserver, _super); + + function AutoDetachObserver(observer) { + _super.call(this); + this.observer = observer; + this.m = new SingleAssignmentDisposable(); + } + + var AutoDetachObserverPrototype = AutoDetachObserver.prototype; + + AutoDetachObserverPrototype.next = function (value) { + var noError = false; + try { + this.observer.onNext(value); + noError = true; + } catch (e) { + throw e; + } finally { + if (!noError) { + this.dispose(); + } + } + }; + + AutoDetachObserverPrototype.error = function (exn) { + try { + this.observer.onError(exn); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.completed = function () { + try { + this.observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; + /* @private */ + AutoDetachObserverPrototype.disposable = function (value) { + return arguments.length ? this.getDisposable() : setDisposable(value); + }; + + AutoDetachObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + /** @private */ + var InnerSubscription = function (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + /** + * @private + * @memberOf InnerSubscription + */ + InnerSubscription.prototype.dispose = function () { + if (!this.subject.isDisposed && this.observer !== null) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + this.observer = null; + } + }; + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.exception) { + observer.onError(this.exception); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, _super); + + /** + * Creates a subject. + * @constructor + */ + function Subject() { + _super.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + } + + addProperties(Subject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (_super) { + + function subscribe(observer) { + checkDisposed.call(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + var ex = this.exception, + hv = this.hasValue, + v = this.value; + + if (ex) { + observer.onError(ex); + } else if (hv) { + observer.onNext(v); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, _super); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + _super.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.value = null; + this.hasValue = false; + this.observers = []; + this.exception = null; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed.call(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var o, i, len; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var os = this.observers.slice(0), + v = this.value, + hv = this.hasValue; + + if (hv) { + for (i = 0, len = os.length; i < len; i++) { + o = os[i]; + o.onNext(v); + o.onCompleted(); + } + } else { + for (i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + this.hasValue = true; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { + inherits(AnonymousSubject, __super__); + + function AnonymousSubject(observer, observable) { + this.observer = observer; + this.observable = observable; + __super__.call(this, this.observable.subscribe.bind(this.observable)); + } + + addProperties(AnonymousSubject.prototype, Observer, { + onCompleted: function () { + this.observer.onCompleted(); + }, + onError: function (exception) { + this.observer.onError(exception); + }, + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } +}.call(this)); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.core.min.js b/ajax/libs/rxjs/2.3.9/rx.core.min.js new file mode 100644 index 000000000..1bb5fce35 --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.core.min.js @@ -0,0 +1 @@ +(function(a){function b(){if(this.isDisposed)throw new Error(A)}function c(a){var b=typeof a;return a&&("function"==b||"object"==b)||!1}function d(a){var b=[];if(!c(a))return b;X.nonEnumArgs&&a.length&&h(a)&&(a=Z.call(a));var d=X.enumPrototypes&&"function"==typeof a,e=X.enumErrorProps&&(a===R||a instanceof Error);for(var f in a)d&&"prototype"==f||e&&("message"==f||"name"==f)||b.push(f);if(X.nonEnumShadows&&a!==S){var g=a.constructor,i=-1,j=V.length;if(a===(g&&g.prototype))var k=a===stringProto?N:a===R?I:O.call(a),l=W[k];for(;++i-1:void 0});return c.pop(),d.pop(),result}function k(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:Z.call(a)}function l(a,b){this.scheduler=a,this.disposable=b,this.isDisposed=!1}var m={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},n=m[typeof window]&&window||this,o=m[typeof exports]&&exports&&!exports.nodeType&&exports,p=m[typeof module]&&module&&!module.nodeType&&module,q=p&&p.exports===o&&o,r=m[typeof global]&&global;!r||r.global!==r&&r.window!==r||(n=r);var s={internals:{},config:{Promise:n.Promise},helpers:{}},t=s.helpers.noop=function(){},u=(s.helpers.notDefined=function(a){return"undefined"==typeof a},s.helpers.isScheduler=function(a){return a instanceof s.Scheduler}),v=s.helpers.identity=function(a){return a},w=(s.helpers.pluck=function(a){return function(b){return b[a]}},s.helpers.just=function(a){return function(){return a}},s.helpers.defaultNow=Date.now),x=(s.helpers.defaultComparer=function(a,b){return Y(a,b)},s.helpers.defaultSubComparer=function(a,b){return a>b?1:b>a?-1:0}),y=(s.helpers.defaultKeySerializer=function(a){return a.toString()},s.helpers.defaultError=function(a){throw a}),z=s.helpers.isPromise=function(a){return!!a&&"function"==typeof a.then},A=(s.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},s.helpers.not=function(a){return!a},"Object has been disposed"),B="function"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";n.Set&&"function"==typeof(new n.Set)["@@iterator"]&&(B="@@iterator");var C,D={done:!0,value:a},E="[object Arguments]",F="[object Array]",G="[object Boolean]",H="[object Date]",I="[object Error]",J="[object Function]",K="[object Number]",L="[object Object]",M="[object RegExp]",N="[object String]",O=Object.prototype.toString,P=Object.prototype.hasOwnProperty,Q=O.call(arguments)==E,R=Error.prototype,S=Object.prototype,T=S.propertyIsEnumerable;try{C=!(O.call(document)==L&&!({toString:0}+""))}catch(U){C=!0}var V=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],W={};W[F]=W[H]=W[K]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},W[G]=W[N]={constructor:!0,toString:!0,valueOf:!0},W[I]=W[J]=W[M]={constructor:!0,toString:!0},W[L]={constructor:!0};var X={};!function(){var a=function(){this.x=1},b=[];a.prototype={valueOf:1,y:1};for(var c in new a)b.push(c);for(c in arguments);X.enumErrorProps=T.call(R,"message")||T.call(R,"name"),X.enumPrototypes=T.call(a,"prototype"),X.nonEnumArgs=0!=c,X.nonEnumShadows=!/valueOf/.test(b)}(1),Q||(h=function(a){return a&&"object"==typeof a?P.call(a,"callee"):!1}),i(/x/)&&(i=function(a){return"function"==typeof a&&O.call(a)==J});var Y=s.internals.isEqual=function(a,b){return j(a,b,[],[])},Z=Array.prototype.slice,$=({}.hasOwnProperty,this.inherits=s.internals.inherits=function(a,b){function c(){this.constructor=a}c.prototype=b.prototype,a.prototype=new c}),_=s.internals.addProperties=function(a){for(var b=Z.call(arguments,1),c=0,d=b.length;d>c;c++){var e=b[c];for(var f in e)a[f]=e[f]}},ab=(s.internals.addRef=function(a,b){return new Ib(function(c){return new db(b.getDisposable(),a.subscribe(c))})},function(a,b){this.id=a,this.value=b});ab.prototype.compareTo=function(a){var b=this.value.compareTo(a.value);return 0===b&&(b=this.id-a.id),b};var bb=s.internals.PriorityQueue=function(a){this.items=new Array(a),this.length=0},cb=bb.prototype;cb.isHigherPriority=function(a,b){return this.items[a].compareTo(this.items[b])<0},cb.percolate=function(a){if(!(a>=this.length||0>a)){var b=a-1>>1;if(!(0>b||b===a)&&this.isHigherPriority(a,b)){var c=this.items[a];this.items[a]=this.items[b],this.items[b]=c,this.percolate(b)}}},cb.heapify=function(b){if(b===a&&(b=0),!(b>=this.length||0>b)){var c=2*b+1,d=2*b+2,e=b;if(cb;b++)a[b].dispose()}},eb.clear=function(){var a=this.disposables.slice(0);this.disposables=[],this.length=0;for(var b=0,c=a.length;c>b;b++)a[b].dispose()},eb.contains=function(a){return-1!==this.disposables.indexOf(a)},eb.toArray=function(){return this.disposables.slice(0)};var fb=s.Disposable=function(a){this.isDisposed=!1,this.action=a||t};fb.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};{var gb=fb.create=function(a){return new fb(a)},hb=fb.empty={dispose:t},ib=function(){function a(a){this.isSingle=a,this.isDisposed=!1,this.current=null}var b=a.prototype;return b.getDisposable=function(){return this.current},b.setDisposable=function(a){if(this.current&&this.isSingle)throw new Error("Disposable has already been assigned");var b,c=this.isDisposed;c||(b=this.current,this.current=a),b&&b.dispose(),c&&a&&a.dispose()},b.dispose=function(){var a;this.isDisposed||(this.isDisposed=!0,a=this.current,this.current=null),a&&a.dispose()},a}(),jb=s.SingleAssignmentDisposable=function(a){function b(){a.call(this,!0)}return $(b,a),b}(ib),kb=s.SerialDisposable=function(a){function b(){a.call(this,!1)}return $(b,a),b}(ib);s.RefCountDisposable=function(){function a(a){this.disposable=a,this.disposable.count++,this.isInnerDisposed=!1}function b(a){this.underlyingDisposable=a,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return a.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},b.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},b.prototype.getDisposable=function(){return this.isDisposed?hb:new a(this)},b}()}l.prototype.dispose=function(){var a=this;this.scheduler.schedule(function(){a.isDisposed||(a.isDisposed=!0,a.disposable.dispose())})};var lb=s.internals.ScheduledItem=function(a,b,c,d,e){this.scheduler=a,this.state=b,this.action=c,this.dueTime=d,this.comparer=e||x,this.disposable=new jb};lb.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},lb.prototype.compareTo=function(a){return this.comparer(this.dueTime,a.dueTime)},lb.prototype.isCancelled=function(){return this.disposable.isDisposed},lb.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var mb,nb=s.Scheduler=function(){function a(a,b,c,d){this.now=a,this._schedule=b,this._scheduleRelative=c,this._scheduleAbsolute=d}function b(a,b){var c=b.first,d=b.second,e=new db,f=function(b){d(b,function(b){var c=!1,d=!1,g=a.scheduleWithState(b,function(a,b){return c?e.remove(g):d=!0,f(b),hb});d||(e.add(g),c=!0)})};return f(c),e}function c(a,b,c){var d=b.first,e=b.second,f=new db,g=function(b){e(b,function(b,d){var e=!1,h=!1,i=a[c].call(a,b,d,function(a,b){return e?f.remove(i):h=!0,g(b),hb});h||(f.add(i),e=!0)})};return g(d),f}function d(a,b){return b(),hb}var e=a.prototype;return e.catchException=e["catch"]=function(a){return new sb(this,a)},e.schedulePeriodic=function(a,b){return this.schedulePeriodicWithState(null,a,function(){b()})},e.schedulePeriodicWithState=function(a,b,c){var d=a,e=setInterval(function(){d=c(d)},b);return gb(function(){clearInterval(e)})},e.schedule=function(a){return this._schedule(a,d)},e.scheduleWithState=function(a,b){return this._schedule(a,b)},e.scheduleWithRelative=function(a,b){return this._scheduleRelative(b,a,d)},e.scheduleWithRelativeAndState=function(a,b,c){return this._scheduleRelative(a,b,c)},e.scheduleWithAbsolute=function(a,b){return this._scheduleAbsolute(b,a,d)},e.scheduleWithAbsoluteAndState=function(a,b,c){return this._scheduleAbsolute(a,b,c)},e.scheduleRecursive=function(a){return this.scheduleRecursiveWithState(a,function(a,b){a(function(){b(a)})})},e.scheduleRecursiveWithState=function(a,c){return this.scheduleWithState({first:a,second:c},function(a,c){return b(a,c)})},e.scheduleRecursiveWithRelative=function(a,b){return this.scheduleRecursiveWithRelativeAndState(b,a,function(a,b){a(function(c){b(a,c)})})},e.scheduleRecursiveWithRelativeAndState=function(a,b,d){return this._scheduleRelative({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithRelativeAndState")})},e.scheduleRecursiveWithAbsolute=function(a,b){return this.scheduleRecursiveWithAbsoluteAndState(b,a,function(a,b){a(function(c){b(a,c)})})},e.scheduleRecursiveWithAbsoluteAndState=function(a,b,d){return this._scheduleAbsolute({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithAbsoluteAndState")})},a.now=w,a.normalize=function(a){return 0>a&&(a=0),a},a}(),ob=nb.normalize,pb=(s.internals.SchedulePeriodicRecursive=function(){function a(a,b){b(0,this._period);try{this._state=this._action(this._state)}catch(c){throw this._cancel.dispose(),c}}function b(a,b,c,d){this._scheduler=a,this._state=b,this._period=c,this._action=d}return b.prototype.start=function(){var b=new jb;return this._cancel=b,b.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,a.bind(this))),b},b}(),nb.immediate=function(){function a(a,b){return b(this,a)}function b(a,b,c){for(var d=ob(d);d-this.now()>0;);return c(this,a)}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new nb(w,a,b,c)}()),qb=nb.currentThread=function(){function a(a){for(var b;a.length>0;)if(b=a.dequeue(),!b.isCancelled()){for(;b.dueTime-nb.now()>0;);b.isCancelled()||b.invoke()}}function b(a,b){return this.scheduleWithRelativeAndState(a,0,b)}function c(b,c,d){var f=this.now()+nb.normalize(c),g=new lb(this,b,d,f);if(e)e.enqueue(g);else{e=new bb(4),e.enqueue(g);try{a(e)}catch(h){throw h}finally{e=null}}return g.disposable}function d(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}var e,f=new nb(w,b,c,d);return f.scheduleRequired=function(){return!e},f.ensureTrampoline=function(a){e?a():this.schedule(a)},f}(),rb=t;!function(){function a(){if(!n.postMessage||n.importScripts)return!1;var a=!1,b=n.onmessage;return n.onmessage=function(){a=!0},n.postMessage("","*"),n.onmessage=b,a}function b(a){if("string"==typeof a.data&&a.data.substring(0,f.length)===f){var b=a.data.substring(f.length),c=g[b];c(),delete g[b]}}var c=RegExp("^"+String(O).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),d="function"==typeof(d=r&&q&&r.setImmediate)&&!c.test(d)&&d,e="function"==typeof(e=r&&q&&r.clearImmediate)&&!c.test(e)&&e;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))mb=process.nextTick;else if("function"==typeof d)mb=d,rb=e;else if(a()){var f="ms.rx.schedule"+Math.random(),g={},h=0;n.addEventListener?n.addEventListener("message",b,!1):n.attachEvent("onmessage",b,!1),mb=function(a){var b=h++;g[b]=a,n.postMessage(f+b,"*")}}else if(n.MessageChannel){var i=new n.MessageChannel,j={},k=0;i.port1.onmessage=function(a){var b=a.data,c=j[b];c(),delete j[b]},mb=function(a){var b=k++;j[b]=a,i.port2.postMessage(b)}}else"document"in n&&"onreadystatechange"in n.document.createElement("script")?mb=function(a){var b=n.document.createElement("script");b.onreadystatechange=function(){a(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},n.document.documentElement.appendChild(b)}:(mb=function(a){return setTimeout(a,0)},rb=clearTimeout)}();var sb=(nb.timeout=function(){function a(a,b){var c=this,d=new jb,e=mb(function(){d.isDisposed||d.setDisposable(b(c,a))});return new db(d,gb(function(){rb(e)}))}function b(a,b,c){var d=this,e=nb.normalize(b);if(0===e)return d.scheduleWithState(a,c);var f=new jb,g=setTimeout(function(){f.isDisposed||f.setDisposable(c(d,a))},e);return new db(f,gb(function(){clearTimeout(g)}))}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new nb(w,a,b,c)}(),function(a){function b(){return this._scheduler.now()}function c(a,b){return this._scheduler.scheduleWithState(a,this._wrap(b))}function d(a,b,c){return this._scheduler.scheduleWithRelativeAndState(a,b,this._wrap(c))}function e(a,b,c){return this._scheduler.scheduleWithAbsoluteAndState(a,b,this._wrap(c))}function f(f,g){this._scheduler=f,this._handler=g,this._recursiveOriginal=null,this._recursiveWrapper=null,a.call(this,b,c,d,e)}return $(f,a),f.prototype._clone=function(a){return new f(a,this._handler)},f.prototype._wrap=function(a){var b=this;return function(c,d){try{return a(b._getRecursiveWrapper(c),d)}catch(e){if(!b._handler(e))throw e;return hb}}},f.prototype._getRecursiveWrapper=function(a){if(this._recursiveOriginal!==a){this._recursiveOriginal=a;var b=this._clone(a);b._recursiveOriginal=a,b._recursiveWrapper=b,this._recursiveWrapper=b}return this._recursiveWrapper},f.prototype.schedulePeriodicWithState=function(a,b,c){var d=this,e=!1,f=new jb;return f.setDisposable(this._scheduler.schedulePeriodicWithState(a,b,function(a){if(e)return null;try{return c(a)}catch(b){if(e=!0,!d._handler(b))throw b;return f.dispose(),null}})),f},f}(nb)),tb=s.Notification=function(){function a(a,b){this.hasValue=null==b?!1:b,this.kind=a}return a.prototype.accept=function(a,b,c){return a&&"object"==typeof a?this._acceptObservable(a):this._accept(a,b,c)},a.prototype.toObservable=function(a){var b=this;return u(a)||(a=pb),new Ib(function(c){return a.schedule(function(){b._acceptObservable(c),"N"===b.kind&&c.onCompleted()})})},a}(),ub=tb.createOnNext=function(){function a(a){return a(this.value)}function b(a){return a.onNext(this.value)}function c(){return"OnNext("+this.value+")"}return function(d){var e=new tb("N",!0);return e.value=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),vb=tb.createOnError=function(){function a(a,b){return b(this.exception)}function b(a){return a.onError(this.exception)}function c(){return"OnError("+this.exception+")"}return function(d){var e=new tb("E");return e.exception=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),wb=tb.createOnCompleted=function(){function a(a,b,c){return c()}function b(a){return a.onCompleted()}function c(){return"OnCompleted()"}return function(){var d=new tb("C");return d._accept=a,d._acceptObservable=b,d.toString=c,d}}(),xb=s.internals.Enumerator=function(a){this._next=a};xb.prototype.next=function(){return this._next()},xb.prototype[B]=function(){return this};var yb=s.internals.Enumerable=function(a){this._iterator=a};yb.prototype[B]=function(){return this._iterator()},yb.prototype.concat=function(){var a=this;return new Ib(function(b){var c;try{c=a[B]()}catch(d){return void b.onError()}var e,f=new kb,g=pb.scheduleRecursive(function(a){var d;if(!e){try{d=c.next()}catch(g){return void b.onError(g)}if(d.done)return void b.onCompleted();var h=d.value;z(h)&&(h=observableFromPromise(h));var i=new jb;f.setDisposable(i),i.setDisposable(h.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){a()}))}});return new db(f,g,gb(function(){e=!0}))})},yb.prototype.catchException=function(){var a=this;return new Ib(function(b){var c;try{c=a[B]()}catch(d){return void b.onError()}var e,f,g=new kb,h=pb.scheduleRecursive(function(a){if(!e){var d;try{d=c.next()}catch(h){return void b.onError(h)}if(d.done)return void(f?b.onError(f):b.onCompleted());var i=d.value;z(i)&&(i=observableFromPromise(i));var j=new jb;g.setDisposable(j),j.setDisposable(i.subscribe(b.onNext.bind(b),function(b){f=b,a()},b.onCompleted.bind(b)))}});return new db(g,h,gb(function(){e=!0}))})};var zb=(yb.repeat=function(a,b){return null==b&&(b=-1),new yb(function(){var c=b;return new xb(function(){return 0===c?D:(c>0&&c--,{done:!1,value:a})})})},yb.forEach=function(a,b,c){return b||(b=v),new yb(function(){var d=-1;return new xb(function(){return++d0&&(a=!this.isAcquired,this.isAcquired=!0),a&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(a){var c;if(!(b.queue.length>0))return void(b.isAcquired=!1);c=b.queue.shift();try{c()}catch(d){throw b.queue=[],b.hasFaulted=!0,d}a()}))},b.prototype.dispose=function(){a.prototype.dispose.call(this),this.disposable.dispose()},b}(Cb),Gb=function(a){function b(){a.apply(this,arguments)}return $(b,a),b.prototype.next=function(b){a.prototype.next.call(this,b),this.ensureActive()},b.prototype.error=function(b){a.prototype.error.call(this,b),this.ensureActive()},b.prototype.completed=function(){a.prototype.completed.call(this),this.ensureActive()},b}(Fb),Hb=s.Observable=function(){function a(a){this._subscribe=a}return Bb=a.prototype,Bb.subscribe=Bb.forEach=function(a,b,c){var d="object"==typeof a?a:Ab(a,b,c);return this._subscribe(d)},a}(),Ib=s.AnonymousObservable=function(a){function b(a){return a&&"function"==typeof a.dispose?a:"function"==typeof a?gb(a):hb}function c(d){function e(a){var c=function(){try{e.setDisposable(b(d(e)))}catch(a){if(!e.fail(a))throw a}},e=new Jb(a);return qb.scheduleRequired()?qb.schedule(c):c(),e}return this instanceof c?void a.call(this,e):new c(d)}return $(c,a),c}(Hb),Jb=function(a){function b(b){a.call(this),this.observer=b,this.m=new jb}$(b,a);var c=b.prototype;return c.next=function(a){var b=!1;try{this.observer.onNext(a),b=!0}catch(c){throw c}finally{b||this.dispose()}},c.error=function(a){try{this.observer.onError(a)}catch(b){throw b}finally{this.dispose()}},c.completed=function(){try{this.observer.onCompleted()}catch(a){throw a}finally{this.dispose()}},c.setDisposable=function(a){this.m.setDisposable(a)},c.getDisposable=function(){return this.m.getDisposable()},c.disposable=function(a){return arguments.length?this.getDisposable():setDisposable(a)},c.dispose=function(){a.prototype.dispose.call(this),this.m.dispose()},b}(Cb),Kb=function(a,b){this.subject=a,this.observer=b};Kb.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1),this.observer=null}};var Lb=(s.Subject=function(a){function c(a){return b.call(this),this.isStopped?this.exception?(a.onError(this.exception),hb):(a.onCompleted(),hb):(this.observers.push(a),new Kb(this,a))}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return $(d,a),_(d.prototype,zb,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped)for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)},dispose:function(){this.isDisposed=!0,this.observers=null}}),d.create=function(a,b){return new Lb(a,b)},d}(Hb),s.AsyncSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),new Kb(this,a);var c=this.exception,d=this.hasValue,e=this.value;return c?a.onError(c):d?(a.onNext(e),a.onCompleted()):a.onCompleted(),hb}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return $(d,a),_(d.prototype,zb,{hasObservers:function(){return b.call(this),this.observers.length>0},onCompleted:function(){var a,c,d;if(b.call(this),!this.isStopped){this.isStopped=!0;var e=this.observers.slice(0),f=this.value,g=this.hasValue;if(g)for(c=0,d=e.length;d>c;c++)a=e[c],a.onNext(f),a.onCompleted();else for(c=0,d=e.length;d>c;c++)e[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){b.call(this),this.isStopped||(this.value=a,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),d}(Hb),s.AnonymousSubject=function(a){function b(b,c){this.observer=b,this.observable=c,a.call(this,this.observable.subscribe.bind(this.observable))}return $(b,a),_(b.prototype,zb,{onCompleted:function(){this.observer.onCompleted()},onError:function(a){this.observer.onError(a)},onNext:function(a){this.observer.onNext(a)}}),b}(Hb));"function"==typeof define&&"object"==typeof define.amd&&define.amd?(n.Rx=s,define(function(){return s})):o&&p?q?(p.exports=s).Rx=s:o.Rx=s:n.Rx=s}).call(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.experimental.js b/ajax/libs/rxjs/2.3.9/rx.experimental.js new file mode 100644 index 000000000..ea44bec92 --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.experimental.js @@ -0,0 +1,464 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // Aliases + var Observable = Rx.Observable, + observableProto = Observable.prototype, + AnonymousObservable = Rx.AnonymousObservable, + observableConcat = Observable.concat, + observableDefer = Observable.defer, + observableEmpty = Observable.empty, + disposableEmpty = Rx.Disposable.empty, + CompositeDisposable = Rx.CompositeDisposable, + SerialDisposable = Rx.SerialDisposable, + SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, + Enumerator = Rx.internals.Enumerator, + Enumerable = Rx.internals.Enumerable, + enumerableFor = Enumerable.forEach, + immediateScheduler = Rx.Scheduler.immediate, + currentThreadScheduler = Rx.Scheduler.currentThread, + slice = Array.prototype.slice, + AsyncSubject = Rx.AsyncSubject, + Observer = Rx.Observer, + inherits = Rx.internals.inherits, + addProperties = Rx.internals.addProperties, + helpers = Rx.helpers, + noop = helpers.noop, + isPromise = helpers.isPromise, + isScheduler = helpers.isScheduler, + observableFromPromise = Observable.fromPromise; + + // Utilities + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || + '_es6shim_iterator_'; + // Bug for mozilla version + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + + var doneEnumerator = { done: true, value: undefined }; + + function enumerableWhile(condition, source) { + return new Enumerable(function () { + return new Enumerator(function () { + return condition() ? + { done: false, value: source } : + { done: true, value: undefined }; + }); + }); + } + + /** + * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. + * This operator allows for a fluent style of writing queries that use the same sequence multiple times. + * + * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + observableProto.letBind = observableProto['let'] = function (func) { + return func(this); + }; + + /** + * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers 0) { + isOwner = !isAcquired; + isAcquired = true; + } + if (isOwner) { + m.setDisposable(scheduler.scheduleRecursive(function (self) { + var work; + if (q.length > 0) { + work = q.shift(); + } else { + isAcquired = false; + return; + } + var m1 = new SingleAssignmentDisposable(); + d.add(m1); + m1.setDisposable(work.subscribe(function (x) { + observer.onNext(x); + var result = null; + try { + result = selector(x); + } catch (e) { + observer.onError(e); + } + q.push(result); + activeCount++; + ensureActive(); + }, observer.onError.bind(observer), function () { + d.remove(m1); + activeCount--; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + self(); + })); + } + }; + + q.push(source); + activeCount++; + ensureActive(); + return d; + }); + }; + + /** + * Runs all observable sequences in parallel and collect their last elements. + * + * @example + * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); + * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); + * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. + */ + Observable.forkJoin = function () { + var allSources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (subscriber) { + var count = allSources.length; + if (count === 0) { + subscriber.onCompleted(); + return disposableEmpty; + } + var group = new CompositeDisposable(), + finished = false, + hasResults = new Array(count), + hasCompleted = new Array(count), + results = new Array(count); + + for (var idx = 0; idx < count; idx++) { + (function (i) { + var source = allSources[i]; + isPromise(source) && (source = observableFromPromise(source)); + group.add( + source.subscribe( + function (value) { + if (!finished) { + hasResults[i] = true; + results[i] = value; + } + }, + function (e) { + finished = true; + subscriber.onError(e); + group.dispose(); + }, + function () { + if (!finished) { + if (!hasResults[i]) { + subscriber.onCompleted(); + return; + } + hasCompleted[i] = true; + for (var ix = 0; ix < count; ix++) { + if (!hasCompleted[ix]) { return; } + } + finished = true; + subscriber.onNext(results); + subscriber.onCompleted(); + } + })); + })(idx); + } + + return group; + }); + }; + + /** + * Runs two observable sequences in parallel and combines their last elemenets. + * + * @param {Observable} second Second observable sequence. + * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. + * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. + */ + observableProto.forkJoin = function (second, resultSelector) { + var first = this; + + return new AnonymousObservable(function (observer) { + var leftStopped = false, rightStopped = false, + hasLeft = false, hasRight = false, + lastLeft, lastRight, + leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); + + isPromise(second) && (second = observableFromPromise(second)); + + leftSubscription.setDisposable( + first.subscribe(function (left) { + hasLeft = true; + lastLeft = left; + }, function (err) { + rightSubscription.dispose(); + observer.onError(err); + }, function () { + leftStopped = true; + if (rightStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + rightSubscription.setDisposable( + second.subscribe(function (right) { + hasRight = true; + lastRight = right; + }, function (err) { + leftSubscription.dispose(); + observer.onError(err); + }, function () { + rightStopped = true; + if (leftStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + return new CompositeDisposable(leftSubscription, rightSubscription); + }); + }; + + /** + * Comonadic bind operator. + * @param {Function} selector A transform function to apply to each element. + * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. + * @returns {Observable} An observable sequence which results from the comonadic bind operation. + */ + observableProto.manySelect = function (selector, scheduler) { + isScheduler(scheduler) || (scheduler = immediateScheduler); + var source = this; + return observableDefer(function () { + var chain; + + return source + .map(function (x) { + var curr = new ChainObservable(x); + + chain && chain.onNext(x); + chain = curr; + + return curr; + }) + .tap( + noop, + function (e) { chain && chain.onError(e); }, + function () { chain && chain.onCompleted(); } + ) + .observeOn(scheduler) + .map(selector); + }); + }; + + var ChainObservable = (function (__super__) { + + function subscribe (observer) { + var self = this, g = new CompositeDisposable(); + g.add(currentThreadScheduler.schedule(function () { + observer.onNext(self.head); + g.add(self.tail.mergeObservable().subscribe(observer)); + })); + + return g; + } + + inherits(ChainObservable, __super__); + + function ChainObservable(head) { + __super__.call(this, subscribe); + this.head = head; + this.tail = new AsyncSubject(); + } + + addProperties(ChainObservable.prototype, Observer, { + onCompleted: function () { + this.onNext(Observable.empty()); + }, + onError: function (e) { + this.onNext(Observable.throwException(e)); + }, + onNext: function (v) { + this.tail.onNext(v); + this.tail.onCompleted(); + } + }); + + return ChainObservable; + + }(Observable)); + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.experimental.min.js b/ajax/libs/rxjs/2.3.9/rx.experimental.min.js new file mode 100644 index 000000000..9bb59edcc --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.experimental.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c,d){function e(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:v.call(a)}function f(a,b){return new r(function(){return new q(function(){return a()?{done:!1,value:b}:{done:!0,value:d}})})}var g=c.Observable,h=g.prototype,i=c.AnonymousObservable,j=g.concat,k=g.defer,l=g.empty,m=c.Disposable.empty,n=c.CompositeDisposable,o=c.SerialDisposable,p=c.SingleAssignmentDisposable,q=c.internals.Enumerator,r=c.internals.Enumerable,s=r.forEach,t=c.Scheduler.immediate,u=c.Scheduler.currentThread,v=Array.prototype.slice,w=c.AsyncSubject,x=c.Observer,y=c.internals.inherits,z=c.internals.addProperties,A=c.helpers,B=A.noop,C=A.isPromise,D=A.isScheduler,E=g.fromPromise,F="function"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";a.Set&&"function"==typeof(new a.Set)["@@iterator"]&&(F="@@iterator");h.letBind=h.let=function(a){return a(this)},g["if"]=g.ifThen=function(a,b,c){return k(function(){return c||(c=l()),C(b)&&(b=E(b)),C(c)&&(c=E(c)),"function"==typeof c.now&&(c=l(c)),a()?b:c})},g["for"]=g.forIn=function(a,b){return s(a,b).concat()};var G=g["while"]=g.whileDo=function(a,b){return C(b)&&(b=E(b)),f(a,b).concat()};h.doWhile=function(a){return j([this,G(a,this)])},g["case"]=g.switchCase=function(a,b,c){return k(function(){C(c)&&(c=E(c)),c||(c=l()),"function"==typeof c.now&&(c=l(c));var d=b[a()];return C(d)&&(d=E(d)),d||c})},h.expand=function(a,b){D(b)||(b=t);var c=this;return new i(function(d){var e=[],f=new o,g=new n(f),h=0,i=!1,j=function(){var c=!1;e.length>0&&(c=!i,i=!0),c&&f.setDisposable(b.scheduleRecursive(function(b){var c;if(!(e.length>0))return void(i=!1);c=e.shift();var f=new p;g.add(f),f.setDisposable(c.subscribe(function(b){d.onNext(b);var c=null;try{c=a(b)}catch(f){d.onError(f)}e.push(c),h++,j()},d.onError.bind(d),function(){g.remove(f),h--,0===h&&d.onCompleted()})),b()}))};return e.push(c),h++,j(),g})},g.forkJoin=function(){var a=e(arguments,0);return new i(function(b){var c=a.length;if(0===c)return b.onCompleted(),m;for(var d=new n,e=!1,f=new Array(c),g=new Array(c),h=new Array(c),i=0;c>i;i++)!function(i){var j=a[i];C(j)&&(j=E(j)),d.add(j.subscribe(function(a){e||(f[i]=!0,h[i]=a)},function(a){e=!0,b.onError(a),d.dispose()},function(){if(!e){if(!f[i])return void b.onCompleted();g[i]=!0;for(var a=0;c>a;a++)if(!g[a])return;e=!0,b.onNext(h),b.onCompleted()}}))}(i);return d})},h.forkJoin=function(a,b){var c=this;return new i(function(d){var e,f,g=!1,h=!1,i=!1,j=!1,k=new p,l=new p;return C(a)&&(a=E(a)),k.setDisposable(c.subscribe(function(a){i=!0,e=a},function(a){l.dispose(),d.onError(a)},function(){if(g=!0,h)if(i)if(j){var a;try{a=b(e,f)}catch(c){return void d.onError(c)}d.onNext(a),d.onCompleted()}else d.onCompleted();else d.onCompleted()})),l.setDisposable(a.subscribe(function(a){j=!0,f=a},function(a){k.dispose(),d.onError(a)},function(){if(h=!0,g)if(i)if(j){var a;try{a=b(e,f)}catch(c){return void d.onError(c)}d.onNext(a),d.onCompleted()}else d.onCompleted();else d.onCompleted()})),new n(k,l)})},h.manySelect=function(a,b){D(b)||(b=t);var c=this;return k(function(){var d;return c.map(function(a){var b=new H(a);return d&&d.onNext(a),d=b,b}).tap(B,function(a){d&&d.onError(a)},function(){d&&d.onCompleted()}).observeOn(b).map(a)})};var H=function(a){function b(a){var b=this,c=new n;return c.add(u.schedule(function(){a.onNext(b.head),c.add(b.tail.mergeObservable().subscribe(a))})),c}function c(c){a.call(this,b),this.head=c,this.tail=new w}return y(c,a),z(c.prototype,x,{onCompleted:function(){this.onNext(g.empty())},onError:function(a){this.onNext(g.throwException(a))},onNext:function(a){this.tail.onNext(a),this.tail.onCompleted()}}),c}(g);return c}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.joinpatterns.js b/ajax/libs/rxjs/2.3.9/rx.joinpatterns.js new file mode 100644 index 000000000..1cda7962f --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.joinpatterns.js @@ -0,0 +1,415 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // Aliases + var Observable = Rx.Observable, + observableProto = Observable.prototype, + AnonymousObservable = Rx.AnonymousObservable, + observableThrow = Observable.throwException, + observerCreate = Rx.Observer.create, + SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, + CompositeDisposable = Rx.CompositeDisposable, + AbstractObserver = Rx.internals.AbstractObserver, + noop = Rx.helpers.noop, + defaultComparer = Rx.internals.isEqual, + inherits = Rx.internals.inherits, + slice = Array.prototype.slice; + + // Utilities + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + + /** @private */ + var Map = (function () { + + /** + * @constructor + * @private + */ + function Map() { + this.keys = []; + this.values = []; + } + + /** + * @private + * @memberOf Map# + */ + Map.prototype['delete'] = function (key) { + var i = this.keys.indexOf(key); + if (i !== -1) { + this.keys.splice(i, 1); + this.values.splice(i, 1); + } + return i !== -1; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.get = function (key, fallback) { + var i = this.keys.indexOf(key); + return i !== -1 ? this.values[i] : fallback; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.set = function (key, value) { + var i = this.keys.indexOf(key); + if (i !== -1) { + this.values[i] = value; + } + this.values[this.keys.push(key) - 1] = value; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.size = function () { return this.keys.length; }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.has = function (key) { + return this.keys.indexOf(key) !== -1; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.getKeys = function () { return this.keys.slice(0); }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.getValues = function () { return this.values.slice(0); }; + + return Map; + }()); + + /** + * @constructor + * Represents a join pattern over observable sequences. + */ + function Pattern(patterns) { + this.patterns = patterns; + } + + /** + * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. + * + * @param other Observable sequence to match in addition to the current pattern. + * @return Pattern object that matches when all observable sequences in the pattern have an available value. + */ + Pattern.prototype.and = function (other) { + var patterns = this.patterns.slice(0); + patterns.push(other); + return new Pattern(patterns); + }; + + /** + * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. + * + * @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. + * @return Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + Pattern.prototype.thenDo = function (selector) { + return new Plan(this, selector); + }; + + function Plan(expression, selector) { + this.expression = expression; + this.selector = selector; + } + + Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { + var self = this; + var joinObservers = []; + for (var i = 0, len = this.expression.patterns.length; i < len; i++) { + joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); + } + var activePlan = new ActivePlan(joinObservers, function () { + var result; + try { + result = self.selector.apply(self, arguments); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, function () { + for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { + joinObservers[j].removeActivePlan(activePlan); + } + deactivate(activePlan); + }); + for (i = 0, len = joinObservers.length; i < len; i++) { + joinObservers[i].addActivePlan(activePlan); + } + return activePlan; + }; + + function planCreateObserver(externalSubscriptions, observable, onError) { + var entry = externalSubscriptions.get(observable); + if (!entry) { + var observer = new JoinObserver(observable, onError); + externalSubscriptions.set(observable, observer); + return observer; + } + return entry; + } + + // Active Plan + function ActivePlan(joinObserverArray, onNext, onCompleted) { + var i, joinObserver; + this.joinObserverArray = joinObserverArray; + this.onNext = onNext; + this.onCompleted = onCompleted; + this.joinObservers = new Map(); + for (i = 0; i < this.joinObserverArray.length; i++) { + joinObserver = this.joinObserverArray[i]; + this.joinObservers.set(joinObserver, joinObserver); + } + } + + ActivePlan.prototype.dequeue = function () { + var values = this.joinObservers.getValues(); + for (var i = 0, len = values.length; i < len; i++) { + values[i].queue.shift(); + } + }; + ActivePlan.prototype.match = function () { + var firstValues, i, len, isCompleted, values, hasValues = true; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + if (this.joinObserverArray[i].queue.length === 0) { + hasValues = false; + break; + } + } + if (hasValues) { + firstValues = []; + isCompleted = false; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + firstValues.push(this.joinObserverArray[i].queue[0]); + if (this.joinObserverArray[i].queue[0].kind === 'C') { + isCompleted = true; + } + } + if (isCompleted) { + this.onCompleted(); + } else { + this.dequeue(); + values = []; + for (i = 0; i < firstValues.length; i++) { + values.push(firstValues[i].value); + } + this.onNext.apply(this, values); + } + } + }; + + /** @private */ + var JoinObserver = (function (_super) { + + inherits(JoinObserver, _super); + + /** + * @constructor + * @private + */ + function JoinObserver(source, onError) { + _super.call(this); + this.source = source; + this.onError = onError; + this.queue = []; + this.activePlans = []; + this.subscription = new SingleAssignmentDisposable(); + this.isDisposed = false; + } + + var JoinObserverPrototype = JoinObserver.prototype; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.next = function (notification) { + if (!this.isDisposed) { + if (notification.kind === 'E') { + this.onError(notification.exception); + return; + } + this.queue.push(notification); + var activePlans = this.activePlans.slice(0); + for (var i = 0, len = activePlans.length; i < len; i++) { + activePlans[i].match(); + } + } + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.error = noop; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.completed = noop; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.addActivePlan = function (activePlan) { + this.activePlans.push(activePlan); + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.subscribe = function () { + this.subscription.setDisposable(this.source.materialize().subscribe(this)); + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.removeActivePlan = function (activePlan) { + var idx = this.activePlans.indexOf(activePlan); + this.activePlans.splice(idx, 1); + if (this.activePlans.length === 0) { + this.dispose(); + } + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + if (!this.isDisposed) { + this.isDisposed = true; + this.subscription.dispose(); + } + }; + + return JoinObserver; + } (AbstractObserver)); + + /** + * Creates a pattern that matches when both observable sequences have an available value. + * + * @param right Observable sequence to match with the current sequence. + * @return {Pattern} Pattern object that matches when both observable sequences have an available value. + */ + observableProto.and = function (right) { + return new Pattern([this, right]); + }; + + /** + * Matches when the observable sequence has an available value and projects the value. + * + * @param selector Selector that will be invoked for values in the source sequence. + * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + observableProto.thenDo = function (selector) { + return new Pattern([this]).thenDo(selector); + }; + + /** + * Joins together the results from several patterns. + * + * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. + * @returns {Observable} Observable sequence with the results form matching several patterns. + */ + Observable.when = function () { + var plans = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var activePlans = [], + externalSubscriptions = new Map(), + group, + i, len, + joinObserver, + joinValues, + outObserver; + outObserver = observerCreate(observer.onNext.bind(observer), function (exception) { + var values = externalSubscriptions.getValues(); + for (var j = 0, jlen = values.length; j < jlen; j++) { + values[j].onError(exception); + } + observer.onError(exception); + }, observer.onCompleted.bind(observer)); + try { + for (i = 0, len = plans.length; i < len; i++) { + activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { + var idx = activePlans.indexOf(activePlan); + activePlans.splice(idx, 1); + if (activePlans.length === 0) { + outObserver.onCompleted(); + } + })); + } + } catch (e) { + observableThrow(e).subscribe(observer); + } + group = new CompositeDisposable(); + joinValues = externalSubscriptions.getValues(); + for (i = 0, len = joinValues.length; i < len; i++) { + joinObserver = joinValues[i]; + joinObserver.subscribe(); + group.add(joinObserver); + } + return group; + }); + }; + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.joinpatterns.min.js b/ajax/libs/rxjs/2.3.9/rx.joinpatterns.min.js new file mode 100644 index 000000000..c4d5f868e --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.joinpatterns.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c){function d(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:s.call(a)}function e(a){this.patterns=a}function f(a,b){this.expression=a,this.selector=b}function g(a,b,c){var d=a.get(b);if(!d){var e=new u(b,c);return a.set(b,e),e}return d}function h(a,b,c){var d,e;for(this.joinObserverArray=a,this.onNext=b,this.onCompleted=c,this.joinObservers=new t,d=0;df;f++)e.push(g(a,this.expression.patterns[f],b.onError.bind(b)));var j=new h(e,function(){var a;try{a=d.selector.apply(d,arguments)}catch(c){return void b.onError(c)}b.onNext(a)},function(){for(var a=0,b=e.length;b>a;a++)e[a].removeActivePlan(j);c(j)});for(f=0,i=e.length;i>f;f++)e[f].addActivePlan(j);return j},h.prototype.dequeue=function(){for(var a=this.joinObservers.getValues(),b=0,c=a.length;c>b;b++)a[b].queue.shift()},h.prototype.match=function(){var a,b,c,d,e,f=!0;for(b=0,c=this.joinObserverArray.length;c>b;b++)if(0===this.joinObserverArray[b].queue.length){f=!1;break}if(f){for(a=[],d=!1,b=0,c=this.joinObserverArray.length;c>b;b++)a.push(this.joinObserverArray[b].queue[0]),"C"===this.joinObserverArray[b].queue[0].kind&&(d=!0);if(d)this.onCompleted();else{for(this.dequeue(),e=[],b=0;bc;c++)b[c].match()}},c.error=q,c.completed=q,c.addActivePlan=function(a){this.activePlans.push(a)},c.subscribe=function(){this.subscription.setDisposable(this.source.materialize().subscribe(this))},c.removeActivePlan=function(a){var b=this.activePlans.indexOf(a);this.activePlans.splice(b,1),0===this.activePlans.length&&this.dispose()},c.dispose=function(){a.prototype.dispose.call(this),this.isDisposed||(this.isDisposed=!0,this.subscription.dispose())},b}(p);return j.and=function(a){return new e([this,a])},j.thenDo=function(a){return new e([this]).thenDo(a)},i.when=function(){var a=d(arguments,0);return new k(function(b){var c,d,e,f,g,h,i=[],j=new t;h=m(b.onNext.bind(b),function(a){for(var c=j.getValues(),d=0,e=c.length;e>d;d++)c[d].onError(a);b.onError(a)},b.onCompleted.bind(b));try{for(d=0,e=a.length;e>d;d++)i.push(a[d].activate(j,h,function(a){var b=i.indexOf(a);i.splice(b,1),0===i.length&&h.onCompleted()}))}catch(k){l(k).subscribe(b)}for(c=new o,g=j.getValues(),d=0,e=g.length;e>d;d++)f=g[d],f.subscribe(),c.add(f);return c})},c}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.js b/ajax/libs/rxjs/2.3.9/rx.js new file mode 100644 index 000000000..4e86567ae --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.js @@ -0,0 +1,4525 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { + + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, + isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = Date.now, + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || + '_es6shim_iterator_'; + // Bug for mozilla version + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { + return; + } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { + return; + } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = + SerialDisposable = Rx.SerialDisposable = (function () { + function BooleanDisposable () { + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + old && old.dispose(); + shouldDispose && value && value.dispose(); + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + old && old.dispose(); + }; + + return BooleanDisposable; + }()); + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + timeSpan < 0 && (timeSpan = 0); + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + (function (schedulerProto) { + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function scheduleInnerRecursive(action, self) { + action(function(dt) { self(action, dt); }); + } + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { self(_action); }); }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + }(Scheduler.prototype)); + + (function (schedulerProto) { + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, action); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var s = state; + + var id = setInterval(function () { + s = action(s); + }, period); + + return disposableCreate(function () { + clearInterval(id); + }); + }; + }(Scheduler.prototype)); + + (function (schedulerProto) { + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchError = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + }(Scheduler.prototype)); + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt); + + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + + currentScheduler.scheduleRequired = function () { return !queue; }; + currentScheduler.ensureTrampoline = function (action) { + if (!queue) { this.schedule(action); } else { action(); } + }; + + return currentScheduler; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, + dt = Scheduler.normalize(dueTime); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** @private */ + var CatchScheduler = (function (_super) { + + function localNow() { + return this._scheduler.now(); + } + + function scheduleNow(state, action) { + return this._scheduler.scheduleWithState(state, this._wrap(action)); + } + + function scheduleRelative(state, dueTime, action) { + return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); + } + + function scheduleAbsolute(state, dueTime, action) { + return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); + } + + inherits(CatchScheduler, _super); + + /** @private */ + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + /** @private */ + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + /** @private */ + CatchScheduler.prototype._wrap = function (action) { + var parent = this; + return function (self, state) { + try { + return action(parent._getRecursiveWrapper(self), state); + } catch (e) { + if (!parent._handler(e)) { throw e; } + return disposableEmpty; + } + }; + }; + + /** @private */ + CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { + if (this._recursiveOriginal !== scheduler) { + this._recursiveOriginal = scheduler; + var wrapper = this._clone(scheduler); + wrapper._recursiveOriginal = scheduler; + wrapper._recursiveWrapper = wrapper; + this._recursiveWrapper = wrapper; + } + return this._recursiveWrapper; + }; + + /** @private */ + CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var self = this, failed = false, d = new SingleAssignmentDisposable(); + + d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { + if (failed) { return null; } + try { + return action(state1); + } catch (e) { + failed = true; + if (!self._handler(e)) { throw e; } + d.dispose(); + return null; + } + })); + + return d; + }; + + return CatchScheduler; + }(Scheduler)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { + return observerOrOnNext && typeof observerOrOnNext === 'object' ? + this._acceptObservable(observerOrOnNext) : + this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notifications + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + Notification.prototype.toObservable = function (scheduler) { + var notification = this; + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + notification.kind === 'N' && observer.onCompleted(); + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + + function _accept (onNext) { return onNext(this.value); } + function _acceptObservable(observer) { return observer.onNext(this.value); } + function toString () { return 'OnNext(' + this.value + ')'; } + + return function (value) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + + function _accept (onNext, onError) { return onError(this.exception); } + function _acceptObservable(observer) { return observer.onError(this.exception); } + function toString () { return 'OnError(' + this.exception + ')'; } + + return function (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { return onCompleted(); } + function _acceptObservable(observer) { return observer.onCompleted(); } + function toString () { return 'OnCompleted()'; } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var CheckedObserver = (function (_super) { + inherits(CheckedObserver, _super); + + function CheckedObserver(observer) { + _super.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + try { + this._observer.onNext(value); + } catch (e) { + throw e; + } finally { + this._state = 0; + } + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + try { + this._observer.onError(err); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + try { + this._observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { + inherits(ScheduledObserver, _super); + + function ScheduledObserver(scheduler, observer) { + _super.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + /** @private */ + var ObserveOnObserver = (function (_super) { + inherits(ObserveOnObserver, _super); + + /** @private */ + function ObserveOnObserver() { + _super.apply(this, arguments); + } + + /** @private */ + ObserveOnObserver.prototype.next = function (value) { + _super.prototype.next.call(this, value); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.error = function (e) { + _super.prototype.error.call(this, e); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.completed = function () { + _super.prototype.completed.call(this); + this.ensureActive(); + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber = typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted); + + return this._subscribe(subscriber); + }; + + return Observable; + })(); + + /** + * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + * + * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects + * that require to be run on a scheduler, use subscribeOn. + * + * @param {Scheduler} scheduler Scheduler to notify observers on. + * @returns {Observable} The source sequence whose observations happen on the specified scheduler. + */ + observableProto.observeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(new ObserveOnObserver(scheduler, observer)); + }); + }; + + /** + * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; + * see the remarks section for more information on the distinction between subscribeOn and observeOn. + + * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer + * callbacks on a scheduler, use observeOn. + + * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. + * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); + d.setDisposable(m); + m.setDisposable(scheduler.schedule(function () { + d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); + })); + return d; + }); + }; + + /** + * Converts a Promise to an Observable sequence + * @param {Promise} An ES6 Compliant promise. + * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. + */ + var observableFromPromise = Observable.fromPromise = function (promise) { + return observableDefer(function () { + var subject = new Rx.AsyncSubject(); + + promise.then( + function (value) { + if (!subject.isDisposed) { + subject.onNext(value); + subject.onCompleted(); + } + }, + subject.onError.bind(subject)); + + return subject; + }); + }; + /* + * Converts an existing observable sequence to an ES6 Compatible Promise + * @example + * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); + * + * // With config + * Rx.config.Promise = RSVP.Promise; + * var promise = Rx.Observable.return(42).toPromise(); + * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. + * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. + */ + observableProto.toPromise = function (promiseCtor) { + promiseCtor || (promiseCtor = Rx.config.Promise); + if (!promiseCtor) { + throw new Error('Promise type not provided nor in Rx.config.Promise'); + } + var source = this; + return new promiseCtor(function (resolve, reject) { + // No cancellation can be done + var value, hasValue = false; + source.subscribe(function (v) { + value = v; + hasValue = true; + }, function (err) { + reject(err); + }, function () { + if (hasValue) { + resolve(value); + } + }); + }); + }; + /** + * Creates a list from an observable sequence. + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + var self = this; + return new AnonymousObservable(function(observer) { + var arr = []; + return self.subscribe( + arr.push.bind(arr), + observer.onError.bind(observer), + function () { + observer.onNext(arr); + observer.onCompleted(); + }); + }); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.create = Observable.createWithDisposable = function (subscribe) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + var maxSafeInteger = Math.pow(2, 53) - 1; + + function numberIsFinite(value) { + return typeof value === 'number' && root.isFinite(value); + } + + function isNan(n) { + return n !== n; + } + + function isIterable(o) { + return o[$iterator$] !== undefined; + } + + function sign(value) { + var number = +value; + if (number === 0) { return number; } + if (isNaN(number)) { return number; } + return number < 0 ? -1 : 1; + } + + function toLength(o) { + var len = +o.length; + if (isNaN(len)) { return 0; } + if (len === 0 || !numberIsFinite(len)) { return len; } + len = sign(len) * Math.floor(Math.abs(len)); + if (len <= 0) { return 0; } + if (len > maxSafeInteger) { return maxSafeInteger; } + return len; + } + + function isCallable(f) { + return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; + } + + /** + * This method creates a new Observable sequence from an array-like or iterable object. + * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. + * @param {Function} [mapFn] Map function to call on every element of the array. + * @param {Any} [thisArg] The context to use calling the mapFn if provided. + * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + Observable.from = function (iterable, mapFn, thisArg, scheduler) { + if (iterable == null) { + throw new Error('iterable cannot be null.') + } + if (mapFn && !isCallable(mapFn)) { + throw new Error('mapFn when provided must be a function'); + } + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var list = Object(iterable), + objIsIterable = isIterable(list), + len = objIsIterable ? 0 : toLength(list), + it = objIsIterable ? list[$iterator$]() : null, + i = 0; + return scheduler.scheduleRecursive(function (self) { + if (i < len || objIsIterable) { + var result; + if (objIsIterable) { + var next = it.next(); + if (next.done) { + observer.onCompleted(); + return; + } + + result = next.value; + } else { + result = list[i]; + } + + if (mapFn && isCallable(mapFn)) { + try { + result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); + } catch (e) { + observer.onError(e); + return; + } + } + + observer.onNext(result); + i++; + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * var res = Rx.Observable.fromArray([1,2,3]); + * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0, len = array.length; + return scheduler.scheduleRecursive(function (self) { + if (count < len) { + observer.onNext(array[count++]); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. + * @returns {Observable} The generated sequence. + */ + Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var first = true, state = initialState; + return scheduler.scheduleRecursive(function (self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + } + } catch (exception) { + observer.onError(exception); + return; + } + if (hasResult) { + observer.onNext(result); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). + * @returns {Observable} An observable sequence whose observers will never get called. + */ + var observableNever = Observable.never = function () { + return new AnonymousObservable(function () { + return disposableEmpty; + }); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.of = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return observableFromArray(args); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + var observableOf = Observable.ofWithScheduler = function (scheduler) { + var len = arguments.length - 1, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } + return observableFromArray(args, scheduler); + }; + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.range(0, 10); + * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleRecursiveWithState(0, function (i, self) { + if (i < count) { + observer.onNext(start + i); + self(i + 1); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.repeat(42); + * var res = Rx.Observable.repeat(42, 4); + * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'just', and 'returnValue' for browsers 0) { + subscribe(q.shift()); + } else { + activeCount--; + isStopped && activeCount === 0 && observer.onCompleted(); + } + })); + } + group.add(sources.subscribe(function (innerSource) { + if (activeCount < maxConcurrentOrOther) { + activeCount++; + subscribe(innerSource); + } else { + q.push(innerSource); + } + }, observer.onError.bind(observer), function () { + isStopped = true; + activeCount === 0 && observer.onCompleted(); + })); + return group; + }); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * + * @example + * 1 - merged = Rx.Observable.merge(xs, ys, zs); + * 2 - merged = Rx.Observable.merge([xs, ys, zs]); + * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); + * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources; + if (!arguments[0]) { + scheduler = immediateScheduler; + sources = slice.call(arguments, 1); + } else if (arguments[0].now) { + scheduler = arguments[0]; + sources = slice.call(arguments, 1); + } else { + scheduler = immediateScheduler; + sources = slice.call(arguments, 0); + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableFromArray(sources, scheduler).mergeObservable(); + }; + + /** + * Merges an observable sequence of observable sequences into an observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.mergeObservable = observableProto.mergeAll =function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + isStopped = false, + m = new SingleAssignmentDisposable(); + + group.add(m); + m.setDisposable(sources.subscribe(function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + innerSubscription.setDisposable(innerSource.subscribe(function (x) { + observer.onNext(x); + }, observer.onError.bind(observer), function () { + group.remove(innerSubscription); + if (isStopped && group.length === 1) { observer.onCompleted(); } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (group.length === 1) { observer.onCompleted(); } + })); + return group; + }); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. + * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. + */ + observableProto.onErrorResumeNext = function (second) { + if (!second) { + throw new Error('Second observable is required'); + } + return onErrorResumeNext([this, second]); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * + * @example + * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); + * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); + * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. + */ + var onErrorResumeNext = Observable.onErrorResumeNext = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var pos = 0, subscription = new SerialDisposable(), + cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, d; + if (pos < sources.length) { + current = sources[pos++]; + isPromise(current) && (current = observableFromPromise(current)); + d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { + self(); + }, function () { + self(); + })); + } else { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + isOpen && observer.onNext(left); + }, observer.onError.bind(observer), function () { + isOpen && observer.onCompleted(); + })); + + isPromise(other) && (other = observableFromPromise(other)); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, observer.onError.bind(observer), function () { + rightSubscription.dispose(); + })); + + return disposables; + }); + }; + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasLatest = false, + innerSubscription = new SerialDisposable(), + isStopped = false, + latest = 0, + subscription = sources.subscribe(function (innerSource) { + var d = new SingleAssignmentDisposable(), id = ++latest; + hasLatest = true; + innerSubscription.setDisposable(d); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + d.setDisposable(innerSource.subscribe(function (x) { + if (latest === id) { + observer.onNext(x); + } + }, function (e) { + if (latest === id) { + observer.onError(e); + } + }, function () { + if (latest === id) { + hasLatest = false; + if (isStopped) { + observer.onCompleted(); + } + } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (!hasLatest) { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, innerSubscription); + }); + }; + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + isPromise(other) && (other = observableFromPromise(other)); + return new CompositeDisposable( + source.subscribe(observer), + other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) + ); + }); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], result; + try { + result = resultSelector(left, right); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + } else { + observer.onCompleted(); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. + * + * @example + * 1 - res = obs1.zip(obs2, fn); + * 1 - res = x1.zip([1,2,3], fn); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { + return zipArray.apply(this, arguments); + } + var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); + sources.unshift(parent); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + var res, queuedValues; + if (queues.every(function (x) { return x.length > 0; })) { + try { + queuedValues = queues.map(function (x) { return x.shift(); }); + res = resultSelector.apply(parent, queuedValues); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(function (x) { return x; })) { + observer.onCompleted(); + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = sources[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + * @param arguments Observable sources. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var args = slice.call(arguments, 0), + first = args.shift(); + return first.zip.apply(first, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + return; + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(identity)) { + observer.onCompleted(); + return; + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + })(idx); + } + + var compositeDisposable = new CompositeDisposable(subscriptions); + compositeDisposable.add(disposableCreate(function () { + for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { + queues[qIdx] = []; + } + })); + return compositeDisposable; + }); + }; + + /** + * Hides the identity of an observable sequence. + * @returns {Observable} An observable sequence that hides the identity of the source sequence. + */ + observableProto.asObservable = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(observer); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. + * + * @example + * var res = xs.bufferWithCount(10); + * var res = xs.bufferWithCount(10, 1); + * @param {Number} count Length of each buffer. + * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithCount = function (count, skip) { + if (typeof skip !== 'number') { + skip = count; + } + return this.windowWithCount(count, skip).selectMany(function (x) { + return x.toArray(); + }).where(function (x) { + return x.length > 0; + }); + }; + + /** + * Dematerializes the explicit notification values of an observable sequence as implicit notifications. + * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + return x.accept(observer); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + * + * var obs = observable.distinctUntilChanged(); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. + * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. + * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + observableProto.distinctUntilChanged = function (keySelector, comparer) { + var source = this; + keySelector || (keySelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var comparerEquals = false, key; + try { + key = keySelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + if (hasCurrentKey) { + try { + comparerEquals = comparer(currentKey, key); + } catch (exception) { + observer.onError(exception); + return; + } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + observer.onNext(value); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * + * @example + * var res = observable.do(observer); + * var res = observable.do(onNext); + * var res = observable.do(onNext, onError); + * var res = observable.do(onNext, onError, onCompleted); + * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { + var source = this, onNextFunc; + if (typeof observerOrOnNext === 'function') { + onNextFunc = observerOrOnNext; + } else { + onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); + onError = observerOrOnNext.onError.bind(observerOrOnNext); + onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); + } + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + try { + onNextFunc(x); + } catch (e) { + observer.onError(e); + } + observer.onNext(x); + }, function (err) { + if (!onError) { + observer.onError(err); + } else { + try { + onError(err); + } catch (e) { + observer.onError(e); + } + observer.onError(err); + } + }, function () { + if (!onCompleted) { + observer.onCompleted(); + } else { + try { + onCompleted(); + } catch (e) { + observer.onError(e); + } + observer.onCompleted(); + } + }); + }); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * + * @example + * var res = observable.finallyAction(function () { console.log('sequence ended'; }); + * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. + * @returns {Observable} Source sequence with the action-invoking termination behavior applied. + */ + observableProto['finally'] = observableProto.finallyAction = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription; + try { + subscription = source.subscribe(observer); + } catch (e) { + action(); + throw e; + } + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Materializes the implicit notifications of an observable sequence as explicit notification values. + * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. + */ + observableProto.materialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (value) { + observer.onNext(notificationCreateOnNext(value)); + }, function (e) { + observer.onNext(notificationCreateOnError(e)); + observer.onCompleted(); + }, function () { + observer.onNext(notificationCreateOnCompleted()); + observer.onCompleted(); + }); + }); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * + * @example + * var res = repeated = source.repeat(); + * var res = repeated = source.repeat(42); + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + observableProto.repeat = function (repeatCount) { + return enumerableRepeat(this, repeatCount).concat(); + }; + + /** + * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. + * Note if you encounter an error and want it to retry once, then you must use .retry(2); + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(2); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchException(); + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @example + * var res = source.scan(function (acc, x) { return acc + x; }); + * var res = source.scan(0, function (acc, x) { return acc + x; }); + * @param {Mixed} [seed] The initial accumulator value. + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @returns {Observable} An observable sequence containing the accumulated values. + */ + observableProto.scan = function () { + var hasSeed = false, seed, accumulator, source = this; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[0]; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return new AnonymousObservable(function (observer) { + var hasAccumulation, accumulation, hasValue; + return source.subscribe ( + function (x) { + try { + if (!hasValue) { + hasValue = true; + } + + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(accumulation); + }, + observer.onError.bind(observer), + function () { + if (!hasValue && hasSeed) { + observer.onNext(seed); + } + observer.onCompleted(); + } + ); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + observer.onNext(q.shift()); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * + * @memberOf Observable# + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && 'now' in Object(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + values = slice.call(arguments, start); + return enumerableFor([observableFromArray(values, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence. + * + * @example + * var res = source.takeLast(5); + * + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, observer.onError.bind(observer), function () { + while(q.length > 0) { observer.onNext(q.shift()); } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, observer.onError.bind(observer), function () { + observer.onNext(q); + observer.onCompleted(); + }); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. + * + * var res = xs.windowWithCount(10); + * var res = xs.windowWithCount(10, 1); + * @param {Number} count Length of each window. + * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithCount = function (count, skip) { + var source = this; + if (count <= 0) { + throw new Error(argumentOutOfRange); + } + if (arguments.length === 1) { + skip = count; + } + if (skip <= 0) { + throw new Error(argumentOutOfRange); + } + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), + refCountDisposable = new RefCountDisposable(m), + n = 0, + q = [], + createWindow = function () { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + }; + createWindow(); + m.setDisposable(source.subscribe(function (x) { + var s; + for (var i = 0, len = q.length; i < len; i++) { + q[i].onNext(x); + } + var c = n - count + 1; + if (c >= 0 && c % skip === 0) { + s = q.shift(); + s.onCompleted(); + } + n++; + if (n % skip === 0) { + createWindow(); + } + }, function (exception) { + while (q.length > 0) { + q.shift().onError(exception); + } + observer.onError(exception); + }, function () { + while (q.length > 0) { + q.shift().onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + function concatMap(source, selector, thisArg) { + return source.map(function (x, i) { + var result = selector.call(thisArg, x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).concatAll(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { + if (resultSelector) { + return this.concatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }); + } + return typeof selector === 'function' ? + concatMap(this, selector, thisArg) : + concatMap(this, function () { return selector; }); + }; + + /** + * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. + * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. + * @param {Function} onError A transform function to apply when an error occurs in the source sequence. + * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. + * @param {Any} [thisArg] An optional "this" to use to invoke each transform. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. + */ + observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + var result; + try { + result = onNext.call(thisArg, x, index++); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + }, + function (err) { + var result; + try { + result = onError.call(thisArg, err); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }, + function () { + var result; + try { + result = onCompleted.call(thisArg); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }); + }).concatAll(); + }; + /** + * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * var res = obs = xs.defaultIfEmpty(); + * 2 - obs = xs.defaultIfEmpty(false); + * + * @memberOf Observable# + * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. + * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. + */ + observableProto.defaultIfEmpty = function (defaultValue) { + var source = this; + if (defaultValue === undefined) { + defaultValue = null; + } + return new AnonymousObservable(function (observer) { + var found = false; + return source.subscribe(function (x) { + found = true; + observer.onNext(x); + }, observer.onError.bind(observer), function () { + if (!found) { + observer.onNext(defaultValue); + } + observer.onCompleted(); + }); + }); + }; + + // Swap out for Array.findIndex + function arrayIndexOfComparer(array, item, comparer) { + for (var i = 0, len = array.length; i < len; i++) { + if (comparer(array[i], item)) { return i; } + } + return -1; + } + + function HashSet(comparer) { + this.comparer = comparer; + this.set = []; + } + HashSet.prototype.push = function(value) { + var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; + retValue && this.set.push(value); + return retValue; + }; + + /** + * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. + * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. + * + * @example + * var res = obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [comparer] Used to compare items in the collection. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, comparer) { + var source = this; + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hashSet = new HashSet(comparer); + return source.subscribe(function (x) { + var key = x; + + if (keySelector) { + try { + key = keySelector(x); + } catch (e) { + observer.onError(e); + return; + } + } + hashSet.push(key) && observer.onNext(x); + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer)); + }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + observableProto.select = observableProto.map = function (selector, thisArg) { + var parent = this; + return new AnonymousObservable(function (observer) { + var count = 0; + return parent.subscribe(function (value) { + var result; + try { + result = selector.call(thisArg, value, count++, parent); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Retrieves the value of a specified property from all elements in the Observable sequence. + * @param {String} property The property to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function (property) { + return this.select(function (x) { return x[property]; }); + }; + + /** + * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. + * @param {Function} onError A transform function to apply when an error occurs in the source sequence. + * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. + * @param {Any} [thisArg] An optional "this" to use to invoke each transform. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. + */ + observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + var result; + try { + result = onNext.call(thisArg, x, index++); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + }, + function (err) { + var result; + try { + result = onError.call(thisArg, err); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }, + function () { + var result; + try { + result = onCompleted.call(thisArg); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }); + }).mergeAll(); + }; + function flatMap(source, selector, thisArg) { + return source.map(function (x, i) { + var result = selector.call(thisArg, x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).mergeObservable(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { + if (resultSelector) { + return this.flatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }, thisArg); + } + return typeof selector === 'function' ? + flatMap(this, selector, thisArg) : + flatMap(this, function () { return selector; }); + }; + + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { + throw new Error(argumentOutOfRange); + } + var observable = this; + return new AnonymousObservable(function (observer) { + var remaining = count; + return observable.subscribe(function (x) { + if (remaining <= 0) { + observer.onNext(x); + } else { + remaining--; + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + * The element's index is used in the logic of the predicate function. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !predicate.call(thisArg, x, i++, source); + } catch (e) { + observer.onError(e); + return; + } + } + if (running) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Utilities + if (!Function.prototype.bind) { + Function.prototype.bind = function (that) { + var target = this, + args = slice.call(arguments, 1); + var bound = function () { + if (this instanceof bound) { + function F() { } + F.prototype = target.prototype; + var self = new F(); + var result = target.apply(self, args.concat(slice.call(arguments))); + if (Object(result) === result) { + return result; + } + return self; + } else { + return target.apply(that, args.concat(slice.call(arguments))); + } + }; + + return bound; + }; + } + +if (!Array.prototype.forEach) { + + Array.prototype.forEach = function (callback, thisArg) { + var T, k; + + if (this == null) { + throw new TypeError(" this is null or not defined"); + } + + var O = Object(this); + var len = O.length >>> 0; + + if (typeof callback !== "function") { + throw new TypeError(callback + " is not a function"); + } + + if (arguments.length > 1) { + T = thisArg; + } + + k = 0; + while (k < len) { + var kValue; + if (k in O) { + kValue = O[k]; + callback.call(T, kValue, k, O); + } + k++; + } + }; +} + + var boxedString = Object("a"), + splitString = boxedString[0] != "a" || !(0 in boxedString); + if (!Array.prototype.every) { + Array.prototype.every = function every(fun /*, thisp */) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self && !fun.call(thisp, self[i], i, object)) { + return false; + } + } + return true; + }; + } + + if (!Array.prototype.map) { + Array.prototype.map = function map(fun /*, thisp*/) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + result = Array(length), + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self) { + result[i] = fun.call(thisp, self[i], i, object); + } + } + return result; + }; + } + + if (!Array.prototype.filter) { + Array.prototype.filter = function (predicate) { + var results = [], item, t = new Object(this); + for (var i = 0, len = t.length >>> 0; i < len; i++) { + item = t[i]; + if (i in t && predicate.call(arguments[1], item, i, t)) { + results.push(item); + } + } + return results; + }; + } + + if (!Array.isArray) { + Array.isArray = function (arg) { + return {}.toString.call(arg) == arrayClass; + }; + } + + if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function indexOf(searchElement) { + var t = Object(this); + var len = t.length >>> 0; + if (len === 0) { + return -1; + } + var n = 0; + if (arguments.length > 1) { + n = Number(arguments[1]); + if (n !== n) { + n = 0; + } else if (n !== 0 && n != Infinity && n !== -Infinity) { + n = (n > 0 || -1) * Math.floor(Math.abs(n)); + } + } + if (n >= len) { + return -1; + } + var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); + for (; k < len; k++) { + if (k in t && t[k] === searchElement) { + return k; + } + } + return -1; + }; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { + return; + } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { + return; + } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = + SerialDisposable = Rx.SerialDisposable = (function () { + function BooleanDisposable () { + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + old && old.dispose(); + shouldDispose && value && value.dispose(); + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + old && old.dispose(); + }; + + return BooleanDisposable; + }()); + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + timeSpan < 0 && (timeSpan = 0); + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + (function (schedulerProto) { + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function scheduleInnerRecursive(action, self) { + action(function(dt) { self(action, dt); }); + } + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { self(_action); }); }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + }(Scheduler.prototype)); + + (function (schedulerProto) { + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, action); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var s = state; + + var id = setInterval(function () { + s = action(s); + }, period); + + return disposableCreate(function () { + clearInterval(id); + }); + }; + }(Scheduler.prototype)); + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt); + + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + + currentScheduler.scheduleRequired = function () { return !queue; }; + currentScheduler.ensureTrampoline = function (action) { + if (!queue) { this.schedule(action); } else { action(); } + }; + + return currentScheduler; + }()); + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, + dt = Scheduler.normalize(dueTime); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { + return observerOrOnNext && typeof observerOrOnNext === 'object' ? + this._acceptObservable(observerOrOnNext) : + this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notifications + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + Notification.prototype.toObservable = function (scheduler) { + var notification = this; + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + notification.kind === 'N' && observer.onCompleted(); + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + + function _accept (onNext) { return onNext(this.value); } + function _acceptObservable(observer) { return observer.onNext(this.value); } + function toString () { return 'OnNext(' + this.value + ')'; } + + return function (value) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + + function _accept (onNext, onError) { return onError(this.exception); } + function _acceptObservable(observer) { return observer.onError(this.exception); } + function toString () { return 'OnError(' + this.exception + ')'; } + + return function (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { return onCompleted(); } + function _acceptObservable(observer) { return observer.onCompleted(); } + function toString () { return 'OnCompleted()'; } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber = typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted); + + return this._subscribe(subscriber); + }; + + return Observable; + })(); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { + inherits(ScheduledObserver, _super); + + function ScheduledObserver(scheduler, observer) { + _super.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + /** + * Creates a list from an observable sequence. + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + var self = this; + return new AnonymousObservable(function(observer) { + var arr = []; + return self.subscribe( + arr.push.bind(arr), + observer.onError.bind(observer), + function () { + observer.onNext(arr); + observer.onCompleted(); + }); + }); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.create = Observable.createWithDisposable = function (subscribe) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + var maxSafeInteger = Math.pow(2, 53) - 1; + + function numberIsFinite(value) { + return typeof value === 'number' && root.isFinite(value); + } + + function isNan(n) { + return n !== n; + } + + function isIterable(o) { + return o[$iterator$] !== undefined; + } + + function sign(value) { + var number = +value; + if (number === 0) { return number; } + if (isNaN(number)) { return number; } + return number < 0 ? -1 : 1; + } + + function toLength(o) { + var len = +o.length; + if (isNaN(len)) { return 0; } + if (len === 0 || !numberIsFinite(len)) { return len; } + len = sign(len) * Math.floor(Math.abs(len)); + if (len <= 0) { return 0; } + if (len > maxSafeInteger) { return maxSafeInteger; } + return len; + } + + function isCallable(f) { + return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; + } + + /** + * This method creates a new Observable sequence from an array-like or iterable object. + * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. + * @param {Function} [mapFn] Map function to call on every element of the array. + * @param {Any} [thisArg] The context to use calling the mapFn if provided. + * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + Observable.from = function (iterable, mapFn, thisArg, scheduler) { + if (iterable == null) { + throw new Error('iterable cannot be null.') + } + if (mapFn && !isCallable(mapFn)) { + throw new Error('mapFn when provided must be a function'); + } + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var list = Object(iterable), + objIsIterable = isIterable(list), + len = objIsIterable ? 0 : toLength(list), + it = objIsIterable ? list[$iterator$]() : null, + i = 0; + return scheduler.scheduleRecursive(function (self) { + if (i < len || objIsIterable) { + var result; + if (objIsIterable) { + var next = it.next(); + if (next.done) { + observer.onCompleted(); + return; + } + + result = next.value; + } else { + result = list[i]; + } + + if (mapFn && isCallable(mapFn)) { + try { + result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); + } catch (e) { + observer.onError(e); + return; + } + } + + observer.onNext(result); + i++; + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * var res = Rx.Observable.fromArray([1,2,3]); + * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0, len = array.length; + return scheduler.scheduleRecursive(function (self) { + if (count < len) { + observer.onNext(array[count++]); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). + * @returns {Observable} An observable sequence whose observers will never get called. + */ + var observableNever = Observable.never = function () { + return new AnonymousObservable(function () { + return disposableEmpty; + }); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.of = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return observableFromArray(args); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + var observableOf = Observable.ofWithScheduler = function (scheduler) { + var len = arguments.length - 1, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } + return observableFromArray(args, scheduler); + }; + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.range(0, 10); + * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleRecursiveWithState(0, function (i, self) { + if (i < count) { + observer.onNext(start + i); + self(i + 1); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.repeat(42); + * var res = Rx.Observable.repeat(42, 4); + * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'just', and 'returnValue' for browsers 0) { + subscribe(q.shift()); + } else { + activeCount--; + isStopped && activeCount === 0 && observer.onCompleted(); + } + })); + } + group.add(sources.subscribe(function (innerSource) { + if (activeCount < maxConcurrentOrOther) { + activeCount++; + subscribe(innerSource); + } else { + q.push(innerSource); + } + }, observer.onError.bind(observer), function () { + isStopped = true; + activeCount === 0 && observer.onCompleted(); + })); + return group; + }); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * + * @example + * 1 - merged = Rx.Observable.merge(xs, ys, zs); + * 2 - merged = Rx.Observable.merge([xs, ys, zs]); + * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); + * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources; + if (!arguments[0]) { + scheduler = immediateScheduler; + sources = slice.call(arguments, 1); + } else if (arguments[0].now) { + scheduler = arguments[0]; + sources = slice.call(arguments, 1); + } else { + scheduler = immediateScheduler; + sources = slice.call(arguments, 0); + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableFromArray(sources, scheduler).mergeObservable(); + }; + + /** + * Merges an observable sequence of observable sequences into an observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.mergeObservable = observableProto.mergeAll =function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + isStopped = false, + m = new SingleAssignmentDisposable(); + + group.add(m); + m.setDisposable(sources.subscribe(function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + innerSubscription.setDisposable(innerSource.subscribe(function (x) { + observer.onNext(x); + }, observer.onError.bind(observer), function () { + group.remove(innerSubscription); + if (isStopped && group.length === 1) { observer.onCompleted(); } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (group.length === 1) { observer.onCompleted(); } + })); + return group; + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + isOpen && observer.onNext(left); + }, observer.onError.bind(observer), function () { + isOpen && observer.onCompleted(); + })); + + isPromise(other) && (other = observableFromPromise(other)); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, observer.onError.bind(observer), function () { + rightSubscription.dispose(); + })); + + return disposables; + }); + }; + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasLatest = false, + innerSubscription = new SerialDisposable(), + isStopped = false, + latest = 0, + subscription = sources.subscribe(function (innerSource) { + var d = new SingleAssignmentDisposable(), id = ++latest; + hasLatest = true; + innerSubscription.setDisposable(d); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + d.setDisposable(innerSource.subscribe(function (x) { + if (latest === id) { + observer.onNext(x); + } + }, function (e) { + if (latest === id) { + observer.onError(e); + } + }, function () { + if (latest === id) { + hasLatest = false; + if (isStopped) { + observer.onCompleted(); + } + } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (!hasLatest) { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, innerSubscription); + }); + }; + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + isPromise(other) && (other = observableFromPromise(other)); + return new CompositeDisposable( + source.subscribe(observer), + other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) + ); + }); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], result; + try { + result = resultSelector(left, right); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + } else { + observer.onCompleted(); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. + * + * @example + * 1 - res = obs1.zip(obs2, fn); + * 1 - res = x1.zip([1,2,3], fn); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { + return zipArray.apply(this, arguments); + } + var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); + sources.unshift(parent); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + var res, queuedValues; + if (queues.every(function (x) { return x.length > 0; })) { + try { + queuedValues = queues.map(function (x) { return x.shift(); }); + res = resultSelector.apply(parent, queuedValues); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(function (x) { return x; })) { + observer.onCompleted(); + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = sources[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + * @param arguments Observable sources. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var args = slice.call(arguments, 0), + first = args.shift(); + return first.zip.apply(first, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + return; + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(identity)) { + observer.onCompleted(); + return; + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + })(idx); + } + + var compositeDisposable = new CompositeDisposable(subscriptions); + compositeDisposable.add(disposableCreate(function () { + for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { + queues[qIdx] = []; + } + })); + return compositeDisposable; + }); + }; + + /** + * Hides the identity of an observable sequence. + * @returns {Observable} An observable sequence that hides the identity of the source sequence. + */ + observableProto.asObservable = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(observer); + }); + }; + + /** + * Dematerializes the explicit notification values of an observable sequence as implicit notifications. + * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + return x.accept(observer); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + * + * var obs = observable.distinctUntilChanged(); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. + * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. + * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + observableProto.distinctUntilChanged = function (keySelector, comparer) { + var source = this; + keySelector || (keySelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var comparerEquals = false, key; + try { + key = keySelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + if (hasCurrentKey) { + try { + comparerEquals = comparer(currentKey, key); + } catch (exception) { + observer.onError(exception); + return; + } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + observer.onNext(value); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * + * @example + * var res = observable.do(observer); + * var res = observable.do(onNext); + * var res = observable.do(onNext, onError); + * var res = observable.do(onNext, onError, onCompleted); + * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { + var source = this, onNextFunc; + if (typeof observerOrOnNext === 'function') { + onNextFunc = observerOrOnNext; + } else { + onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); + onError = observerOrOnNext.onError.bind(observerOrOnNext); + onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); + } + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + try { + onNextFunc(x); + } catch (e) { + observer.onError(e); + } + observer.onNext(x); + }, function (err) { + if (!onError) { + observer.onError(err); + } else { + try { + onError(err); + } catch (e) { + observer.onError(e); + } + observer.onError(err); + } + }, function () { + if (!onCompleted) { + observer.onCompleted(); + } else { + try { + onCompleted(); + } catch (e) { + observer.onError(e); + } + observer.onCompleted(); + } + }); + }); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * + * @example + * var res = observable.finallyAction(function () { console.log('sequence ended'; }); + * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. + * @returns {Observable} Source sequence with the action-invoking termination behavior applied. + */ + observableProto['finally'] = observableProto.finallyAction = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription; + try { + subscription = source.subscribe(observer); + } catch (e) { + action(); + throw e; + } + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Materializes the implicit notifications of an observable sequence as explicit notification values. + * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. + */ + observableProto.materialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (value) { + observer.onNext(notificationCreateOnNext(value)); + }, function (e) { + observer.onNext(notificationCreateOnError(e)); + observer.onCompleted(); + }, function () { + observer.onNext(notificationCreateOnCompleted()); + observer.onCompleted(); + }); + }); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * + * @example + * var res = repeated = source.repeat(); + * var res = repeated = source.repeat(42); + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + observableProto.repeat = function (repeatCount) { + return enumerableRepeat(this, repeatCount).concat(); + }; + + /** + * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. + * Note if you encounter an error and want it to retry once, then you must use .retry(2); + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(2); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchException(); + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @example + * var res = source.scan(function (acc, x) { return acc + x; }); + * var res = source.scan(0, function (acc, x) { return acc + x; }); + * @param {Mixed} [seed] The initial accumulator value. + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @returns {Observable} An observable sequence containing the accumulated values. + */ + observableProto.scan = function () { + var hasSeed = false, seed, accumulator, source = this; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[0]; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return new AnonymousObservable(function (observer) { + var hasAccumulation, accumulation, hasValue; + return source.subscribe ( + function (x) { + try { + if (!hasValue) { + hasValue = true; + } + + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(accumulation); + }, + observer.onError.bind(observer), + function () { + if (!hasValue && hasSeed) { + observer.onNext(seed); + } + observer.onCompleted(); + } + ); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + observer.onNext(q.shift()); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * + * @memberOf Observable# + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && 'now' in Object(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + values = slice.call(arguments, start); + return enumerableFor([observableFromArray(values, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence. + * + * @example + * var res = source.takeLast(5); + * + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, observer.onError.bind(observer), function () { + while(q.length > 0) { observer.onNext(q.shift()); } + observer.onCompleted(); + }); + }); + }; + + function concatMap(source, selector, thisArg) { + return source.map(function (x, i) { + var result = selector.call(thisArg, x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).concatAll(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { + if (resultSelector) { + return this.concatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }); + } + return typeof selector === 'function' ? + concatMap(this, selector, thisArg) : + concatMap(this, function () { return selector; }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + observableProto.select = observableProto.map = function (selector, thisArg) { + var parent = this; + return new AnonymousObservable(function (observer) { + var count = 0; + return parent.subscribe(function (value) { + var result; + try { + result = selector.call(thisArg, value, count++, parent); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Retrieves the value of a specified property from all elements in the Observable sequence. + * @param {String} property The property to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function (property) { + return this.select(function (x) { return x[property]; }); + }; + + function flatMap(source, selector, thisArg) { + return source.map(function (x, i) { + var result = selector.call(thisArg, x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).mergeObservable(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { + if (resultSelector) { + return this.flatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }, thisArg); + } + return typeof selector === 'function' ? + flatMap(this, selector, thisArg) : + flatMap(this, function () { return selector; }); + }; + + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { + throw new Error(argumentOutOfRange); + } + var observable = this; + return new AnonymousObservable(function (observer) { + var remaining = count; + return observable.subscribe(function (x) { + if (remaining <= 0) { + observer.onNext(x); + } else { + remaining--; + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + * The element's index is used in the logic of the predicate function. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !predicate.call(thisArg, x, i++, source); + } catch (e) { + observer.onError(e); + return; + } + } + if (running) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case 0) { + var now = scheduler.now(); + d = d + p; + d <= now && (d = now + p); + } + observer.onNext(count++); + self(d); + }); + }); + } + + function observableTimerTimeSpan(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { + return dueTime === period ? + new AnonymousObservable(function (observer) { + return scheduler.schedulePeriodicWithState(0, period, function (count) { + observer.onNext(count); + return count + 1; + }); + }) : + observableDefer(function () { + return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); + }); + } + + /** + * Returns an observable sequence that produces a value after each period. + * + * @example + * 1 - res = Rx.Observable.interval(1000); + * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); + * + * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. + * @returns {Observable} An observable sequence that produces a value after each period. + */ + var observableinterval = Observable.interval = function (period, scheduler) { + return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); + }; + + /** + * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. + * + * @example + * 1 - res = Rx.Observable.timer(new Date()); + * 2 - res = Rx.Observable.timer(new Date(), 1000); + * 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout); + * + * 5 - res = Rx.Observable.timer(5000); + * 6 - res = Rx.Observable.timer(5000, 1000); + * 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); + * 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. + * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. + */ + var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { + var period; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { + period = periodOrScheduler; + } else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') { + scheduler = periodOrScheduler; + } + if (dueTime instanceof Date && period === undefined) { + return observableTimerDate(dueTime.getTime(), scheduler); + } + if (dueTime instanceof Date && period !== undefined) { + period = periodOrScheduler; + return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); + } + return period === undefined ? + observableTimerTimeSpan(dueTime, scheduler) : + observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); + }; + + function observableDelayTimeSpan(source, dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + var active = false, + cancelable = new SerialDisposable(), + exception = null, + q = [], + running = false, + subscription; + subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { + var d, shouldRun; + if (notification.value.kind === 'E') { + q = []; + q.push(notification); + exception = notification.value.exception; + shouldRun = !running; + } else { + q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); + shouldRun = !active; + active = true; + } + if (shouldRun) { + if (exception !== null) { + observer.onError(exception); + } else { + d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { + var e, recurseDueTime, result, shouldRecurse; + if (exception !== null) { + return; + } + running = true; + do { + result = null; + if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { + result = q.shift().value; + } + if (result !== null) { + result.accept(observer); + } + } while (result !== null); + shouldRecurse = false; + recurseDueTime = 0; + if (q.length > 0) { + shouldRecurse = true; + recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); + } else { + active = false; + } + e = exception; + running = false; + if (e !== null) { + observer.onError(e); + } else if (shouldRecurse) { + self(recurseDueTime); + } + })); + } + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + } + + function observableDelayDate(source, dueTime, scheduler) { + return observableDefer(function () { + return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); + }); + } + + /** + * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. + * + * @example + * 1 - res = Rx.Observable.delay(new Date()); + * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); + * + * 3 - res = Rx.Observable.delay(5000); + * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); + * @memberOf Observable# + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. + * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delay = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return dueTime instanceof Date ? + observableDelayDate(this, dueTime.getTime(), scheduler) : + observableDelayTimeSpan(this, dueTime, scheduler); + }; + + /** + * Ignores values from an observable sequence which are followed by another value before dueTime. + * + * @example + * 1 - res = source.throttle(5000); // 5 seconds + * 2 - res = source.throttle(5000, scheduler); + * + * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttle = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) + }; + + /** + * Records the timestamp for each value in an observable sequence. + * + * @example + * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } + * 2 - res = source.timestamp(Rx.Scheduler.timeout); + * + * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with timestamp information on values. + */ + observableProto.timestamp = function (scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return this.map(function (x) { + return { value: x, timestamp: scheduler.now() }; + }); + }; + + function sampleObservable(source, sampler) { + + return new AnonymousObservable(function (observer) { + var atEnd, value, hasValue; + + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + observer.onNext(value); + } + atEnd && observer.onCompleted(); + } + + return new CompositeDisposable( + source.subscribe(function (newValue) { + hasValue = true; + value = newValue; + }, observer.onError.bind(observer), function () { + atEnd = true; + }), + sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) + ); + }); + } + + /** + * Samples the observable sequence at each interval. + * + * @example + * 1 - res = source.sample(sampleObservable); // Sampler tick sequence + * 2 - res = source.sample(5000); // 5 seconds + * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. + * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Sampled observable sequence. + */ + observableProto.sample = function (intervalOrSampler, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return typeof intervalOrSampler === 'number' ? + sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : + sampleObservable(this, intervalOrSampler); + }; + + /** + * Returns the source observable sequence or the other observable sequence if dueTime elapses. + * + * @example + * 1 - res = source.timeout(new Date()); // As a date + * 2 - res = source.timeout(5000); // 5 seconds + * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable + * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable + * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable + * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. + * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. + * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeout = function (dueTime, other, scheduler) { + other || (other = observableThrow(new Error('Timeout'))); + isScheduler(scheduler) || (scheduler = timeoutScheduler); + + var source = this, schedulerMethod = dueTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + + return new AnonymousObservable(function (observer) { + var id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + + subscription.setDisposable(original); + + var createTimer = function () { + var myId = id; + timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { + if (id === myId) { + isPromise(other) && (other = observableFromPromise(other)); + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + createTimer(); + + original.setDisposable(source.subscribe(function (x) { + if (!switched) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + if (!switched) { + id++; + observer.onError(e); + } + }, function () { + if (!switched) { + id++; + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Time shifts the observable sequence by delaying the subscription. + * + * @example + * 1 - res = source.delaySubscription(5000); // 5s + * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Number} dueTime Absolute or relative time to perform the subscription at. + * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delaySubscription = function (dueTime, scheduler) { + return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty); + }; + + /** + * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only + * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector + * + * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. + * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { + var source = this, subDelay, selector; + if (typeof subscriptionDelay === 'function') { + selector = subscriptionDelay; + } else { + subDelay = subscriptionDelay; + selector = delayDurationSelector; + } + return new AnonymousObservable(function (observer) { + var delays = new CompositeDisposable(), atEnd = false, done = function () { + if (atEnd && delays.length === 0) { + observer.onCompleted(); + } + }, subscription = new SerialDisposable(), start = function () { + subscription.setDisposable(source.subscribe(function (x) { + var delay; + try { + delay = selector(x); + } catch (error) { + observer.onError(error); + return; + } + var d = new SingleAssignmentDisposable(); + delays.add(d); + d.setDisposable(delay.subscribe(function () { + observer.onNext(x); + delays.remove(d); + done(); + }, observer.onError.bind(observer), function () { + observer.onNext(x); + delays.remove(d); + done(); + })); + }, observer.onError.bind(observer), function () { + atEnd = true; + subscription.dispose(); + done(); + })); + }; + + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(function () { + start(); + }, observer.onError.bind(observer), function () { start(); })); + } + + return new CompositeDisposable(subscription, delays); + }); + }; + + /** + * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. + * + * @example + * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); + * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); + * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); + * + * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). + * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. + * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { + if (arguments.length === 1) { + timeoutdurationSelector = firstTimeout; + var firstTimeout = observableNever(); + } + other || (other = observableThrow(new Error('Timeout'))); + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); + + subscription.setDisposable(original); + + var id = 0, switched = false, setTimer = function (timeout) { + var myId = id, timerWins = function () { + return id === myId; + }; + var d = new SingleAssignmentDisposable(); + timer.setDisposable(d); + d.setDisposable(timeout.subscribe(function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + d.dispose(); + }, function (e) { + if (timerWins()) { + observer.onError(e); + } + }, function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + setTimer(firstTimeout); + var observerWins = function () { + var res = !switched; + if (res) { + id++; + } + return res; + }; + + original.setDisposable(source.subscribe(function (x) { + if (observerWins()) { + observer.onNext(x); + var timeout; + try { + timeout = timeoutdurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + setTimer(timeout); + } + }, function (e) { + if (observerWins()) { + observer.onError(e); + } + }, function () { + if (observerWins()) { + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); + * + * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttleWithSelector = function (throttleDurationSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { + var throttle; + try { + throttle = throttleDurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + hasValue = true; + value = x; + id++; + var currentid = id, d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(throttle.subscribe(function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + }, observer.onError.bind(observer), function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + })); + }, function (e) { + cancelable.dispose(); + observer.onError(e); + hasValue = false; + id++; + }, function () { + cancelable.dispose(); + if (hasValue) { + observer.onNext(value); + } + observer.onCompleted(); + hasValue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * 1 - res = source.skipLastWithTime(5000); + * 2 - res = source.skipLastWithTime(5000, scheduler); + * + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for skipping elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. + */ + observableProto.skipLastWithTime = function (duration, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. + * + * @example + * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var q = []; + + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { + observer.onNext(next.value); + } + } + + observer.onCompleted(); + }); + }); + }; + + /** + * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + observableProto.takeWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), source.subscribe(observer)); + }); + }; + + /** + * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.skipWithTime(5000, [optional scheduler]); + * + * @description + * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. + * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded + * may not execute immediately, despite the zero due time. + * + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. + * @param {Number} duration Duration for skipping elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + observableProto.skipWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false; + return new CompositeDisposable( + scheduler.scheduleWithRelative(duration, function () { open = true; }), + source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); + }); + }; + + var PausableObservable = (function (_super) { + + inherits(PausableObservable, _super); + + function subscribe(observer) { + var conn = this.source.publish(), + subscription = conn.subscribe(observer), + connection = disposableEmpty; + + var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { + if (b) { + connection = conn.connect(); + } else { + connection.dispose(); + connection = disposableEmpty; + } + }); + + return new CompositeDisposable(subscription, connection, pausable); + } + + function PausableObservable(source, pauser) { + this.source = source; + this.controller = new Subject(); + + if (pauser && pauser.subscribe) { + this.pauser = this.controller.merge(pauser); + } else { + this.pauser = this.controller; + } + + _super.call(this, subscribe); + } + + PausableObservable.prototype.pause = function () { + this.controller.onNext(false); + }; + + PausableObservable.prototype.resume = function () { + this.controller.onNext(true); + }; + + return PausableObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausable(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausable = function (pauser) { + return new PausableObservable(this, pauser); + }; + function combineLatestSource(source, subject, resultSelector) { + return new AnonymousObservable(function (observer) { + var n = 2, + hasValue = [false, false], + hasValueAll = false, + isDone = false, + values = new Array(n); + + function next(x, i) { + values[i] = x + var res; + hasValue[i] = true; + if (hasValueAll || (hasValueAll = hasValue.every(identity))) { + try { + res = resultSelector.apply(null, values); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe( + function (x) { + next(x, 0); + }, + observer.onError.bind(observer), + function () { + isDone = true; + observer.onCompleted(); + }), + subject.subscribe( + function (x) { + next(x, 1); + }, + observer.onError.bind(observer)) + ); + }); + } + + var PausableBufferedObservable = (function (_super) { + + inherits(PausableBufferedObservable, _super); + + function subscribe(observer) { + var q = [], previousShouldFire; + + var subscription = + combineLatestSource( + this.source, + this.pauser.distinctUntilChanged().startWith(false), + function (data, shouldFire) { + return { data: data, shouldFire: shouldFire }; + }) + .subscribe( + function (results) { + if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { + // change in shouldFire + if (results.shouldFire) { + while (q.length > 0) { + observer.onNext(q.shift()); + } + } + } else { + // new data + if (results.shouldFire) { + observer.onNext(results.data); + } else { + q.push(results.data); + } + } + previousShouldFire = results.shouldFire; + + }, + function (err) { + // Empty buffer before sending error + while (q.length > 0) { + observer.onNext(q.shift()); + } + observer.onError(err); + }, + function () { + // Empty buffer before sending completion + while (q.length > 0) { + observer.onNext(q.shift()); + } + observer.onCompleted(); + } + ); + return subscription; + } + + function PausableBufferedObservable(source, pauser) { + this.source = source; + this.controller = new Subject(); + + if (pauser && pauser.subscribe) { + this.pauser = this.controller.merge(pauser); + } else { + this.pauser = this.controller; + } + + _super.call(this, subscribe); + } + + PausableBufferedObservable.prototype.pause = function () { + this.controller.onNext(false); + }; + + PausableBufferedObservable.prototype.resume = function () { + this.controller.onNext(true); + }; + + return PausableBufferedObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, + * and yields the values that were buffered while paused. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausableBuffered(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausableBuffered = function (subject) { + return new PausableBufferedObservable(this, subject); + }; + + /** + * Attaches a controller to the observable sequence with the ability to queue. + * @example + * var source = Rx.Observable.interval(100).controlled(); + * source.request(3); // Reads 3 values + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.controlled = function (enableQueue) { + if (enableQueue == null) { enableQueue = true; } + return new ControlledObservable(this, enableQueue); + }; + var ControlledObservable = (function (_super) { + + inherits(ControlledObservable, _super); + + function subscribe (observer) { + return this.source.subscribe(observer); + } + + function ControlledObservable (source, enableQueue) { + _super.call(this, subscribe); + this.subject = new ControlledSubject(enableQueue); + this.source = source.multicast(this.subject).refCount(); + } + + ControlledObservable.prototype.request = function (numberOfItems) { + if (numberOfItems == null) { numberOfItems = -1; } + return this.subject.request(numberOfItems); + }; + + return ControlledObservable; + + }(Observable)); + + var ControlledSubject = Rx.ControlledSubject = (function (_super) { + + function subscribe (observer) { + return this.subject.subscribe(observer); + } + + inherits(ControlledSubject, _super); + + function ControlledSubject(enableQueue) { + if (enableQueue == null) { + enableQueue = true; + } + + _super.call(this, subscribe); + this.subject = new Subject(); + this.enableQueue = enableQueue; + this.queue = enableQueue ? [] : null; + this.requestedCount = 0; + this.requestedDisposable = disposableEmpty; + this.error = null; + this.hasFailed = false; + this.hasCompleted = false; + this.controlledDisposable = disposableEmpty; + } + + addProperties(ControlledSubject.prototype, Observer, { + onCompleted: function () { + checkDisposed.call(this); + this.hasCompleted = true; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onCompleted(); + } + }, + onError: function (error) { + checkDisposed.call(this); + this.hasFailed = true; + this.error = error; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onError(error); + } + }, + onNext: function (value) { + checkDisposed.call(this); + var hasRequested = false; + + if (this.requestedCount === 0) { + if (this.enableQueue) { + this.queue.push(value); + } + } else { + if (this.requestedCount !== -1) { + if (this.requestedCount-- === 0) { + this.disposeCurrentRequest(); + } + } + hasRequested = true; + } + + if (hasRequested) { + this.subject.onNext(value); + } + }, + _processRequest: function (numberOfItems) { + if (this.enableQueue) { + //console.log('queue length', this.queue.length); + + while (this.queue.length >= numberOfItems && numberOfItems > 0) { + //console.log('number of items', numberOfItems); + this.subject.onNext(this.queue.shift()); + numberOfItems--; + } + + if (this.queue.length !== 0) { + return { numberOfItems: numberOfItems, returnValue: true }; + } else { + return { numberOfItems: numberOfItems, returnValue: false }; + } + } + + if (this.hasFailed) { + this.subject.onError(this.error); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } else if (this.hasCompleted) { + this.subject.onCompleted(); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } + + return { numberOfItems: numberOfItems, returnValue: false }; + }, + request: function (number) { + checkDisposed.call(this); + this.disposeCurrentRequest(); + var self = this, + r = this._processRequest(number); + + number = r.numberOfItems; + if (!r.returnValue) { + this.requestedCount = number; + this.requestedDisposable = disposableCreate(function () { + self.requestedCount = 0; + }); + + return this.requestedDisposable + } else { + return disposableEmpty; + } + }, + disposeCurrentRequest: function () { + this.requestedDisposable.dispose(); + this.requestedDisposable = disposableEmpty; + }, + + dispose: function () { + this.isDisposed = true; + this.error = null; + this.subject.dispose(); + this.requestedDisposable.dispose(); + } + }); + + return ControlledSubject; + }(Observable)); + /* + * Performs a exclusive waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @returns {Observable} A exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusive = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasCurrent = false, + isStopped = false, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + if (!hasCurrent) { + hasCurrent = true; + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + var innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + innerSubscription.setDisposable(innerSource.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (!hasCurrent && g.length === 1) { + observer.onCompleted(); + } + })); + + return g; + }); + }; + /* + * Performs a exclusive map waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @param {Function} selector Selector to invoke for every item in the current subscription. + * @param {Any} [thisArg] An optional context to invoke with the selector parameter. + * @returns {Observable} An exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusiveMap = function (selector, thisArg) { + var sources = this; + return new AnonymousObservable(function (observer) { + var index = 0, + hasCurrent = false, + isStopped = true, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + + if (!hasCurrent) { + hasCurrent = true; + + innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + innerSubscription.setDisposable(innerSource.subscribe( + function (x) { + var result; + try { + result = selector.call(thisArg, x, index++, innerSource); + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(result); + }, + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (g.length === 1 && !hasCurrent) { + observer.onCompleted(); + } + })); + return g; + }); + }; + var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { + inherits(AnonymousObservable, __super__); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } + + return typeof subscriber === 'function' ? + disposableCreate(subscriber) : + disposableEmpty; + } + + function AnonymousObservable(subscribe) { + if (!(this instanceof AnonymousObservable)) { + return new AnonymousObservable(subscribe); + } + + function s(observer) { + var setDisposable = function () { + try { + autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); + } catch (e) { + if (!autoDetachObserver.fail(e)) { + throw e; + } + } + }; + + var autoDetachObserver = new AutoDetachObserver(observer); + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.schedule(setDisposable); + } else { + setDisposable(); + } + + return autoDetachObserver; + } + + __super__.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + /** @private */ + var AutoDetachObserver = (function (_super) { + inherits(AutoDetachObserver, _super); + + function AutoDetachObserver(observer) { + _super.call(this); + this.observer = observer; + this.m = new SingleAssignmentDisposable(); + } + + var AutoDetachObserverPrototype = AutoDetachObserver.prototype; + + AutoDetachObserverPrototype.next = function (value) { + var noError = false; + try { + this.observer.onNext(value); + noError = true; + } catch (e) { + throw e; + } finally { + if (!noError) { + this.dispose(); + } + } + }; + + AutoDetachObserverPrototype.error = function (exn) { + try { + this.observer.onError(exn); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.completed = function () { + try { + this.observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; + /* @private */ + AutoDetachObserverPrototype.disposable = function (value) { + return arguments.length ? this.getDisposable() : setDisposable(value); + }; + + AutoDetachObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + /** @private */ + var InnerSubscription = function (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + /** + * @private + * @memberOf InnerSubscription + */ + InnerSubscription.prototype.dispose = function () { + if (!this.subject.isDisposed && this.observer !== null) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + this.observer = null; + } + }; + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.exception) { + observer.onError(this.exception); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, _super); + + /** + * Creates a subject. + * @constructor + */ + function Subject() { + _super.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + } + + addProperties(Subject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (__super__) { + + function subscribe(observer) { + checkDisposed.call(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + var ex = this.exception, + hv = this.hasValue, + v = this.value; + + if (ex) { + observer.onError(ex); + } else if (hv) { + observer.onNext(v); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, __super__); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + __super__.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.value = null; + this.hasValue = false; + this.observers = []; + this.exception = null; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed.call(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var o, i, len; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var os = this.observers.slice(0), + v = this.value, + hv = this.hasValue; + + if (hv) { + for (i = 0, len = os.length; i < len; i++) { + o = os[i]; + o.onNext(v); + o.onCompleted(); + } + } else { + for (i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the error. + * @param {Mixed} error The Error to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed.call(this); + if (this.isStopped) { return; } + this.value = value; + this.hasValue = true; + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { + inherits(AnonymousSubject, __super__); + + function AnonymousSubject(observer, observable) { + this.observer = observer; + this.observable = observable; + __super__.call(this, this.observable.subscribe.bind(this.observable)); + } + + addProperties(AnonymousSubject.prototype, Observer, { + onCompleted: function () { + this.observer.onCompleted(); + }, + onError: function (exception) { + this.observer.onError(exception); + }, + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + /** + * Represents a value that changes over time. + * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. + */ + var BehaviorSubject = Rx.BehaviorSubject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + observer.onNext(this.value); + return new InnerSubscription(this, observer); + } + var ex = this.exception; + if (ex) { + observer.onError(ex); + } else { + observer.onCompleted(); + } + return disposableEmpty; + } + + inherits(BehaviorSubject, _super); + + /** + * @constructor + * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. + * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. + */ + function BehaviorSubject(value) { + _super.call(this, subscribe); + + this.value = value, + this.observers = [], + this.isDisposed = false, + this.isStopped = false, + this.exception = null; + } + + addProperties(BehaviorSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.exception = null; + } + }); + + return BehaviorSubject; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. + */ + var ReplaySubject = Rx.ReplaySubject = (function (_super) { + + function RemovableDisposable (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + RemovableDisposable.prototype.dispose = function () { + this.observer.dispose(); + if (!this.subject.isDisposed) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + } + }; + + function subscribe(observer) { + var so = new ScheduledObserver(this.scheduler, observer), + subscription = new RemovableDisposable(this, so); + checkDisposed.call(this); + this._trim(this.scheduler.now()); + this.observers.push(so); + + var n = this.q.length; + + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } + + if (this.hasError) { + n++; + so.onError(this.error); + } else if (this.isStopped) { + n++; + so.onCompleted(); + } + + so.ensureActive(n); + return subscription; + } + + inherits(ReplaySubject, _super); + + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; + this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + _super.call(this, subscribe); + } + + addProperties(ReplaySubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /* @private */ + _trim: function (now) { + while (this.q.length > this.bufferSize) { + this.q.shift(); + } + while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { + this.q.shift(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); + + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onNext(value); + observer.ensureActive(); + } + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } +}.call(this)); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.lite.compat.min.js b/ajax/libs/rxjs/2.3.9/rx.lite.compat.min.js new file mode 100644 index 000000000..dd1ba3317 --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.lite.compat.min.js @@ -0,0 +1,2 @@ +(function(a){function b(){if(this.isDisposed)throw new Error(W)}function c(a){var b=typeof a;return a&&("function"==b||"object"==b)||!1}function d(a){var b=[];if(!c(a))return b;rb.nonEnumArgs&&a.length&&h(a)&&(a=tb.call(a));var d=rb.enumPrototypes&&"function"==typeof a,e=rb.enumErrorProps&&(a===lb||a instanceof Error);for(var f in a)d&&"prototype"==f||e&&("message"==f||"name"==f)||b.push(f);if(rb.nonEnumShadows&&a!==mb){var g=a.constructor,i=-1,j=pb.length;if(a===(g&&g.prototype))var k=a===stringProto?hb:a===lb?cb:ib.call(a),l=qb[k];for(;++i-1:void 0});return c.pop(),d.pop(),result}function k(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:tb.call(a)}function l(a,b){for(var c=new Array(a),d=0;a>d;d++)c[d]=b();return c}function m(a){return"number"==typeof a&&H.isFinite(a)}function n(b){return b[X]!==a}function o(a){var b=+a;return 0===b?b:isNaN(b)?b:0>b?-1:1}function p(a){var b=+a.length;return isNaN(b)?0:0!==b&&m(b)?(b=o(b)*Math.floor(Math.abs(b)),0>=b?0:b>ec?ec:b):b}function q(a){return"[object Function]"===Object.prototype.toString.call(a)&&"function"==typeof a}function r(a,b){return new zc(function(c){var d=new Gb,e=new SerialDisposable;return e.setDisposable(d),d.setDisposable(a.subscribe(c.onNext.bind(c),function(a){var d,f;try{f=b(a)}catch(g){return void c.onError(g)}U(f)&&(f=rc(f)),d=new Gb,e.setDisposable(d),d.setDisposable(f.subscribe(c))},c.onCompleted.bind(c))),e})}function s(a,b){var c=this;return new zc(function(d){var e=0,f=a.length;return c.subscribe(function(c){if(f>e){var g,h=a[e++];try{g=b(c,h)}catch(i){return void d.onError(i)}d.onNext(g)}else d.onCompleted()},d.onError.bind(d),d.onCompleted.bind(d))})}function t(a,b,c){return a.map(function(a,d){var e=b.call(c,a,d);return U(e)?rc(e):e}).concatAll()}function u(a,b,c){return a.map(function(a,d){var e=b.call(c,a,d);return U(e)?rc(e):e}).mergeObservable()}function v(a){var b=function(){this.cancelBubble=!0},c=function(){if(this.bubbledKeyCode=this.keyCode,this.ctrlKey)try{this.keyCode=0}catch(a){}this.defaultPrevented=!0,this.returnValue=!1,this.modified=!0};if(a||(a=H.event),!a.target)switch(a.target=a.target||a.srcElement,"mouseover"==a.type&&(a.relatedTarget=a.fromElement),"mouseout"==a.type&&(a.relatedTarget=a.toElement),a.stopPropagation||(a.stopPropagation=b,a.preventDefault=c),a.type){case"keypress":var d="charCode"in a?a.charCode:a.keyCode;10==d?(d=0,a.keyCode=13):13==d||27==d?d=0:3==d&&(d=99),a.charCode=d,a.keyChar=a.charCode?String.fromCharCode(a.charCode):""}return a}function w(a,b,c){if(a.addEventListener)return a.addEventListener(b,c,!1),Eb(function(){a.removeEventListener(b,c,!1)});if(a.attachEvent){var d=function(a){c(v(a))};return a.attachEvent("on"+b,d),Eb(function(){a.detachEvent("on"+b,d)})}return a["on"+b]=c,Eb(function(){a["on"+b]=null})}function x(a,b,c){var d=new Bb;if("[object NodeList]"===Object.prototype.toString.call(a))for(var e=0,f=a.length;f>e;e++)d.add(x(a.item(e),b,c));else a&&d.add(w(a,b,c));return d}function y(a,b){return new zc(function(c){return b.scheduleWithAbsolute(a,function(){c.onNext(0),c.onCompleted()})})}function z(a,b,c){return new zc(function(d){var e=0,f=a,g=Jb(b);return c.scheduleRecursiveWithAbsolute(f,function(a){if(g>0){var b=c.now();f+=g,b>=f&&(f=b+g)}d.onNext(e++),a(f)})})}function A(a,b){return new zc(function(c){return b.scheduleWithRelative(Jb(a),function(){c.onNext(0),c.onCompleted()})})}function B(a,b,c){return a===b?new zc(function(a){return c.schedulePeriodicWithState(0,b,function(b){return a.onNext(b),b+1})}):cc(function(){return z(c.now()+a,b,c)})}function C(a,b,c){return new zc(function(d){var e,f=!1,g=new SerialDisposable,h=null,i=[],j=!1;return e=a.materialize().timestamp(c).subscribe(function(a){var e,k;"E"===a.value.kind?(i=[],i.push(a),h=a.value.exception,k=!j):(i.push({value:a.value,timestamp:a.timestamp+b}),k=!f,f=!0),k&&(null!==h?d.onError(h):(e=new Gb,g.setDisposable(e),e.setDisposable(c.scheduleRecursiveWithRelative(b,function(a){var b,e,g,k;if(null===h){j=!0;do g=null,i.length>0&&i[0].timestamp-c.now()<=0&&(g=i.shift().value),null!==g&&g.accept(d);while(null!==g);k=!1,e=0,i.length>0?(k=!0,e=Math.max(0,i[0].timestamp-c.now())):f=!1,b=h,j=!1,null!==b?d.onError(b):k&&a(e)}}))))}),new Bb(e,g)})}function D(a,b,c){return cc(function(){return C(a,b-c.now(),c)})}function E(a,b){return new zc(function(c){function d(){g&&(g=!1,c.onNext(f)),e&&c.onCompleted()}var e,f,g;return new Bb(a.subscribe(function(a){g=!0,f=a},c.onError.bind(c),function(){e=!0}),b.subscribe(d,c.onError.bind(c),d))})}function F(a,b,c){return new zc(function(d){function e(a,b){j[b]=a;var e;if(g[b]=!0,h||(h=g.every(P))){try{e=c.apply(null,j)}catch(f){return void d.onError(f)}d.onNext(e)}else i&&d.onCompleted()}var f=2,g=[!1,!1],h=!1,i=!1,j=new Array(f);return new Bb(a.subscribe(function(a){e(a,0)},d.onError.bind(d),function(){i=!0,d.onCompleted()}),b.subscribe(function(a){e(a,1)},d.onError.bind(d)))})}var G={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},H=G[typeof window]&&window||this,I=G[typeof exports]&&exports&&!exports.nodeType&&exports,J=G[typeof module]&&module&&!module.nodeType&&module,K=J&&J.exports===I&&I,L=G[typeof global]&&global;!L||L.global!==L&&L.window!==L||(H=L);var M={internals:{},config:{Promise:H.Promise},helpers:{}},N=M.helpers.noop=function(){},O=(M.helpers.notDefined=function(a){return"undefined"==typeof a},M.helpers.isScheduler=function(a){return a instanceof M.Scheduler}),P=M.helpers.identity=function(a){return a},Q=(M.helpers.pluck=function(a){return function(b){return b[a]}},M.helpers.just=function(a){return function(){return a}},M.helpers.defaultNow=function(){return Date.now?Date.now:function(){return+new Date}}()),R=M.helpers.defaultComparer=function(a,b){return sb(a,b)},S=M.helpers.defaultSubComparer=function(a,b){return a>b?1:b>a?-1:0},T=(M.helpers.defaultKeySerializer=function(a){return a.toString()},M.helpers.defaultError=function(a){throw a}),U=M.helpers.isPromise=function(a){return!!a&&"function"==typeof a.then},V=(M.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},M.helpers.not=function(a){return!a},"Argument out of range"),W="Object has been disposed",X="function"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";H.Set&&"function"==typeof(new H.Set)["@@iterator"]&&(X="@@iterator");var Y,Z={done:!0,value:a},$="[object Arguments]",_="[object Array]",ab="[object Boolean]",bb="[object Date]",cb="[object Error]",db="[object Function]",eb="[object Number]",fb="[object Object]",gb="[object RegExp]",hb="[object String]",ib=Object.prototype.toString,jb=Object.prototype.hasOwnProperty,kb=ib.call(arguments)==$,lb=Error.prototype,mb=Object.prototype,nb=mb.propertyIsEnumerable;try{Y=!(ib.call(document)==fb&&!({toString:0}+""))}catch(ob){Y=!0}var pb=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],qb={};qb[_]=qb[bb]=qb[eb]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},qb[ab]=qb[hb]={constructor:!0,toString:!0,valueOf:!0},qb[cb]=qb[db]=qb[gb]={constructor:!0,toString:!0},qb[fb]={constructor:!0};var rb={};!function(){var a=function(){this.x=1},b=[];a.prototype={valueOf:1,y:1};for(var c in new a)b.push(c);for(c in arguments);rb.enumErrorProps=nb.call(lb,"message")||nb.call(lb,"name"),rb.enumPrototypes=nb.call(a,"prototype"),rb.nonEnumArgs=0!=c,rb.nonEnumShadows=!/valueOf/.test(b)}(1),kb||(h=function(a){return a&&"object"==typeof a?jb.call(a,"callee"):!1}),i(/x/)&&(i=function(a){return"function"==typeof a&&ib.call(a)==db});{var sb=M.internals.isEqual=function(a,b){return j(a,b,[],[])},tb=Array.prototype.slice,ub=({}.hasOwnProperty,this.inherits=M.internals.inherits=function(a,b){function c(){this.constructor=a}c.prototype=b.prototype,a.prototype=new c}),vb=M.internals.addProperties=function(a){for(var b=tb.call(arguments,1),c=0,d=b.length;d>c;c++){var e=b[c];for(var f in e)a[f]=e[f]}};M.internals.addRef=function(a,b){return new zc(function(c){return new Bb(b.getDisposable(),a.subscribe(c))})}}Function.prototype.bind||(Function.prototype.bind=function(a){var b=this,c=tb.call(arguments,1),d=function(){function e(){}if(this instanceof d){e.prototype=b.prototype;var f=new e,g=b.apply(f,c.concat(tb.call(arguments)));return Object(g)===g?g:f}return b.apply(a,c.concat(tb.call(arguments)))};return d}),Array.prototype.forEach||(Array.prototype.forEach=function(a,b){var c,d;if(null==this)throw new TypeError(" this is null or not defined");var e=Object(this),f=e.length>>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(arguments.length>1&&(c=b),d=0;f>d;){var g;d in e&&(g=e[d],a.call(c,g,d,e)),d++}});var wb=Object("a"),xb="a"!=wb[0]||!(0 in wb);Array.prototype.every||(Array.prototype.every=function(a){var b=Object(this),c=xb&&{}.toString.call(this)==hb?this.split(""):b,d=c.length>>>0,e=arguments[1];if({}.toString.call(a)!=db)throw new TypeError(a+" is not a function");for(var f=0;d>f;f++)if(f in c&&!a.call(e,c[f],f,b))return!1;return!0}),Array.prototype.map||(Array.prototype.map=function(a){var b=Object(this),c=xb&&{}.toString.call(this)==hb?this.split(""):b,d=c.length>>>0,e=Array(d),f=arguments[1];if({}.toString.call(a)!=db)throw new TypeError(a+" is not a function");for(var g=0;d>g;g++)g in c&&(e[g]=a.call(f,c[g],g,b));return e}),Array.prototype.filter||(Array.prototype.filter=function(a){for(var b,c=[],d=new Object(this),e=0,f=d.length>>>0;f>e;e++)b=d[e],e in d&&a.call(arguments[1],b,e,d)&&c.push(b);return c}),Array.isArray||(Array.isArray=function(a){return{}.toString.call(a)==_}),Array.prototype.indexOf||(Array.prototype.indexOf=function(a){var b=Object(this),c=b.length>>>0;if(0===c)return-1;var d=0;if(arguments.length>1&&(d=Number(arguments[1]),d!==d?d=0:0!==d&&1/0!=d&&d!==-1/0&&(d=(d>0||-1)*Math.floor(Math.abs(d)))),d>=c)return-1;for(var e=d>=0?d:Math.max(c-Math.abs(d),0);c>e;e++)if(e in b&&b[e]===a)return e;return-1});var yb=function(a,b){this.id=a,this.value=b};yb.prototype.compareTo=function(a){var b=this.value.compareTo(a.value);return 0===b&&(b=this.id-a.id),b};var zb=M.internals.PriorityQueue=function(a){this.items=new Array(a),this.length=0},Ab=zb.prototype;Ab.isHigherPriority=function(a,b){return this.items[a].compareTo(this.items[b])<0},Ab.percolate=function(a){if(!(a>=this.length||0>a)){var b=a-1>>1;if(!(0>b||b===a)&&this.isHigherPriority(a,b)){var c=this.items[a];this.items[a]=this.items[b],this.items[b]=c,this.percolate(b)}}},Ab.heapify=function(b){if(b===a&&(b=0),!(b>=this.length||0>b)){var c=2*b+1,d=2*b+2,e=b;if(cb;b++)a[b].dispose()}},Cb.toArray=function(){return this.disposables.slice(0)};var Db=M.Disposable=function(a){this.isDisposed=!1,this.action=a||N};Db.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var Eb=Db.create=function(a){return new Db(a)},Fb=Db.empty={dispose:N},Gb=M.SingleAssignmentDisposable=SerialDisposable=M.SerialDisposable=function(){function a(){this.isDisposed=!1,this.current=null}var b=a.prototype;return b.getDisposable=function(){return this.current},b.setDisposable=function(a){var b,c=this.isDisposed;c||(b=this.current,this.current=a),b&&b.dispose(),c&&a&&a.dispose()},b.dispose=function(){var a;this.isDisposed||(this.isDisposed=!0,a=this.current,this.current=null),a&&a.dispose()},a}(),Hb=(M.RefCountDisposable=function(){function a(a){this.disposable=a,this.disposable.count++,this.isInnerDisposed=!1}function b(a){this.underlyingDisposable=a,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return a.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},b.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},b.prototype.getDisposable=function(){return this.isDisposed?Fb:new a(this)},b}(),M.internals.ScheduledItem=function(a,b,c,d,e){this.scheduler=a,this.state=b,this.action=c,this.dueTime=d,this.comparer=e||S,this.disposable=new Gb});Hb.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},Hb.prototype.compareTo=function(a){return this.comparer(this.dueTime,a.dueTime)},Hb.prototype.isCancelled=function(){return this.disposable.isDisposed},Hb.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var Ib=M.Scheduler=function(){function a(a,b,c,d){this.now=a,this._schedule=b,this._scheduleRelative=c,this._scheduleAbsolute=d}function b(a,b){return b(),Fb}var c=a.prototype;return c.schedule=function(a){return this._schedule(a,b)},c.scheduleWithState=function(a,b){return this._schedule(a,b)},c.scheduleWithRelative=function(a,c){return this._scheduleRelative(c,a,b)},c.scheduleWithRelativeAndState=function(a,b,c){return this._scheduleRelative(a,b,c)},c.scheduleWithAbsolute=function(a,c){return this._scheduleAbsolute(c,a,b)},c.scheduleWithAbsoluteAndState=function(a,b,c){return this._scheduleAbsolute(a,b,c)},a.now=Q,a.normalize=function(a){return 0>a&&(a=0),a},a}(),Jb=Ib.normalize;!function(a){function b(a,b){var c=b.first,d=b.second,e=new Bb,f=function(b){d(b,function(b){var c=!1,d=!1,g=a.scheduleWithState(b,function(a,b){return c?e.remove(g):d=!0,f(b),Fb});d||(e.add(g),c=!0)})};return f(c),e}function c(a,b,c){var d=b.first,e=b.second,f=new Bb,g=function(b){e(b,function(b,d){var e=!1,h=!1,i=a[c].call(a,b,d,function(a,b){return e?f.remove(i):h=!0,g(b),Fb});h||(f.add(i),e=!0)})};return g(d),f}function d(a,b){a(function(c){b(a,c)})}a.scheduleRecursive=function(a){return this.scheduleRecursiveWithState(a,function(a,b){a(function(){b(a)})})},a.scheduleRecursiveWithState=function(a,c){return this.scheduleWithState({first:a,second:c},b)},a.scheduleRecursiveWithRelative=function(a,b){return this.scheduleRecursiveWithRelativeAndState(b,a,d)},a.scheduleRecursiveWithRelativeAndState=function(a,b,d){return this._scheduleRelative({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithRelativeAndState")})},a.scheduleRecursiveWithAbsolute=function(a,b){return this.scheduleRecursiveWithAbsoluteAndState(b,a,d)},a.scheduleRecursiveWithAbsoluteAndState=function(a,b,d){return this._scheduleAbsolute({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithAbsoluteAndState")})}}(Ib.prototype),function(){Ib.prototype.schedulePeriodic=function(a,b){return this.schedulePeriodicWithState(null,a,b)},Ib.prototype.schedulePeriodicWithState=function(a,b,c){var d=a,e=setInterval(function(){d=c(d)},b);return Eb(function(){clearInterval(e)})}}(Ib.prototype);var Kb,Lb=Ib.immediate=function(){function a(a,b){return b(this,a)}function b(a,b,c){for(var d=Jb(d);d-this.now()>0;);return c(this,a)}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new Ib(Q,a,b,c)}(),Mb=Ib.currentThread=function(){function a(a){for(var b;a.length>0;)if(b=a.dequeue(),!b.isCancelled()){for(;b.dueTime-Ib.now()>0;);b.isCancelled()||b.invoke()}}function b(a,b){return this.scheduleWithRelativeAndState(a,0,b)}function c(b,c,d){var f=this.now()+Ib.normalize(c),g=new Hb(this,b,d,f);if(e)e.enqueue(g);else{e=new zb(4),e.enqueue(g);try{a(e)}catch(h){throw h}finally{e=null}}return g.disposable}function d(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}var e,f=new Ib(Q,b,c,d);return f.scheduleRequired=function(){return!e},f.ensureTrampoline=function(a){e?a():this.schedule(a)},f}(),Nb=(M.internals.SchedulePeriodicRecursive=function(){function a(a,b){b(0,this._period);try{this._state=this._action(this._state)}catch(c){throw this._cancel.dispose(),c}}function b(a,b,c,d){this._scheduler=a,this._state=b,this._period=c,this._action=d}return b.prototype.start=function(){var b=new Gb;return this._cancel=b,b.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,a.bind(this))),b},b}(),N);!function(){function a(){if(!H.postMessage||H.importScripts)return!1;var a=!1,b=H.onmessage;return H.onmessage=function(){a=!0},H.postMessage("","*"),H.onmessage=b,a}function b(a){if("string"==typeof a.data&&a.data.substring(0,f.length)===f){var b=a.data.substring(f.length),c=g[b];c(),delete g[b]}}var c=RegExp("^"+String(ib).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),d="function"==typeof(d=L&&K&&L.setImmediate)&&!c.test(d)&&d,e="function"==typeof(e=L&&K&&L.clearImmediate)&&!c.test(e)&&e;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))Kb=process.nextTick;else if("function"==typeof d)Kb=d,Nb=e;else if(a()){var f="ms.rx.schedule"+Math.random(),g={},h=0;H.addEventListener?H.addEventListener("message",b,!1):H.attachEvent("onmessage",b,!1),Kb=function(a){var b=h++;g[b]=a,H.postMessage(f+b,"*")}}else if(H.MessageChannel){var i=new H.MessageChannel,j={},k=0;i.port1.onmessage=function(a){var b=a.data,c=j[b];c(),delete j[b]},Kb=function(a){var b=k++;j[b]=a,i.port2.postMessage(b)}}else"document"in H&&"onreadystatechange"in H.document.createElement("script")?Kb=function(a){var b=H.document.createElement("script");b.onreadystatechange=function(){a(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},H.document.documentElement.appendChild(b)}:(Kb=function(a){return setTimeout(a,0)},Nb=clearTimeout)}();var Ob=Ib.timeout=function(){function a(a,b){var c=this,d=new Gb,e=Kb(function(){d.isDisposed||d.setDisposable(b(c,a))});return new Bb(d,Eb(function(){Nb(e)}))}function b(a,b,c){var d=this,e=Ib.normalize(b);if(0===e)return d.scheduleWithState(a,c);var f=new Gb,g=setTimeout(function(){f.isDisposed||f.setDisposable(c(d,a))},e);return new Bb(f,Eb(function(){clearTimeout(g)}))}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new Ib(Q,a,b,c)}(),Pb=M.Notification=function(){function a(a,b){this.hasValue=null==b?!1:b,this.kind=a}return a.prototype.accept=function(a,b,c){return a&&"object"==typeof a?this._acceptObservable(a):this._accept(a,b,c)},a.prototype.toObservable=function(a){var b=this;return O(a)||(a=Lb),new zc(function(c){return a.schedule(function(){b._acceptObservable(c),"N"===b.kind&&c.onCompleted()})})},a}(),Qb=Pb.createOnNext=function(){function a(a){return a(this.value)}function b(a){return a.onNext(this.value)}function c(){return"OnNext("+this.value+")"}return function(d){var e=new Pb("N",!0);return e.value=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),Rb=Pb.createOnError=function(){function a(a,b){return b(this.exception)}function b(a){return a.onError(this.exception)}function c(){return"OnError("+this.exception+")"}return function(d){var e=new Pb("E");return e.exception=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),Sb=Pb.createOnCompleted=function(){function a(a,b,c){return c()}function b(a){return a.onCompleted()}function c(){return"OnCompleted()"}return function(){var d=new Pb("C");return d._accept=a,d._acceptObservable=b,d.toString=c,d}}(),Tb=M.internals.Enumerator=function(a){this._next=a};Tb.prototype.next=function(){return this._next()},Tb.prototype[X]=function(){return this};var Ub=M.internals.Enumerable=function(a){this._iterator=a};Ub.prototype[X]=function(){return this._iterator()},Ub.prototype.concat=function(){var a=this;return new zc(function(b){var c;try{c=a[X]()}catch(d){return void b.onError()}var e,f=new SerialDisposable,g=Lb.scheduleRecursive(function(a){var d;if(!e){try{d=c.next()}catch(g){return void b.onError(g)}if(d.done)return void b.onCompleted();var h=d.value;U(h)&&(h=rc(h));var i=new Gb;f.setDisposable(i),i.setDisposable(h.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){a()}))}});return new Bb(f,g,Eb(function(){e=!0}))})},Ub.prototype.catchException=function(){var a=this;return new zc(function(b){var c;try{c=a[X]()}catch(d){return void b.onError()}var e,f,g=new SerialDisposable,h=Lb.scheduleRecursive(function(a){if(!e){var d;try{d=c.next()}catch(h){return void b.onError(h)}if(d.done)return void(f?b.onError(f):b.onCompleted());var i=d.value;U(i)&&(i=rc(i));var j=new Gb;g.setDisposable(j),j.setDisposable(i.subscribe(b.onNext.bind(b),function(b){f=b,a()},b.onCompleted.bind(b)))}});return new Bb(g,h,Eb(function(){e=!0}))})};var Vb=Ub.repeat=function(a,b){return null==b&&(b=-1),new Ub(function(){var c=b;return new Tb(function(){return 0===c?Z:(c>0&&c--,{done:!1,value:a})})})},Wb=Ub.forEach=function(a,b,c){return b||(b=P),new Ub(function(){var d=-1;return new Tb(function(){return++d0&&(a=!this.isAcquired,this.isAcquired=!0),a&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(a){var c;if(!(b.queue.length>0))return void(b.isAcquired=!1);c=b.queue.shift();try{c()}catch(d){throw b.queue=[],b.hasFaulted=!0,d}a()}))},b.prototype.dispose=function(){a.prototype.dispose.call(this),this.disposable.dispose()},b}($b);Zb.toArray=function(){var a=this;return new zc(function(b){var c=[];return a.subscribe(c.push.bind(c),b.onError.bind(b),function(){b.onNext(c),b.onCompleted()})})},ac.create=ac.createWithDisposable=function(a){return new zc(a)};var cc=ac.defer=function(a){return new zc(function(b){var c;try{c=a()}catch(d){return ic(d).subscribe(b)}return U(c)&&(c=rc(c)),c.subscribe(b)})},dc=ac.empty=function(a){return O(a)||(a=Lb),new zc(function(b){return a.schedule(function(){b.onCompleted()})})},ec=Math.pow(2,53)-1;ac.from=function(a,b,c,d){if(null==a)throw new Error("iterable cannot be null.");if(b&&!q(b))throw new Error("mapFn when provided must be a function");return O(d)||(d=Mb),new zc(function(e){var f=Object(a),g=n(f),h=g?0:p(f),i=g?f[X]():null,j=0;return d.scheduleRecursive(function(a){if(h>j||g){var d;if(g){var k=i.next();if(k.done)return void e.onCompleted();d=k.value}else d=f[j];if(b&&q(b))try{d=c?b.call(c,d,j):b(d,j)}catch(l){return void e.onError(l)}e.onNext(d),j++,a()}else e.onCompleted()})})};var fc=ac.fromArray=function(a,b){return O(b)||(b=Mb),new zc(function(c){var d=0,e=a.length;return b.scheduleRecursive(function(b){e>d?(c.onNext(a[d++]),b()):c.onCompleted()})})},gc=ac.never=function(){return new zc(function(){return Fb})};ac.of=function(){for(var a=arguments.length,b=new Array(a),c=0;a>c;c++)b[c]=arguments[c];return fc(b)};ac.ofWithScheduler=function(a){for(var b=arguments.length-1,c=new Array(b),d=0;b>d;d++)c[d]=arguments[d+1];return fc(c,a)};ac.range=function(a,b,c){return O(c)||(c=Mb),new zc(function(d){return c.scheduleRecursiveWithState(0,function(c,e){b>c?(d.onNext(a+c),e(c+1)):d.onCompleted()})})},ac.repeat=function(a,b,c){return O(c)||(c=Mb),hc(a,c).repeat(null==b?-1:b)};var hc=ac["return"]=ac.returnValue=ac.just=function(a,b){return O(b)||(b=Lb),new zc(function(c){return b.schedule(function(){c.onNext(a),c.onCompleted()})})},ic=ac["throw"]=ac.throwException=function(a,b){return O(b)||(b=Lb),new zc(function(c){return b.schedule(function(){c.onError(a)})})};Zb["catch"]=Zb.catchException=function(a){return"function"==typeof a?r(this,a):jc([this,a])};var jc=ac.catchException=ac["catch"]=function(){var a=k(arguments,0);return Wb(a).catchException()};Zb.combineLatest=function(){var a=tb.call(arguments);return Array.isArray(a[0])?a[0].unshift(this):a.unshift(this),kc.apply(this,a)};var kc=ac.combineLatest=function(){var a=tb.call(arguments),b=a.pop();return Array.isArray(a[0])&&(a=a[0]),new zc(function(c){function d(a){var d;if(h[a]=!0,i||(i=h.every(P))){try{d=b.apply(null,k)}catch(e){return void c.onError(e)}c.onNext(d)}else j.filter(function(b,c){return c!==a}).every(P)&&c.onCompleted()}function e(a){j[a]=!0,j.every(P)&&c.onCompleted()}for(var f=function(){return!1},g=a.length,h=l(g,f),i=!1,j=l(g,f),k=new Array(g),m=new Array(g),n=0;g>n;n++)!function(b){var f=a[b],g=new Gb;U(f)&&(f=rc(f)),g.setDisposable(f.subscribe(function(a){k[b]=a,d(b)},c.onError.bind(c),function(){e(b)})),m[b]=g}(n);return new Bb(m)})};Zb.concat=function(){var a=tb.call(arguments,0);return a.unshift(this),lc.apply(this,a)};var lc=ac.concat=function(){var a=k(arguments,0);return Wb(a).concat()};Zb.concatObservable=Zb.concatAll=function(){return this.merge(1)},Zb.merge=function(a){if("number"!=typeof a)return mc(this,a);var b=this;return new zc(function(c){function d(a){var b=new Gb;f.add(b),U(a)&&(a=rc(a)),b.setDisposable(a.subscribe(c.onNext.bind(c),c.onError.bind(c),function(){f.remove(b),h.length>0?d(h.shift()):(e--,g&&0===e&&c.onCompleted())}))}var e=0,f=new Bb,g=!1,h=[];return f.add(b.subscribe(function(b){a>e?(e++,d(b)):h.push(b)},c.onError.bind(c),function(){g=!0,0===e&&c.onCompleted()})),f})};var mc=ac.merge=function(){var a,b;return arguments[0]?arguments[0].now?(a=arguments[0],b=tb.call(arguments,1)):(a=Lb,b=tb.call(arguments,0)):(a=Lb,b=tb.call(arguments,1)),Array.isArray(b[0])&&(b=b[0]),fc(b,a).mergeObservable()};Zb.mergeObservable=Zb.mergeAll=function(){var a=this;return new zc(function(b){var c=new Bb,d=!1,e=new Gb;return c.add(e),e.setDisposable(a.subscribe(function(a){var e=new Gb;c.add(e),U(a)&&(a=rc(a)),e.setDisposable(a.subscribe(function(a){b.onNext(a)},b.onError.bind(b),function(){c.remove(e),d&&1===c.length&&b.onCompleted()}))},b.onError.bind(b),function(){d=!0,1===c.length&&b.onCompleted()})),c})},Zb.skipUntil=function(a){var b=this;return new zc(function(c){var d=!1,e=new Bb(b.subscribe(function(a){d&&c.onNext(a)},c.onError.bind(c),function(){d&&c.onCompleted()}));U(a)&&(a=rc(a));var f=new Gb;return e.add(f),f.setDisposable(a.subscribe(function(){d=!0,f.dispose()},c.onError.bind(c),function(){f.dispose()})),e})},Zb["switch"]=Zb.switchLatest=function(){var a=this;return new zc(function(b){var c=!1,d=new SerialDisposable,e=!1,f=0,g=a.subscribe(function(a){var g=new Gb,h=++f;c=!0,d.setDisposable(g),U(a)&&(a=rc(a)),g.setDisposable(a.subscribe(function(a){f===h&&b.onNext(a)},function(a){f===h&&b.onError(a)},function(){f===h&&(c=!1,e&&b.onCompleted())}))},b.onError.bind(b),function(){e=!0,c||b.onCompleted()});return new Bb(g,d)})},Zb.takeUntil=function(a){var b=this;return new zc(function(c){return U(a)&&(a=rc(a)),new Bb(b.subscribe(c),a.subscribe(c.onCompleted.bind(c),c.onError.bind(c),N))})},Zb.zip=function(){if(Array.isArray(arguments[0]))return s.apply(this,arguments);var a=this,b=tb.call(arguments),c=b.pop();return b.unshift(a),new zc(function(d){function e(b){var e,f;if(h.every(function(a){return a.length>0})){try{f=h.map(function(a){return a.shift()}),e=c.apply(a,f)}catch(g){return void d.onError(g)}d.onNext(e)}else i.filter(function(a,c){return c!==b}).every(P)&&d.onCompleted()}function f(a){i[a]=!0,i.every(function(a){return a})&&d.onCompleted()}for(var g=b.length,h=l(g,function(){return[]}),i=l(g,function(){return!1}),j=new Array(g),k=0;g>k;k++)!function(a){var c=b[a],g=new Gb;U(c)&&(c=rc(c)),g.setDisposable(c.subscribe(function(b){h[a].push(b),e(a)},d.onError.bind(d),function(){f(a)})),j[a]=g}(k);return new Bb(j)})},ac.zip=function(){var a=tb.call(arguments,0),b=a.shift();return b.zip.apply(b,a)},ac.zipArray=function(){var a=k(arguments,0);return new zc(function(b){function c(a){if(f.every(function(a){return a.length>0})){var c=f.map(function(a){return a.shift()});b.onNext(c)}else if(g.filter(function(b,c){return c!==a}).every(P))return void b.onCompleted()}function d(a){return g[a]=!0,g.every(P)?void b.onCompleted():void 0}for(var e=a.length,f=l(e,function(){return[]}),g=l(e,function(){return!1}),h=new Array(e),i=0;e>i;i++)!function(e){h[e]=new Gb,h[e].setDisposable(a[e].subscribe(function(a){f[e].push(a),c(e)},b.onError.bind(b),function(){d(e) +}))}(i);var j=new Bb(h);return j.add(Eb(function(){for(var a=0,b=f.length;b>a;a++)f[a]=[]})),j})},Zb.asObservable=function(){var a=this;return new zc(function(b){return a.subscribe(b)})},Zb.dematerialize=function(){var a=this;return new zc(function(b){return a.subscribe(function(a){return a.accept(b)},b.onError.bind(b),b.onCompleted.bind(b))})},Zb.distinctUntilChanged=function(a,b){var c=this;return a||(a=P),b||(b=R),new zc(function(d){var e,f=!1;return c.subscribe(function(c){var g,h=!1;try{g=a(c)}catch(i){return void d.onError(i)}if(f)try{h=b(e,g)}catch(i){return void d.onError(i)}f&&h||(f=!0,e=g,d.onNext(c))},d.onError.bind(d),d.onCompleted.bind(d))})},Zb["do"]=Zb.doAction=Zb.tap=function(a,b,c){var d,e=this;return"function"==typeof a?d=a:(d=a.onNext.bind(a),b=a.onError.bind(a),c=a.onCompleted.bind(a)),new zc(function(a){return e.subscribe(function(b){try{d(b)}catch(c){a.onError(c)}a.onNext(b)},function(c){if(b){try{b(c)}catch(d){a.onError(d)}a.onError(c)}else a.onError(c)},function(){if(c){try{c()}catch(b){a.onError(b)}a.onCompleted()}else a.onCompleted()})})},Zb["finally"]=Zb.finallyAction=function(a){var b=this;return new zc(function(c){var d;try{d=b.subscribe(c)}catch(e){throw a(),e}return Eb(function(){try{d.dispose()}catch(b){throw b}finally{a()}})})},Zb.ignoreElements=function(){var a=this;return new zc(function(b){return a.subscribe(N,b.onError.bind(b),b.onCompleted.bind(b))})},Zb.materialize=function(){var a=this;return new zc(function(b){return a.subscribe(function(a){b.onNext(Qb(a))},function(a){b.onNext(Rb(a)),b.onCompleted()},function(){b.onNext(Sb()),b.onCompleted()})})},Zb.repeat=function(a){return Vb(this,a).concat()},Zb.retry=function(a){return Vb(this,a).catchException()},Zb.scan=function(){var a,b,c=!1,d=this;return 2===arguments.length?(c=!0,a=arguments[0],b=arguments[1]):b=arguments[0],new zc(function(e){var f,g,h;return d.subscribe(function(d){try{h||(h=!0),f?g=b(g,d):(g=c?b(a,d):d,f=!0)}catch(i){return void e.onError(i)}e.onNext(g)},e.onError.bind(e),function(){!h&&c&&e.onNext(a),e.onCompleted()})})},Zb.skipLast=function(a){var b=this;return new zc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&c.onNext(d.shift())},c.onError.bind(c),c.onCompleted.bind(c))})},Zb.startWith=function(){var a,b,c=0;return arguments.length&&"now"in Object(arguments[0])?(b=arguments[0],c=1):b=Lb,a=tb.call(arguments,c),Wb([fc(a,b),this]).concat()},Zb.takeLast=function(a){var b=this;return new zc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&d.shift()},c.onError.bind(c),function(){for(;d.length>0;)c.onNext(d.shift());c.onCompleted()})})},Zb.selectConcat=Zb.concatMap=function(a,b,c){return b?this.concatMap(function(c,d){var e=a(c,d),f=U(e)?rc(e):e;return f.map(function(a){return b(c,a,d)})}):"function"==typeof a?t(this,a,c):t(this,function(){return a})},Zb.select=Zb.map=function(a,b){var c=this;return new zc(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},Zb.pluck=function(a){return this.select(function(b){return b[a]})},Zb.selectMany=Zb.flatMap=function(a,b,c){return b?this.flatMap(function(c,d){var e=a(c,d),f=U(e)?rc(e):e;return f.map(function(a){return b(c,a,d)})},c):"function"==typeof a?u(this,a,c):u(this,function(){return a})},Zb.selectSwitch=Zb.flatMapLatest=Zb.switchMap=function(a,b){return this.select(a,b).switchLatest()},Zb.skip=function(a){if(0>a)throw new Error(V);var b=this;return new zc(function(c){var d=a;return b.subscribe(function(a){0>=d?c.onNext(a):d--},c.onError.bind(c),c.onCompleted.bind(c))})},Zb.skipWhile=function(a,b){var c=this;return new zc(function(d){var e=0,f=!1;return c.subscribe(function(g){if(!f)try{f=!a.call(b,g,e++,c)}catch(h){return void d.onError(h)}f&&d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},Zb.take=function(a,b){if(0>a)throw new Error(V);if(0===a)return dc(b);var c=this;return new zc(function(b){var d=a;return c.subscribe(function(a){d>0&&(d--,b.onNext(a),0===d&&b.onCompleted())},b.onError.bind(b),b.onCompleted.bind(b))})},Zb.takeWhile=function(a,b){var c=this;return new zc(function(d){var e=0,f=!0;return c.subscribe(function(g){if(f){try{f=a.call(b,g,e++,c)}catch(h){return void d.onError(h)}f?d.onNext(g):d.onCompleted()}},d.onError.bind(d),d.onCompleted.bind(d))})},Zb.where=Zb.filter=function(a,b){var c=this;return new zc(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}g&&d.onNext(f)},d.onError.bind(d),d.onCompleted.bind(d))})},ac.fromCallback=function(a,b,c){return function(){var d=tb.call(arguments,0);return new zc(function(e){function f(a){var b=a;if(c){try{b=c(arguments)}catch(d){return void e.onError(d)}e.onNext(b)}else b.length<=1?e.onNext.apply(e,b):e.onNext(b);e.onCompleted()}d.push(f),a.apply(b,d)}).publishLast().refCount()}},ac.fromNodeCallback=function(a,b,c){return function(){var d=tb.call(arguments,0);return new zc(function(e){function f(a){if(a)return void e.onError(a);var b=tb.call(arguments,1);if(c){try{b=c(b)}catch(d){return void e.onError(d)}e.onNext(b)}else b.length<=1?e.onNext.apply(e,b):e.onNext(b);e.onCompleted()}d.push(f),a.apply(b,d)}).publishLast().refCount()}},M.config.useNativeEvents=!1;var nc=H.angular&&angular.element?angular.element:H.jQuery?H.jQuery:H.Zepto?H.Zepto:null,oc=!!H.Ember&&"function"==typeof H.Ember.addListener,pc=!!H.Backbone&&!!H.Backbone.Marionette;ac.fromEvent=function(a,b,c){if(a.addListener)return qc(function(c){a.addListener(b,c)},function(c){a.removeListener(b,c)},c);if(!M.config.useNativeEvents){if(pc)return qc(function(c){a.on(b,c)},function(c){a.off(b,c)},c);if(oc)return qc(function(c){Ember.addListener(a,b,c)},function(c){Ember.removeListener(a,b,c)},c);if(nc){var d=nc(a);return qc(function(a){d.on(b,a)},function(a){d.off(b,a)},c)}}return new zc(function(d){return x(a,b,function(a){var b=a;if(c)try{b=c(arguments)}catch(e){return void d.onError(e)}d.onNext(b)})}).publish().refCount()};var qc=ac.fromEventPattern=function(a,b,c){return new zc(function(d){function e(a){var b=a;if(c)try{b=c(arguments)}catch(e){return void d.onError(e)}d.onNext(b)}var f=a(e);return Eb(function(){b&&b(e,f)})}).publish().refCount()},rc=ac.fromPromise=function(a){return cc(function(){var b=new M.AsyncSubject;return a.then(function(a){b.isDisposed||(b.onNext(a),b.onCompleted())},b.onError.bind(b)),b})};Zb.toPromise=function(a){if(a||(a=M.config.Promise),!a)throw new Error("Promise type not provided nor in Rx.config.Promise");var b=this;return new a(function(a,c){var d,e=!1;b.subscribe(function(a){d=a,e=!0},function(a){c(a)},function(){e&&a(d)})})},ac.startAsync=function(a){var b;try{b=a()}catch(c){return ic(c)}return rc(b)},Zb.multicast=function(a,b){var c=this;return"function"==typeof a?new zc(function(d){var e=c.multicast(a());return new Bb(b(e).subscribe(d),e.connect())}):new sc(c,a)},Zb.publish=function(a){return a?this.multicast(function(){return new Cc},a):this.multicast(new Cc)},Zb.share=function(){return this.publish(null).refCount()},Zb.publishLast=function(a){return a?this.multicast(function(){return new Dc},a):this.multicast(new Dc)},Zb.publishValue=function(a,b){return 2===arguments.length?this.multicast(function(){return new Fc(b)},a):this.multicast(new Fc(a))},Zb.shareValue=function(a){return this.publishValue(a).refCount()},Zb.replay=function(a,b,c,d){return a?this.multicast(function(){return new Gc(b,c,d)},a):this.multicast(new Gc(b,c,d))},Zb.shareReplay=function(a,b,c){return this.replay(null,a,b,c).refCount()};var sc=M.ConnectableObservable=function(a){function b(b,c){var d,e=!1,f=b.asObservable();this.connect=function(){return e||(e=!0,d=new Bb(f.subscribe(c),Eb(function(){e=!1}))),d},a.call(this,c.subscribe.bind(c))}return ub(b,a),b.prototype.refCount=function(){var a,b=0,c=this;return new zc(function(d){var e=1===++b,f=c.subscribe(d);return e&&(a=c.connect()),function(){f.dispose(),0===--b&&a.dispose()}})},b}(ac),tc=ac.interval=function(a,b){return B(a,a,O(b)?b:Ob)},uc=ac.timer=function(b,c,d){var e;return O(d)||(d=Ob),c!==a&&"number"==typeof c?e=c:c!==a&&"object"==typeof c&&(d=c),b instanceof Date&&e===a?y(b.getTime(),d):b instanceof Date&&e!==a?(e=c,z(b.getTime(),e,d)):e===a?A(b,d):B(b,e,d)};Zb.delay=function(a,b){return O(b)||(b=Ob),a instanceof Date?D(this,a.getTime(),b):C(this,a,b)},Zb.throttle=function(a,b){return O(b)||(b=Ob),this.throttleWithSelector(function(){return uc(a,b)})},Zb.timestamp=function(a){return O(a)||(a=Ob),this.map(function(b){return{value:b,timestamp:a.now()}})},Zb.sample=function(a,b){return O(b)||(b=Ob),"number"==typeof a?E(this,tc(a,b)):E(this,a)},Zb.timeout=function(a,b,c){b||(b=ic(new Error("Timeout"))),O(c)||(c=Ob);var d=this,e=a instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new zc(function(f){var g=0,h=new Gb,i=new SerialDisposable,j=!1,k=new SerialDisposable;i.setDisposable(h);var l=function(){var d=g;k.setDisposable(c[e](a,function(){g===d&&(U(b)&&(b=rc(b)),i.setDisposable(b.subscribe(f)))}))};return l(),h.setDisposable(d.subscribe(function(a){j||(g++,f.onNext(a),l())},function(a){j||(g++,f.onError(a))},function(){j||(g++,f.onCompleted())})),new Bb(i,k)})},Zb.delaySubscription=function(a,b){return this.delayWithSelector(uc(a,O(b)?b:Ob),dc)},Zb.delayWithSelector=function(a,b){var c,d,e=this;return"function"==typeof a?d=a:(c=a,d=b),new zc(function(a){var b=new Bb,f=!1,g=function(){f&&0===b.length&&a.onCompleted()},h=new SerialDisposable,i=function(){h.setDisposable(e.subscribe(function(c){var e;try{e=d(c)}catch(f){return void a.onError(f)}var h=new Gb;b.add(h),h.setDisposable(e.subscribe(function(){a.onNext(c),b.remove(h),g()},a.onError.bind(a),function(){a.onNext(c),b.remove(h),g()}))},a.onError.bind(a),function(){f=!0,h.dispose(),g()}))};return c?h.setDisposable(c.subscribe(function(){i()},a.onError.bind(a),function(){i()})):i(),new Bb(h,b)})},Zb.timeoutWithSelector=function(a,b,c){if(1===arguments.length){b=a;var a=gc()}c||(c=ic(new Error("Timeout")));var d=this;return new zc(function(e){var f=new SerialDisposable,g=new SerialDisposable,h=new Gb;f.setDisposable(h);var i=0,j=!1,k=function(a){var b=i,d=function(){return i===b},h=new Gb;g.setDisposable(h),h.setDisposable(a.subscribe(function(){d()&&f.setDisposable(c.subscribe(e)),h.dispose()},function(a){d()&&e.onError(a)},function(){d()&&f.setDisposable(c.subscribe(e))}))};k(a);var l=function(){var a=!j;return a&&i++,a};return h.setDisposable(d.subscribe(function(a){if(l()){e.onNext(a);var c;try{c=b(a)}catch(d){return void e.onError(d)}k(c)}},function(a){l()&&e.onError(a)},function(){l()&&e.onCompleted()})),new Bb(f,g)})},Zb.throttleWithSelector=function(a){var b=this;return new zc(function(c){var d,e=!1,f=new SerialDisposable,g=0,h=b.subscribe(function(b){var h;try{h=a(b)}catch(i){return void c.onError(i)}e=!0,d=b,g++;var j=g,k=new Gb;f.setDisposable(k),k.setDisposable(h.subscribe(function(){e&&g===j&&c.onNext(d),e=!1,k.dispose()},c.onError.bind(c),function(){e&&g===j&&c.onNext(d),e=!1,k.dispose()}))},function(a){f.dispose(),c.onError(a),e=!1,g++},function(){f.dispose(),e&&c.onNext(d),c.onCompleted(),e=!1,g++});return new Bb(h,f)})},Zb.skipLastWithTime=function(a,b){O(b)||(b=Ob);var c=this;return new zc(function(d){var e=[];return c.subscribe(function(c){var f=b.now();for(e.push({interval:f,value:c});e.length>0&&f-e[0].interval>=a;)d.onNext(e.shift().value)},d.onError.bind(d),function(){for(var c=b.now();e.length>0&&c-e[0].interval>=a;)d.onNext(e.shift().value);d.onCompleted()})})},Zb.takeLastWithTime=function(a,b){var c=this;return O(b)||(b=Ob),new zc(function(d){var e=[];return c.subscribe(function(c){var d=b.now();for(e.push({interval:d,value:c});e.length>0&&d-e[0].interval>=a;)e.shift()},d.onError.bind(d),function(){for(var c=b.now();e.length>0;){var f=e.shift();c-f.interval<=a&&d.onNext(f.value)}d.onCompleted()})})},Zb.takeWithTime=function(a,b){var c=this;return O(b)||(b=Ob),new zc(function(d){return new Bb(b.scheduleWithRelative(a,d.onCompleted.bind(d)),c.subscribe(d))})},Zb.skipWithTime=function(a,b){var c=this;return O(b)||(b=Ob),new zc(function(d){var e=!1;return new Bb(b.scheduleWithRelative(a,function(){e=!0}),c.subscribe(function(a){e&&d.onNext(a)},d.onError.bind(d),d.onCompleted.bind(d)))})};var vc=function(a){function b(a){var b=this.source.publish(),c=b.subscribe(a),d=Fb,e=this.pauser.distinctUntilChanged().subscribe(function(a){a?d=b.connect():(d.dispose(),d=Fb)});return new Bb(c,d,e)}function c(c,d){this.source=c,this.controller=new Cc,this.pauser=d&&d.subscribe?this.controller.merge(d):this.controller,a.call(this,b)}return ub(c,a),c.prototype.pause=function(){this.controller.onNext(!1)},c.prototype.resume=function(){this.controller.onNext(!0)},c}(ac);Zb.pausable=function(a){return new vc(this,a)};var wc=function(b){function c(b){var c,d=[],e=F(this.source,this.pauser.distinctUntilChanged().startWith(!1),function(a,b){return{data:a,shouldFire:b}}).subscribe(function(e){if(c!==a&&e.shouldFire!=c){if(e.shouldFire)for(;d.length>0;)b.onNext(d.shift())}else e.shouldFire?b.onNext(e.data):d.push(e.data);c=e.shouldFire},function(a){for(;d.length>0;)b.onNext(d.shift());b.onError(a)},function(){for(;d.length>0;)b.onNext(d.shift());b.onCompleted()});return e}function d(a,d){this.source=a,this.controller=new Cc,this.pauser=d&&d.subscribe?this.controller.merge(d):this.controller,b.call(this,c)}return ub(d,b),d.prototype.pause=function(){this.controller.onNext(!1)},d.prototype.resume=function(){this.controller.onNext(!0)},d}(ac);Zb.pausableBuffered=function(a){return new wc(this,a)},Zb.controlled=function(a){return null==a&&(a=!0),new xc(this,a)};var xc=function(a){function b(a){return this.source.subscribe(a)}function c(c,d){a.call(this,b),this.subject=new yc(d),this.source=c.multicast(this.subject).refCount()}return ub(c,a),c.prototype.request=function(a){return null==a&&(a=-1),this.subject.request(a)},c}(ac),yc=M.ControlledSubject=function(a){function c(a){return this.subject.subscribe(a)}function d(b){null==b&&(b=!0),a.call(this,c),this.subject=new Cc,this.enableQueue=b,this.queue=b?[]:null,this.requestedCount=0,this.requestedDisposable=Fb,this.error=null,this.hasFailed=!1,this.hasCompleted=!1,this.controlledDisposable=Fb}return ub(d,a),vb(d.prototype,Xb,{onCompleted:function(){b.call(this),this.hasCompleted=!0,this.enableQueue&&0!==this.queue.length||this.subject.onCompleted()},onError:function(a){b.call(this),this.hasFailed=!0,this.error=a,this.enableQueue&&0!==this.queue.length||this.subject.onError(a)},onNext:function(a){b.call(this);var c=!1;0===this.requestedCount?this.enableQueue&&this.queue.push(a):(-1!==this.requestedCount&&0===this.requestedCount--&&this.disposeCurrentRequest(),c=!0),c&&this.subject.onNext(a)},_processRequest:function(a){if(this.enableQueue){for(;this.queue.length>=a&&a>0;)this.subject.onNext(this.queue.shift()),a--;return 0!==this.queue.length?{numberOfItems:a,returnValue:!0}:{numberOfItems:a,returnValue:!1}}return this.hasFailed?(this.subject.onError(this.error),this.controlledDisposable.dispose(),this.controlledDisposable=Fb):this.hasCompleted&&(this.subject.onCompleted(),this.controlledDisposable.dispose(),this.controlledDisposable=Fb),{numberOfItems:a,returnValue:!1}},request:function(a){b.call(this),this.disposeCurrentRequest();var c=this,d=this._processRequest(a);return a=d.numberOfItems,d.returnValue?Fb:(this.requestedCount=a,this.requestedDisposable=Eb(function(){c.requestedCount=0}),this.requestedDisposable)},disposeCurrentRequest:function(){this.requestedDisposable.dispose(),this.requestedDisposable=Fb},dispose:function(){this.isDisposed=!0,this.error=null,this.subject.dispose(),this.requestedDisposable.dispose()}}),d}(ac);Zb.exclusive=function(){var a=this;return new zc(function(b){var c=!1,d=!1,e=new Gb,f=new Bb;return f.add(e),e.setDisposable(a.subscribe(function(a){if(!c){c=!0,U(a)&&(a=rc(a));var e=new Gb;f.add(e),e.setDisposable(a.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){f.remove(e),c=!1,d&&1===f.length&&b.onCompleted()}))}},b.onError.bind(b),function(){d=!0,c||1!==f.length||b.onCompleted()})),f})},Zb.exclusiveMap=function(a,b){var c=this;return new zc(function(d){var e=0,f=!1,g=!0,h=new Gb,i=new Bb;return i.add(h),h.setDisposable(c.subscribe(function(c){f||(f=!0,innerSubscription=new Gb,i.add(innerSubscription),U(c)&&(c=rc(c)),innerSubscription.setDisposable(c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}d.onNext(g)},d.onError.bind(d),function(){i.remove(innerSubscription),f=!1,g&&1===i.length&&d.onCompleted()})))},d.onError.bind(d),function(){g=!0,1!==i.length||f||d.onCompleted()})),i})};var zc=M.AnonymousObservable=function(a){function b(a){return a&&"function"==typeof a.dispose?a:"function"==typeof a?Eb(a):Fb}function c(d){function e(a){var c=function(){try{e.setDisposable(b(d(e)))}catch(a){if(!e.fail(a))throw a}},e=new Ac(a);return Mb.scheduleRequired()?Mb.schedule(c):c(),e}return this instanceof c?void a.call(this,e):new c(d)}return ub(c,a),c}(ac),Ac=function(a){function b(b){a.call(this),this.observer=b,this.m=new Gb}ub(b,a);var c=b.prototype;return c.next=function(a){var b=!1;try{this.observer.onNext(a),b=!0}catch(c){throw c}finally{b||this.dispose()}},c.error=function(a){try{this.observer.onError(a)}catch(b){throw b}finally{this.dispose()}},c.completed=function(){try{this.observer.onCompleted()}catch(a){throw a}finally{this.dispose()}},c.setDisposable=function(a){this.m.setDisposable(a)},c.getDisposable=function(){return this.m.getDisposable()},c.disposable=function(a){return arguments.length?this.getDisposable():setDisposable(a)},c.dispose=function(){a.prototype.dispose.call(this),this.m.dispose()},b}($b),Bc=function(a,b){this.subject=a,this.observer=b};Bc.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1),this.observer=null}};var Cc=M.Subject=function(a){function c(a){return b.call(this),this.isStopped?this.exception?(a.onError(this.exception),Fb):(a.onCompleted(),Fb):(this.observers.push(a),new Bc(this,a))}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return ub(d,a),vb(d.prototype,Xb,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped)for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)},dispose:function(){this.isDisposed=!0,this.observers=null}}),d.create=function(a,b){return new Ec(a,b)},d}(ac),Dc=M.AsyncSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),new Bc(this,a);var c=this.exception,d=this.hasValue,e=this.value;return c?a.onError(c):d?(a.onNext(e),a.onCompleted()):a.onCompleted(),Fb}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return ub(d,a),vb(d.prototype,Xb,{hasObservers:function(){return b.call(this),this.observers.length>0},onCompleted:function(){var a,c,d;if(b.call(this),!this.isStopped){this.isStopped=!0;var e=this.observers.slice(0),f=this.value,g=this.hasValue;if(g)for(c=0,d=e.length;d>c;c++)a=e[c],a.onNext(f),a.onCompleted();else for(c=0,d=e.length;d>c;c++)e[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){b.call(this),this.isStopped||(this.value=a,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),d}(ac),Ec=M.AnonymousSubject=function(a){function b(b,c){this.observer=b,this.observable=c,a.call(this,this.observable.subscribe.bind(this.observable))}return ub(b,a),vb(b.prototype,Xb,{onCompleted:function(){this.observer.onCompleted()},onError:function(a){this.observer.onError(a)},onNext:function(a){this.observer.onNext(a)}}),b}(ac),Fc=M.BehaviorSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),a.onNext(this.value),new Bc(this,a);var c=this.exception;return c?a.onError(c):a.onCompleted(),Fb}function d(b){a.call(this,c),this.value=b,this.observers=[],this.isDisposed=!1,this.isStopped=!1,this.exception=null}return ub(d,a),vb(d.prototype,Xb,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped){this.value=a;for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)}},dispose:function(){this.isDisposed=!0,this.observers=null,this.value=null,this.exception=null}}),d}(ac),Gc=M.ReplaySubject=function(a){function c(a,b){this.subject=a,this.observer=b}function d(a){var d=new bc(this.scheduler,a),e=new c(this,d);b.call(this),this._trim(this.scheduler.now()),this.observers.push(d);for(var f=this.q.length,g=0,h=this.q.length;h>g;g++)d.onNext(this.q[g].value);return this.hasError?(f++,d.onError(this.error)):this.isStopped&&(f++,d.onCompleted()),d.ensureActive(f),e}function e(b,c,e){this.bufferSize=null==b?Number.MAX_VALUE:b,this.windowSize=null==c?Number.MAX_VALUE:c,this.scheduler=e||Mb,this.q=[],this.observers=[],this.isStopped=!1,this.isDisposed=!1,this.hasError=!1,this.error=null,a.call(this,d)}return c.prototype.dispose=function(){if(this.observer.dispose(),!this.subject.isDisposed){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1)}},ub(e,a),vb(e.prototype,Xb,{hasObservers:function(){return this.observers.length>0},_trim:function(a){for(;this.q.length>this.bufferSize;)this.q.shift();for(;this.q.length>0&&a-this.q[0].interval>this.windowSize;)this.q.shift()},onNext:function(a){var c;if(b.call(this),!this.isStopped){var d=this.scheduler.now();this.q.push({interval:d,value:a}),this._trim(d);for(var e=this.observers.slice(0),f=0,g=e.length;g>f;f++)c=e[f],c.onNext(a),c.ensureActive()}},onError:function(a){var c;if(b.call(this),!this.isStopped){this.isStopped=!0,this.error=a,this.hasError=!0;var d=this.scheduler.now();this._trim(d);for(var e=this.observers.slice(0),f=0,g=e.length;g>f;f++)c=e[f],c.onError(a),c.ensureActive();this.observers=[]}},onCompleted:function(){var a;if(b.call(this),!this.isStopped){this.isStopped=!0;var c=this.scheduler.now();this._trim(c);for(var d=this.observers.slice(0),e=0,f=d.length;f>e;e++)a=d[e],a.onCompleted(),a.ensureActive();this.observers=[]}},dispose:function(){this.isDisposed=!0,this.observers=null}}),e}(ac);"function"==typeof define&&"object"==typeof define.amd&&define.amd?(H.Rx=M,define(function(){return M})):I&&J?K?(J.exports=M).Rx=M:I.Rx=M:H.Rx=M}).call(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.lite.extras.js b/ajax/libs/rxjs/2.3.9/rx.lite.extras.js new file mode 100644 index 000000000..11c718ce1 --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.lite.extras.js @@ -0,0 +1,592 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // References + var Observable = Rx.Observable, + observableProto = Observable.prototype, + observableNever = Observable.never, + observableThrow = Observable.throwException, + AnonymousObservable = Rx.AnonymousObservable, + Observer = Rx.Observer, + Subject = Rx.Subject, + internals = Rx.internals, + helpers = Rx.helpers, + ScheduledObserver = internals.ScheduledObserver, + SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, + CompositeDisposable = Rx.CompositeDisposable, + RefCountDisposable = Rx.RefCountDisposable, + disposableEmpty = Rx.Disposable.empty, + immediateScheduler = Rx.Scheduler.immediate, + defaultKeySerializer = helpers.defaultKeySerializer, + addRef = Rx.internals.addRef, + identity = helpers.identity, + isPromise = helpers.isPromise, + inherits = internals.inherits, + noop = helpers.noop, + isScheduler = helpers.isScheduler, + observableFromPromise = Observable.fromPromise, + slice = Array.prototype.slice; + + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + + var argumentOutOfRange = 'Argument out of range'; + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + var CheckedObserver = (function (_super) { + inherits(CheckedObserver, _super); + + function CheckedObserver(observer) { + _super.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + try { + this._observer.onNext(value); + } catch (e) { + throw e; + } finally { + this._state = 0; + } + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + try { + this._observer.onError(err); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + try { + this._observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + /** @private */ + var ObserveOnObserver = (function (_super) { + inherits(ObserveOnObserver, _super); + + /** @private */ + function ObserveOnObserver() { + _super.apply(this, arguments); + } + + /** @private */ + ObserveOnObserver.prototype.next = function (value) { + _super.prototype.next.call(this, value); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.error = function (e) { + _super.prototype.error.call(this, e); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.completed = function () { + _super.prototype.completed.call(this); + this.ensureActive(); + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + /** + * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + * + * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects + * that require to be run on a scheduler, use subscribeOn. + * + * @param {Scheduler} scheduler Scheduler to notify observers on. + * @returns {Observable} The source sequence whose observations happen on the specified scheduler. + */ + observableProto.observeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(new ObserveOnObserver(scheduler, observer)); + }); + }; + + /** + * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; + * see the remarks section for more information on the distinction between subscribeOn and observeOn. + + * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer + * callbacks on a scheduler, use observeOn. + + * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. + * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); + d.setDisposable(m); + m.setDisposable(scheduler.schedule(function () { + d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); + })); + return d; + }); + }; + + /** + * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. + * @returns {Observable} The generated sequence. + */ + Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var first = true, state = initialState; + return scheduler.scheduleRecursive(function (self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + } + } catch (exception) { + observer.onError(exception); + return; + } + if (hasResult) { + observer.onNext(result); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. + * + * @example + * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); + * @param {Function} resourceFactory Factory function to obtain a resource object. + * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. + * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. + */ + Observable.using = function (resourceFactory, observableFactory) { + return new AnonymousObservable(function (observer) { + var disposable = disposableEmpty, resource, source; + try { + resource = resourceFactory(); + if (resource) { + disposable = resource; + } + source = observableFactory(resource); + } catch (exception) { + return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); + } + return new CompositeDisposable(source.subscribe(observer), disposable); + }); + }; + + /** + * Propagates the observable sequence or Promise that reacts first. + * @param {Observable} rightSource Second observable sequence or Promise. + * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. + */ + observableProto.amb = function (rightSource) { + var leftSource = this; + return new AnonymousObservable(function (observer) { + var choice, + leftChoice = 'L', rightChoice = 'R', + leftSubscription = new SingleAssignmentDisposable(), + rightSubscription = new SingleAssignmentDisposable(); + + isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); + + function choiceL() { + if (!choice) { + choice = leftChoice; + rightSubscription.dispose(); + } + } + + function choiceR() { + if (!choice) { + choice = rightChoice; + leftSubscription.dispose(); + } + } + + leftSubscription.setDisposable(leftSource.subscribe(function (left) { + choiceL(); + if (choice === leftChoice) { + observer.onNext(left); + } + }, function (err) { + choiceL(); + if (choice === leftChoice) { + observer.onError(err); + } + }, function () { + choiceL(); + if (choice === leftChoice) { + observer.onCompleted(); + } + })); + + rightSubscription.setDisposable(rightSource.subscribe(function (right) { + choiceR(); + if (choice === rightChoice) { + observer.onNext(right); + } + }, function (err) { + choiceR(); + if (choice === rightChoice) { + observer.onError(err); + } + }, function () { + choiceR(); + if (choice === rightChoice) { + observer.onCompleted(); + } + })); + + return new CompositeDisposable(leftSubscription, rightSubscription); + }); + }; + + /** + * Propagates the observable sequence or Promise that reacts first. + * + * @example + * var = Rx.Observable.amb(xs, ys, zs); + * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. + */ + Observable.amb = function () { + var acc = observableNever(), + items = argsOrArray(arguments, 0); + function func(previous, current) { + return previous.amb(current); + } + for (var i = 0, len = items.length; i < len; i++) { + acc = func(acc, items[i]); + } + return acc; + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. + * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. + */ + observableProto.onErrorResumeNext = function (second) { + if (!second) { + throw new Error('Second observable is required'); + } + return onErrorResumeNext([this, second]); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * + * @example + * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); + * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); + * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. + */ + var onErrorResumeNext = Observable.onErrorResumeNext = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var pos = 0, subscription = new SerialDisposable(), + cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, d; + if (pos < sources.length) { + current = sources[pos++]; + isPromise(current) && (current = observableFromPromise(current)); + d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { + self(); + }, function () { + self(); + })); + } else { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. + * + * @example + * var res = xs.bufferWithCount(10); + * var res = xs.bufferWithCount(10, 1); + * @param {Number} count Length of each buffer. + * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithCount = function (count, skip) { + if (typeof skip !== 'number') { + skip = count; + } + return this.windowWithCount(count, skip).selectMany(function (x) { + return x.toArray(); + }).where(function (x) { + return x.length > 0; + }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. + * + * var res = xs.windowWithCount(10); + * var res = xs.windowWithCount(10, 1); + * @param {Number} count Length of each window. + * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithCount = function (count, skip) { + var source = this; + if (count <= 0) { + throw new Error(argumentOutOfRange); + } + if (arguments.length === 1) { + skip = count; + } + if (skip <= 0) { + throw new Error(argumentOutOfRange); + } + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), + refCountDisposable = new RefCountDisposable(m), + n = 0, + q = [], + createWindow = function () { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + }; + createWindow(); + m.setDisposable(source.subscribe(function (x) { + var s; + for (var i = 0, len = q.length; i < len; i++) { + q[i].onNext(x); + } + var c = n - count + 1; + if (c >= 0 && c % skip === 0) { + s = q.shift(); + s.onCompleted(); + } + n++; + if (n % skip === 0) { + createWindow(); + } + }, function (exception) { + while (q.length > 0) { + q.shift().onError(exception); + } + observer.onError(exception); + }, function () { + while (q.length > 0) { + q.shift().onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, observer.onError.bind(observer), function () { + observer.onNext(q); + observer.onCompleted(); + }); + }); + }; + + /** + * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * var res = obs = xs.defaultIfEmpty(); + * 2 - obs = xs.defaultIfEmpty(false); + * + * @memberOf Observable# + * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. + * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. + */ + observableProto.defaultIfEmpty = function (defaultValue) { + var source = this; + if (defaultValue === undefined) { + defaultValue = null; + } + return new AnonymousObservable(function (observer) { + var found = false; + return source.subscribe(function (x) { + found = true; + observer.onNext(x); + }, observer.onError.bind(observer), function () { + if (!found) { + observer.onNext(defaultValue); + } + observer.onCompleted(); + }); + }); + }; + + // Swap out for Array.findIndex + function arrayIndexOfComparer(array, item, comparer) { + for (var i = 0, len = array.length; i < len; i++) { + if (comparer(array[i], item)) { return i; } + } + return -1; + } + + function HashSet(comparer) { + this.comparer = comparer; + this.set = []; + } + HashSet.prototype.push = function(value) { + var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; + retValue && this.set.push(value); + return retValue; + }; + + /** + * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. + * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. + * + * @example + * var res = obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [comparer] Used to compare items in the collection. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, comparer) { + var source = this; + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hashSet = new HashSet(comparer); + return source.subscribe(function (x) { + var key = x; + + if (keySelector) { + try { + key = keySelector(x); + } catch (e) { + observer.onError(e); + return; + } + } + hashSet.push(key) && observer.onNext(x); + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer)); + }); + }; + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.lite.extras.min.js b/ajax/libs/rxjs/2.3.9/rx.lite.extras.min.js new file mode 100644 index 000000000..9f9fab9ab --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.lite.extras.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c,d){function e(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:C.call(a)}function f(a,b){this.scheduler=a,this.disposable=b,this.isDisposed=!1}function g(a,b,c){for(var d=0,e=a.length;e>d;d++)if(c(a[d],b))return d;return-1}function h(a){this.comparer=a,this.set=[]}var i=c.Observable,j=i.prototype,k=i.never,l=i.throwException,m=c.AnonymousObservable,n=c.Observer,o=c.Subject,p=c.internals,q=c.helpers,r=p.ScheduledObserver,s=c.SingleAssignmentDisposable,t=c.CompositeDisposable,u=c.RefCountDisposable,v=c.Disposable.empty,w=c.Scheduler.immediate,x=(q.defaultKeySerializer,c.internals.addRef),y=(q.identity,q.isPromise),z=p.inherits,A=(q.noop,q.isScheduler),B=i.fromPromise,C=Array.prototype.slice,D="Argument out of range";f.prototype.dispose=function(){var a=this;this.scheduler.schedule(function(){a.isDisposed||(a.isDisposed=!0,a.disposable.dispose())})};var E=(function(a){function b(b){a.call(this),this._observer=b,this._state=0}z(b,a);var c=b.prototype;return c.onNext=function(a){this.checkAccess();try{this._observer.onNext(a)}catch(b){throw b}finally{this._state=0}},c.onError=function(a){this.checkAccess();try{this._observer.onError(a)}catch(b){throw b}finally{this._state=2}},c.onCompleted=function(){this.checkAccess();try{this._observer.onCompleted()}catch(a){throw a}finally{this._state=2}},c.checkAccess=function(){if(1===this._state)throw new Error("Re-entrancy detected");if(2===this._state)throw new Error("Observer completed");0===this._state&&(this._state=1)},b}(n),function(a){function b(){a.apply(this,arguments)}return z(b,a),b.prototype.next=function(b){a.prototype.next.call(this,b),this.ensureActive()},b.prototype.error=function(b){a.prototype.error.call(this,b),this.ensureActive()},b.prototype.completed=function(){a.prototype.completed.call(this),this.ensureActive()},b}(r));j.observeOn=function(a){var b=this;return new m(function(c){return b.subscribe(new E(a,c))})},j.subscribeOn=function(a){var b=this;return new m(function(c){var d=new s,e=new SerialDisposable;return e.setDisposable(d),d.setDisposable(a.schedule(function(){e.setDisposable(new f(a,b.subscribe(c)))})),e})},i.generate=function(a,b,c,d,e){return A(e)||(e=currentThreadScheduler),new m(function(f){var g=!0,h=a;return e.scheduleRecursive(function(a){var e,i;try{g?g=!1:h=c(h),e=b(h),e&&(i=d(h))}catch(j){return void f.onError(j)}e?(f.onNext(i),a()):f.onCompleted()})})},i.using=function(a,b){return new m(function(c){var d,e,f=v;try{d=a(),d&&(f=d),e=b(d)}catch(g){return new t(l(g).subscribe(c),f)}return new t(e.subscribe(c),f)})},j.amb=function(a){var b=this;return new m(function(c){function d(){f||(f=g,j.dispose())}function e(){f||(f=h,i.dispose())}var f,g="L",h="R",i=new s,j=new s;return y(a)&&(a=B(a)),i.setDisposable(b.subscribe(function(a){d(),f===g&&c.onNext(a)},function(a){d(),f===g&&c.onError(a)},function(){d(),f===g&&c.onCompleted()})),j.setDisposable(a.subscribe(function(a){e(),f===h&&c.onNext(a)},function(a){e(),f===h&&c.onError(a)},function(){e(),f===h&&c.onCompleted()})),new t(i,j)})},i.amb=function(){function a(a,b){return a.amb(b)}for(var b=k(),c=e(arguments,0),d=0,f=c.length;f>d;d++)b=a(b,c[d]);return b},j.onErrorResumeNext=function(a){if(!a)throw new Error("Second observable is required");return F([this,a])};var F=i.onErrorResumeNext=function(){var a=e(arguments,0);return new m(function(b){var c=0,d=new SerialDisposable,e=w.scheduleRecursive(function(e){var f,g;c0})},j.windowWithCount=function(a,b){var c=this;if(0>=a)throw new Error(D);if(1===arguments.length&&(b=a),0>=b)throw new Error(D);return new m(function(d){var e=new s,f=new u(e),g=0,h=[],i=function(){var a=new o;h.push(a),d.onNext(x(a,f))};return i(),e.setDisposable(c.subscribe(function(c){for(var d,e=0,f=h.length;f>e;e++)h[e].onNext(c);var j=g-a+1;j>=0&&j%b===0&&(d=h.shift(),d.onCompleted()),g++,g%b===0&&i()},function(a){for(;h.length>0;)h.shift().onError(a);d.onError(a)},function(){for(;h.length>0;)h.shift().onCompleted();d.onCompleted()})),f})},j.takeLastBuffer=function(a){var b=this;return new m(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&d.shift()},c.onError.bind(c),function(){c.onNext(d),c.onCompleted()})})},j.defaultIfEmpty=function(a){var b=this;return a===d&&(a=null),new m(function(c){var d=!1;return b.subscribe(function(a){d=!0,c.onNext(a)},c.onError.bind(c),function(){d||c.onNext(a),c.onCompleted()})})},h.prototype.push=function(a){var b=-1===g(this.set,a,this.comparer);return b&&this.set.push(a),b},j.distinct=function(a,b){var c=this;return b||(b=defaultComparer),new m(function(d){var e=new h(b);return c.subscribe(function(b){var c=b;if(a)try{c=a(b)}catch(f){return void d.onError(f)}e.push(c)&&d.onNext(b)},d.onError.bind(d),d.onCompleted.bind(d))})},c}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.lite.js b/ajax/libs/rxjs/2.3.9/rx.lite.js new file mode 100644 index 000000000..a2ff81b17 --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.lite.js @@ -0,0 +1,5508 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { + + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, + isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = Date.now, + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || + '_es6shim_iterator_'; + // Bug for mozilla version + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { + return; + } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { + return; + } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = + SerialDisposable = Rx.SerialDisposable = (function () { + function BooleanDisposable () { + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + old && old.dispose(); + shouldDispose && value && value.dispose(); + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + old && old.dispose(); + }; + + return BooleanDisposable; + }()); + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + timeSpan < 0 && (timeSpan = 0); + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + (function (schedulerProto) { + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function scheduleInnerRecursive(action, self) { + action(function(dt) { self(action, dt); }); + } + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { self(_action); }); }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + }(Scheduler.prototype)); + + (function (schedulerProto) { + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, action); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var s = state; + + var id = setInterval(function () { + s = action(s); + }, period); + + return disposableCreate(function () { + clearInterval(id); + }); + }; + }(Scheduler.prototype)); + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt); + + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + + currentScheduler.scheduleRequired = function () { return !queue; }; + currentScheduler.ensureTrampoline = function (action) { + if (!queue) { this.schedule(action); } else { action(); } + }; + + return currentScheduler; + }()); + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, + dt = Scheduler.normalize(dueTime); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { + return observerOrOnNext && typeof observerOrOnNext === 'object' ? + this._acceptObservable(observerOrOnNext) : + this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notifications + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + Notification.prototype.toObservable = function (scheduler) { + var notification = this; + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + notification.kind === 'N' && observer.onCompleted(); + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + + function _accept (onNext) { return onNext(this.value); } + function _acceptObservable(observer) { return observer.onNext(this.value); } + function toString () { return 'OnNext(' + this.value + ')'; } + + return function (value) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + + function _accept (onNext, onError) { return onError(this.exception); } + function _acceptObservable(observer) { return observer.onError(this.exception); } + function toString () { return 'OnError(' + this.exception + ')'; } + + return function (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { return onCompleted(); } + function _acceptObservable(observer) { return observer.onCompleted(); } + function toString () { return 'OnCompleted()'; } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber = typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted); + + return this._subscribe(subscriber); + }; + + return Observable; + })(); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { + inherits(ScheduledObserver, _super); + + function ScheduledObserver(scheduler, observer) { + _super.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + /** + * Creates a list from an observable sequence. + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + var self = this; + return new AnonymousObservable(function(observer) { + var arr = []; + return self.subscribe( + arr.push.bind(arr), + observer.onError.bind(observer), + function () { + observer.onNext(arr); + observer.onCompleted(); + }); + }); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.create = Observable.createWithDisposable = function (subscribe) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + var maxSafeInteger = Math.pow(2, 53) - 1; + + function numberIsFinite(value) { + return typeof value === 'number' && root.isFinite(value); + } + + function isNan(n) { + return n !== n; + } + + function isIterable(o) { + return o[$iterator$] !== undefined; + } + + function sign(value) { + var number = +value; + if (number === 0) { return number; } + if (isNaN(number)) { return number; } + return number < 0 ? -1 : 1; + } + + function toLength(o) { + var len = +o.length; + if (isNaN(len)) { return 0; } + if (len === 0 || !numberIsFinite(len)) { return len; } + len = sign(len) * Math.floor(Math.abs(len)); + if (len <= 0) { return 0; } + if (len > maxSafeInteger) { return maxSafeInteger; } + return len; + } + + function isCallable(f) { + return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; + } + + /** + * This method creates a new Observable sequence from an array-like or iterable object. + * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. + * @param {Function} [mapFn] Map function to call on every element of the array. + * @param {Any} [thisArg] The context to use calling the mapFn if provided. + * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + Observable.from = function (iterable, mapFn, thisArg, scheduler) { + if (iterable == null) { + throw new Error('iterable cannot be null.') + } + if (mapFn && !isCallable(mapFn)) { + throw new Error('mapFn when provided must be a function'); + } + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var list = Object(iterable), + objIsIterable = isIterable(list), + len = objIsIterable ? 0 : toLength(list), + it = objIsIterable ? list[$iterator$]() : null, + i = 0; + return scheduler.scheduleRecursive(function (self) { + if (i < len || objIsIterable) { + var result; + if (objIsIterable) { + var next = it.next(); + if (next.done) { + observer.onCompleted(); + return; + } + + result = next.value; + } else { + result = list[i]; + } + + if (mapFn && isCallable(mapFn)) { + try { + result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); + } catch (e) { + observer.onError(e); + return; + } + } + + observer.onNext(result); + i++; + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * var res = Rx.Observable.fromArray([1,2,3]); + * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0, len = array.length; + return scheduler.scheduleRecursive(function (self) { + if (count < len) { + observer.onNext(array[count++]); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). + * @returns {Observable} An observable sequence whose observers will never get called. + */ + var observableNever = Observable.never = function () { + return new AnonymousObservable(function () { + return disposableEmpty; + }); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.of = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return observableFromArray(args); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + var observableOf = Observable.ofWithScheduler = function (scheduler) { + var len = arguments.length - 1, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } + return observableFromArray(args, scheduler); + }; + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.range(0, 10); + * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleRecursiveWithState(0, function (i, self) { + if (i < count) { + observer.onNext(start + i); + self(i + 1); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.repeat(42); + * var res = Rx.Observable.repeat(42, 4); + * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'just', and 'returnValue' for browsers 0) { + subscribe(q.shift()); + } else { + activeCount--; + isStopped && activeCount === 0 && observer.onCompleted(); + } + })); + } + group.add(sources.subscribe(function (innerSource) { + if (activeCount < maxConcurrentOrOther) { + activeCount++; + subscribe(innerSource); + } else { + q.push(innerSource); + } + }, observer.onError.bind(observer), function () { + isStopped = true; + activeCount === 0 && observer.onCompleted(); + })); + return group; + }); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * + * @example + * 1 - merged = Rx.Observable.merge(xs, ys, zs); + * 2 - merged = Rx.Observable.merge([xs, ys, zs]); + * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); + * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources; + if (!arguments[0]) { + scheduler = immediateScheduler; + sources = slice.call(arguments, 1); + } else if (arguments[0].now) { + scheduler = arguments[0]; + sources = slice.call(arguments, 1); + } else { + scheduler = immediateScheduler; + sources = slice.call(arguments, 0); + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableFromArray(sources, scheduler).mergeObservable(); + }; + + /** + * Merges an observable sequence of observable sequences into an observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.mergeObservable = observableProto.mergeAll =function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + isStopped = false, + m = new SingleAssignmentDisposable(); + + group.add(m); + m.setDisposable(sources.subscribe(function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + innerSubscription.setDisposable(innerSource.subscribe(function (x) { + observer.onNext(x); + }, observer.onError.bind(observer), function () { + group.remove(innerSubscription); + if (isStopped && group.length === 1) { observer.onCompleted(); } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (group.length === 1) { observer.onCompleted(); } + })); + return group; + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + isOpen && observer.onNext(left); + }, observer.onError.bind(observer), function () { + isOpen && observer.onCompleted(); + })); + + isPromise(other) && (other = observableFromPromise(other)); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, observer.onError.bind(observer), function () { + rightSubscription.dispose(); + })); + + return disposables; + }); + }; + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasLatest = false, + innerSubscription = new SerialDisposable(), + isStopped = false, + latest = 0, + subscription = sources.subscribe(function (innerSource) { + var d = new SingleAssignmentDisposable(), id = ++latest; + hasLatest = true; + innerSubscription.setDisposable(d); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + d.setDisposable(innerSource.subscribe(function (x) { + if (latest === id) { + observer.onNext(x); + } + }, function (e) { + if (latest === id) { + observer.onError(e); + } + }, function () { + if (latest === id) { + hasLatest = false; + if (isStopped) { + observer.onCompleted(); + } + } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (!hasLatest) { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, innerSubscription); + }); + }; + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + isPromise(other) && (other = observableFromPromise(other)); + return new CompositeDisposable( + source.subscribe(observer), + other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) + ); + }); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], result; + try { + result = resultSelector(left, right); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + } else { + observer.onCompleted(); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. + * + * @example + * 1 - res = obs1.zip(obs2, fn); + * 1 - res = x1.zip([1,2,3], fn); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { + return zipArray.apply(this, arguments); + } + var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); + sources.unshift(parent); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + var res, queuedValues; + if (queues.every(function (x) { return x.length > 0; })) { + try { + queuedValues = queues.map(function (x) { return x.shift(); }); + res = resultSelector.apply(parent, queuedValues); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(function (x) { return x; })) { + observer.onCompleted(); + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = sources[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + * @param arguments Observable sources. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var args = slice.call(arguments, 0), + first = args.shift(); + return first.zip.apply(first, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + return; + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(identity)) { + observer.onCompleted(); + return; + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + })(idx); + } + + var compositeDisposable = new CompositeDisposable(subscriptions); + compositeDisposable.add(disposableCreate(function () { + for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { + queues[qIdx] = []; + } + })); + return compositeDisposable; + }); + }; + + /** + * Hides the identity of an observable sequence. + * @returns {Observable} An observable sequence that hides the identity of the source sequence. + */ + observableProto.asObservable = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(observer); + }); + }; + + /** + * Dematerializes the explicit notification values of an observable sequence as implicit notifications. + * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + return x.accept(observer); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + * + * var obs = observable.distinctUntilChanged(); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. + * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. + * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + observableProto.distinctUntilChanged = function (keySelector, comparer) { + var source = this; + keySelector || (keySelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var comparerEquals = false, key; + try { + key = keySelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + if (hasCurrentKey) { + try { + comparerEquals = comparer(currentKey, key); + } catch (exception) { + observer.onError(exception); + return; + } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + observer.onNext(value); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * + * @example + * var res = observable.do(observer); + * var res = observable.do(onNext); + * var res = observable.do(onNext, onError); + * var res = observable.do(onNext, onError, onCompleted); + * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { + var source = this, onNextFunc; + if (typeof observerOrOnNext === 'function') { + onNextFunc = observerOrOnNext; + } else { + onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); + onError = observerOrOnNext.onError.bind(observerOrOnNext); + onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); + } + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + try { + onNextFunc(x); + } catch (e) { + observer.onError(e); + } + observer.onNext(x); + }, function (err) { + if (!onError) { + observer.onError(err); + } else { + try { + onError(err); + } catch (e) { + observer.onError(e); + } + observer.onError(err); + } + }, function () { + if (!onCompleted) { + observer.onCompleted(); + } else { + try { + onCompleted(); + } catch (e) { + observer.onError(e); + } + observer.onCompleted(); + } + }); + }); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * + * @example + * var res = observable.finallyAction(function () { console.log('sequence ended'; }); + * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. + * @returns {Observable} Source sequence with the action-invoking termination behavior applied. + */ + observableProto['finally'] = observableProto.finallyAction = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription; + try { + subscription = source.subscribe(observer); + } catch (e) { + action(); + throw e; + } + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Materializes the implicit notifications of an observable sequence as explicit notification values. + * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. + */ + observableProto.materialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (value) { + observer.onNext(notificationCreateOnNext(value)); + }, function (e) { + observer.onNext(notificationCreateOnError(e)); + observer.onCompleted(); + }, function () { + observer.onNext(notificationCreateOnCompleted()); + observer.onCompleted(); + }); + }); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * + * @example + * var res = repeated = source.repeat(); + * var res = repeated = source.repeat(42); + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + observableProto.repeat = function (repeatCount) { + return enumerableRepeat(this, repeatCount).concat(); + }; + + /** + * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. + * Note if you encounter an error and want it to retry once, then you must use .retry(2); + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(2); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchException(); + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @example + * var res = source.scan(function (acc, x) { return acc + x; }); + * var res = source.scan(0, function (acc, x) { return acc + x; }); + * @param {Mixed} [seed] The initial accumulator value. + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @returns {Observable} An observable sequence containing the accumulated values. + */ + observableProto.scan = function () { + var hasSeed = false, seed, accumulator, source = this; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[0]; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return new AnonymousObservable(function (observer) { + var hasAccumulation, accumulation, hasValue; + return source.subscribe ( + function (x) { + try { + if (!hasValue) { + hasValue = true; + } + + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(accumulation); + }, + observer.onError.bind(observer), + function () { + if (!hasValue && hasSeed) { + observer.onNext(seed); + } + observer.onCompleted(); + } + ); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + observer.onNext(q.shift()); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * + * @memberOf Observable# + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && 'now' in Object(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + values = slice.call(arguments, start); + return enumerableFor([observableFromArray(values, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence. + * + * @example + * var res = source.takeLast(5); + * + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, observer.onError.bind(observer), function () { + while(q.length > 0) { observer.onNext(q.shift()); } + observer.onCompleted(); + }); + }); + }; + + function concatMap(source, selector, thisArg) { + return source.map(function (x, i) { + var result = selector.call(thisArg, x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).concatAll(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { + if (resultSelector) { + return this.concatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }); + } + return typeof selector === 'function' ? + concatMap(this, selector, thisArg) : + concatMap(this, function () { return selector; }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + observableProto.select = observableProto.map = function (selector, thisArg) { + var parent = this; + return new AnonymousObservable(function (observer) { + var count = 0; + return parent.subscribe(function (value) { + var result; + try { + result = selector.call(thisArg, value, count++, parent); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Retrieves the value of a specified property from all elements in the Observable sequence. + * @param {String} property The property to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function (property) { + return this.select(function (x) { return x[property]; }); + }; + + function flatMap(source, selector, thisArg) { + return source.map(function (x, i) { + var result = selector.call(thisArg, x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).mergeObservable(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { + if (resultSelector) { + return this.flatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }, thisArg); + } + return typeof selector === 'function' ? + flatMap(this, selector, thisArg) : + flatMap(this, function () { return selector; }); + }; + + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { + throw new Error(argumentOutOfRange); + } + var observable = this; + return new AnonymousObservable(function (observer) { + var remaining = count; + return observable.subscribe(function (x) { + if (remaining <= 0) { + observer.onNext(x); + } else { + remaining--; + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + * The element's index is used in the logic of the predicate function. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !predicate.call(thisArg, x, i++, source); + } catch (e) { + observer.onError(e); + return; + } + } + if (running) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case 0) { + var now = scheduler.now(); + d = d + p; + d <= now && (d = now + p); + } + observer.onNext(count++); + self(d); + }); + }); + } + + function observableTimerTimeSpan(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { + return dueTime === period ? + new AnonymousObservable(function (observer) { + return scheduler.schedulePeriodicWithState(0, period, function (count) { + observer.onNext(count); + return count + 1; + }); + }) : + observableDefer(function () { + return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); + }); + } + + /** + * Returns an observable sequence that produces a value after each period. + * + * @example + * 1 - res = Rx.Observable.interval(1000); + * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); + * + * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. + * @returns {Observable} An observable sequence that produces a value after each period. + */ + var observableinterval = Observable.interval = function (period, scheduler) { + return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); + }; + + /** + * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. + * + * @example + * 1 - res = Rx.Observable.timer(new Date()); + * 2 - res = Rx.Observable.timer(new Date(), 1000); + * 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout); + * + * 5 - res = Rx.Observable.timer(5000); + * 6 - res = Rx.Observable.timer(5000, 1000); + * 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); + * 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. + * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. + */ + var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { + var period; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { + period = periodOrScheduler; + } else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') { + scheduler = periodOrScheduler; + } + if (dueTime instanceof Date && period === undefined) { + return observableTimerDate(dueTime.getTime(), scheduler); + } + if (dueTime instanceof Date && period !== undefined) { + period = periodOrScheduler; + return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); + } + return period === undefined ? + observableTimerTimeSpan(dueTime, scheduler) : + observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); + }; + + function observableDelayTimeSpan(source, dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + var active = false, + cancelable = new SerialDisposable(), + exception = null, + q = [], + running = false, + subscription; + subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { + var d, shouldRun; + if (notification.value.kind === 'E') { + q = []; + q.push(notification); + exception = notification.value.exception; + shouldRun = !running; + } else { + q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); + shouldRun = !active; + active = true; + } + if (shouldRun) { + if (exception !== null) { + observer.onError(exception); + } else { + d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { + var e, recurseDueTime, result, shouldRecurse; + if (exception !== null) { + return; + } + running = true; + do { + result = null; + if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { + result = q.shift().value; + } + if (result !== null) { + result.accept(observer); + } + } while (result !== null); + shouldRecurse = false; + recurseDueTime = 0; + if (q.length > 0) { + shouldRecurse = true; + recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); + } else { + active = false; + } + e = exception; + running = false; + if (e !== null) { + observer.onError(e); + } else if (shouldRecurse) { + self(recurseDueTime); + } + })); + } + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + } + + function observableDelayDate(source, dueTime, scheduler) { + return observableDefer(function () { + return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); + }); + } + + /** + * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. + * + * @example + * 1 - res = Rx.Observable.delay(new Date()); + * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); + * + * 3 - res = Rx.Observable.delay(5000); + * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); + * @memberOf Observable# + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. + * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delay = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return dueTime instanceof Date ? + observableDelayDate(this, dueTime.getTime(), scheduler) : + observableDelayTimeSpan(this, dueTime, scheduler); + }; + + /** + * Ignores values from an observable sequence which are followed by another value before dueTime. + * + * @example + * 1 - res = source.throttle(5000); // 5 seconds + * 2 - res = source.throttle(5000, scheduler); + * + * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttle = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) + }; + + /** + * Records the timestamp for each value in an observable sequence. + * + * @example + * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } + * 2 - res = source.timestamp(Rx.Scheduler.timeout); + * + * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with timestamp information on values. + */ + observableProto.timestamp = function (scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return this.map(function (x) { + return { value: x, timestamp: scheduler.now() }; + }); + }; + + function sampleObservable(source, sampler) { + + return new AnonymousObservable(function (observer) { + var atEnd, value, hasValue; + + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + observer.onNext(value); + } + atEnd && observer.onCompleted(); + } + + return new CompositeDisposable( + source.subscribe(function (newValue) { + hasValue = true; + value = newValue; + }, observer.onError.bind(observer), function () { + atEnd = true; + }), + sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) + ); + }); + } + + /** + * Samples the observable sequence at each interval. + * + * @example + * 1 - res = source.sample(sampleObservable); // Sampler tick sequence + * 2 - res = source.sample(5000); // 5 seconds + * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. + * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Sampled observable sequence. + */ + observableProto.sample = function (intervalOrSampler, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return typeof intervalOrSampler === 'number' ? + sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : + sampleObservable(this, intervalOrSampler); + }; + + /** + * Returns the source observable sequence or the other observable sequence if dueTime elapses. + * + * @example + * 1 - res = source.timeout(new Date()); // As a date + * 2 - res = source.timeout(5000); // 5 seconds + * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable + * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable + * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable + * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. + * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. + * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeout = function (dueTime, other, scheduler) { + other || (other = observableThrow(new Error('Timeout'))); + isScheduler(scheduler) || (scheduler = timeoutScheduler); + + var source = this, schedulerMethod = dueTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + + return new AnonymousObservable(function (observer) { + var id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + + subscription.setDisposable(original); + + var createTimer = function () { + var myId = id; + timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { + if (id === myId) { + isPromise(other) && (other = observableFromPromise(other)); + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + createTimer(); + + original.setDisposable(source.subscribe(function (x) { + if (!switched) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + if (!switched) { + id++; + observer.onError(e); + } + }, function () { + if (!switched) { + id++; + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Time shifts the observable sequence by delaying the subscription. + * + * @example + * 1 - res = source.delaySubscription(5000); // 5s + * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Number} dueTime Absolute or relative time to perform the subscription at. + * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delaySubscription = function (dueTime, scheduler) { + return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty); + }; + + /** + * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only + * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector + * + * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. + * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { + var source = this, subDelay, selector; + if (typeof subscriptionDelay === 'function') { + selector = subscriptionDelay; + } else { + subDelay = subscriptionDelay; + selector = delayDurationSelector; + } + return new AnonymousObservable(function (observer) { + var delays = new CompositeDisposable(), atEnd = false, done = function () { + if (atEnd && delays.length === 0) { + observer.onCompleted(); + } + }, subscription = new SerialDisposable(), start = function () { + subscription.setDisposable(source.subscribe(function (x) { + var delay; + try { + delay = selector(x); + } catch (error) { + observer.onError(error); + return; + } + var d = new SingleAssignmentDisposable(); + delays.add(d); + d.setDisposable(delay.subscribe(function () { + observer.onNext(x); + delays.remove(d); + done(); + }, observer.onError.bind(observer), function () { + observer.onNext(x); + delays.remove(d); + done(); + })); + }, observer.onError.bind(observer), function () { + atEnd = true; + subscription.dispose(); + done(); + })); + }; + + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(function () { + start(); + }, observer.onError.bind(observer), function () { start(); })); + } + + return new CompositeDisposable(subscription, delays); + }); + }; + + /** + * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. + * + * @example + * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); + * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); + * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); + * + * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). + * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. + * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { + if (arguments.length === 1) { + timeoutdurationSelector = firstTimeout; + var firstTimeout = observableNever(); + } + other || (other = observableThrow(new Error('Timeout'))); + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); + + subscription.setDisposable(original); + + var id = 0, switched = false, setTimer = function (timeout) { + var myId = id, timerWins = function () { + return id === myId; + }; + var d = new SingleAssignmentDisposable(); + timer.setDisposable(d); + d.setDisposable(timeout.subscribe(function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + d.dispose(); + }, function (e) { + if (timerWins()) { + observer.onError(e); + } + }, function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + setTimer(firstTimeout); + var observerWins = function () { + var res = !switched; + if (res) { + id++; + } + return res; + }; + + original.setDisposable(source.subscribe(function (x) { + if (observerWins()) { + observer.onNext(x); + var timeout; + try { + timeout = timeoutdurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + setTimer(timeout); + } + }, function (e) { + if (observerWins()) { + observer.onError(e); + } + }, function () { + if (observerWins()) { + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); + * + * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttleWithSelector = function (throttleDurationSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { + var throttle; + try { + throttle = throttleDurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + hasValue = true; + value = x; + id++; + var currentid = id, d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(throttle.subscribe(function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + }, observer.onError.bind(observer), function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + })); + }, function (e) { + cancelable.dispose(); + observer.onError(e); + hasValue = false; + id++; + }, function () { + cancelable.dispose(); + if (hasValue) { + observer.onNext(value); + } + observer.onCompleted(); + hasValue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * 1 - res = source.skipLastWithTime(5000); + * 2 - res = source.skipLastWithTime(5000, scheduler); + * + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for skipping elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. + */ + observableProto.skipLastWithTime = function (duration, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. + * + * @example + * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var q = []; + + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { + observer.onNext(next.value); + } + } + + observer.onCompleted(); + }); + }); + }; + + /** + * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + observableProto.takeWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), source.subscribe(observer)); + }); + }; + + /** + * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.skipWithTime(5000, [optional scheduler]); + * + * @description + * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. + * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded + * may not execute immediately, despite the zero due time. + * + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. + * @param {Number} duration Duration for skipping elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + observableProto.skipWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false; + return new CompositeDisposable( + scheduler.scheduleWithRelative(duration, function () { open = true; }), + source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); + }); + }; + + var PausableObservable = (function (_super) { + + inherits(PausableObservable, _super); + + function subscribe(observer) { + var conn = this.source.publish(), + subscription = conn.subscribe(observer), + connection = disposableEmpty; + + var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { + if (b) { + connection = conn.connect(); + } else { + connection.dispose(); + connection = disposableEmpty; + } + }); + + return new CompositeDisposable(subscription, connection, pausable); + } + + function PausableObservable(source, pauser) { + this.source = source; + this.controller = new Subject(); + + if (pauser && pauser.subscribe) { + this.pauser = this.controller.merge(pauser); + } else { + this.pauser = this.controller; + } + + _super.call(this, subscribe); + } + + PausableObservable.prototype.pause = function () { + this.controller.onNext(false); + }; + + PausableObservable.prototype.resume = function () { + this.controller.onNext(true); + }; + + return PausableObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausable(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausable = function (pauser) { + return new PausableObservable(this, pauser); + }; + function combineLatestSource(source, subject, resultSelector) { + return new AnonymousObservable(function (observer) { + var n = 2, + hasValue = [false, false], + hasValueAll = false, + isDone = false, + values = new Array(n); + + function next(x, i) { + values[i] = x + var res; + hasValue[i] = true; + if (hasValueAll || (hasValueAll = hasValue.every(identity))) { + try { + res = resultSelector.apply(null, values); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe( + function (x) { + next(x, 0); + }, + observer.onError.bind(observer), + function () { + isDone = true; + observer.onCompleted(); + }), + subject.subscribe( + function (x) { + next(x, 1); + }, + observer.onError.bind(observer)) + ); + }); + } + + var PausableBufferedObservable = (function (_super) { + + inherits(PausableBufferedObservable, _super); + + function subscribe(observer) { + var q = [], previousShouldFire; + + var subscription = + combineLatestSource( + this.source, + this.pauser.distinctUntilChanged().startWith(false), + function (data, shouldFire) { + return { data: data, shouldFire: shouldFire }; + }) + .subscribe( + function (results) { + if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { + // change in shouldFire + if (results.shouldFire) { + while (q.length > 0) { + observer.onNext(q.shift()); + } + } + } else { + // new data + if (results.shouldFire) { + observer.onNext(results.data); + } else { + q.push(results.data); + } + } + previousShouldFire = results.shouldFire; + + }, + function (err) { + // Empty buffer before sending error + while (q.length > 0) { + observer.onNext(q.shift()); + } + observer.onError(err); + }, + function () { + // Empty buffer before sending completion + while (q.length > 0) { + observer.onNext(q.shift()); + } + observer.onCompleted(); + } + ); + return subscription; + } + + function PausableBufferedObservable(source, pauser) { + this.source = source; + this.controller = new Subject(); + + if (pauser && pauser.subscribe) { + this.pauser = this.controller.merge(pauser); + } else { + this.pauser = this.controller; + } + + _super.call(this, subscribe); + } + + PausableBufferedObservable.prototype.pause = function () { + this.controller.onNext(false); + }; + + PausableBufferedObservable.prototype.resume = function () { + this.controller.onNext(true); + }; + + return PausableBufferedObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, + * and yields the values that were buffered while paused. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausableBuffered(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausableBuffered = function (subject) { + return new PausableBufferedObservable(this, subject); + }; + + /** + * Attaches a controller to the observable sequence with the ability to queue. + * @example + * var source = Rx.Observable.interval(100).controlled(); + * source.request(3); // Reads 3 values + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.controlled = function (enableQueue) { + if (enableQueue == null) { enableQueue = true; } + return new ControlledObservable(this, enableQueue); + }; + var ControlledObservable = (function (_super) { + + inherits(ControlledObservable, _super); + + function subscribe (observer) { + return this.source.subscribe(observer); + } + + function ControlledObservable (source, enableQueue) { + _super.call(this, subscribe); + this.subject = new ControlledSubject(enableQueue); + this.source = source.multicast(this.subject).refCount(); + } + + ControlledObservable.prototype.request = function (numberOfItems) { + if (numberOfItems == null) { numberOfItems = -1; } + return this.subject.request(numberOfItems); + }; + + return ControlledObservable; + + }(Observable)); + + var ControlledSubject = Rx.ControlledSubject = (function (_super) { + + function subscribe (observer) { + return this.subject.subscribe(observer); + } + + inherits(ControlledSubject, _super); + + function ControlledSubject(enableQueue) { + if (enableQueue == null) { + enableQueue = true; + } + + _super.call(this, subscribe); + this.subject = new Subject(); + this.enableQueue = enableQueue; + this.queue = enableQueue ? [] : null; + this.requestedCount = 0; + this.requestedDisposable = disposableEmpty; + this.error = null; + this.hasFailed = false; + this.hasCompleted = false; + this.controlledDisposable = disposableEmpty; + } + + addProperties(ControlledSubject.prototype, Observer, { + onCompleted: function () { + checkDisposed.call(this); + this.hasCompleted = true; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onCompleted(); + } + }, + onError: function (error) { + checkDisposed.call(this); + this.hasFailed = true; + this.error = error; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onError(error); + } + }, + onNext: function (value) { + checkDisposed.call(this); + var hasRequested = false; + + if (this.requestedCount === 0) { + if (this.enableQueue) { + this.queue.push(value); + } + } else { + if (this.requestedCount !== -1) { + if (this.requestedCount-- === 0) { + this.disposeCurrentRequest(); + } + } + hasRequested = true; + } + + if (hasRequested) { + this.subject.onNext(value); + } + }, + _processRequest: function (numberOfItems) { + if (this.enableQueue) { + //console.log('queue length', this.queue.length); + + while (this.queue.length >= numberOfItems && numberOfItems > 0) { + //console.log('number of items', numberOfItems); + this.subject.onNext(this.queue.shift()); + numberOfItems--; + } + + if (this.queue.length !== 0) { + return { numberOfItems: numberOfItems, returnValue: true }; + } else { + return { numberOfItems: numberOfItems, returnValue: false }; + } + } + + if (this.hasFailed) { + this.subject.onError(this.error); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } else if (this.hasCompleted) { + this.subject.onCompleted(); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } + + return { numberOfItems: numberOfItems, returnValue: false }; + }, + request: function (number) { + checkDisposed.call(this); + this.disposeCurrentRequest(); + var self = this, + r = this._processRequest(number); + + number = r.numberOfItems; + if (!r.returnValue) { + this.requestedCount = number; + this.requestedDisposable = disposableCreate(function () { + self.requestedCount = 0; + }); + + return this.requestedDisposable + } else { + return disposableEmpty; + } + }, + disposeCurrentRequest: function () { + this.requestedDisposable.dispose(); + this.requestedDisposable = disposableEmpty; + }, + + dispose: function () { + this.isDisposed = true; + this.error = null; + this.subject.dispose(); + this.requestedDisposable.dispose(); + } + }); + + return ControlledSubject; + }(Observable)); + /* + * Performs a exclusive waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @returns {Observable} A exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusive = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasCurrent = false, + isStopped = false, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + if (!hasCurrent) { + hasCurrent = true; + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + var innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + innerSubscription.setDisposable(innerSource.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (!hasCurrent && g.length === 1) { + observer.onCompleted(); + } + })); + + return g; + }); + }; + /* + * Performs a exclusive map waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @param {Function} selector Selector to invoke for every item in the current subscription. + * @param {Any} [thisArg] An optional context to invoke with the selector parameter. + * @returns {Observable} An exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusiveMap = function (selector, thisArg) { + var sources = this; + return new AnonymousObservable(function (observer) { + var index = 0, + hasCurrent = false, + isStopped = true, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + + if (!hasCurrent) { + hasCurrent = true; + + innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + innerSubscription.setDisposable(innerSource.subscribe( + function (x) { + var result; + try { + result = selector.call(thisArg, x, index++, innerSource); + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(result); + }, + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (g.length === 1 && !hasCurrent) { + observer.onCompleted(); + } + })); + return g; + }); + }; + var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { + inherits(AnonymousObservable, __super__); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } + + return typeof subscriber === 'function' ? + disposableCreate(subscriber) : + disposableEmpty; + } + + function AnonymousObservable(subscribe) { + if (!(this instanceof AnonymousObservable)) { + return new AnonymousObservable(subscribe); + } + + function s(observer) { + var setDisposable = function () { + try { + autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); + } catch (e) { + if (!autoDetachObserver.fail(e)) { + throw e; + } + } + }; + + var autoDetachObserver = new AutoDetachObserver(observer); + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.schedule(setDisposable); + } else { + setDisposable(); + } + + return autoDetachObserver; + } + + __super__.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + /** @private */ + var AutoDetachObserver = (function (_super) { + inherits(AutoDetachObserver, _super); + + function AutoDetachObserver(observer) { + _super.call(this); + this.observer = observer; + this.m = new SingleAssignmentDisposable(); + } + + var AutoDetachObserverPrototype = AutoDetachObserver.prototype; + + AutoDetachObserverPrototype.next = function (value) { + var noError = false; + try { + this.observer.onNext(value); + noError = true; + } catch (e) { + throw e; + } finally { + if (!noError) { + this.dispose(); + } + } + }; + + AutoDetachObserverPrototype.error = function (exn) { + try { + this.observer.onError(exn); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.completed = function () { + try { + this.observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; + /* @private */ + AutoDetachObserverPrototype.disposable = function (value) { + return arguments.length ? this.getDisposable() : setDisposable(value); + }; + + AutoDetachObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + /** @private */ + var InnerSubscription = function (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + /** + * @private + * @memberOf InnerSubscription + */ + InnerSubscription.prototype.dispose = function () { + if (!this.subject.isDisposed && this.observer !== null) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + this.observer = null; + } + }; + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.exception) { + observer.onError(this.exception); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, _super); + + /** + * Creates a subject. + * @constructor + */ + function Subject() { + _super.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + } + + addProperties(Subject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (__super__) { + + function subscribe(observer) { + checkDisposed.call(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + var ex = this.exception, + hv = this.hasValue, + v = this.value; + + if (ex) { + observer.onError(ex); + } else if (hv) { + observer.onNext(v); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, __super__); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + __super__.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.value = null; + this.hasValue = false; + this.observers = []; + this.exception = null; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed.call(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var o, i, len; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var os = this.observers.slice(0), + v = this.value, + hv = this.hasValue; + + if (hv) { + for (i = 0, len = os.length; i < len; i++) { + o = os[i]; + o.onNext(v); + o.onCompleted(); + } + } else { + for (i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the error. + * @param {Mixed} error The Error to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed.call(this); + if (this.isStopped) { return; } + this.value = value; + this.hasValue = true; + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { + inherits(AnonymousSubject, __super__); + + function AnonymousSubject(observer, observable) { + this.observer = observer; + this.observable = observable; + __super__.call(this, this.observable.subscribe.bind(this.observable)); + } + + addProperties(AnonymousSubject.prototype, Observer, { + onCompleted: function () { + this.observer.onCompleted(); + }, + onError: function (exception) { + this.observer.onError(exception); + }, + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + /** + * Represents a value that changes over time. + * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. + */ + var BehaviorSubject = Rx.BehaviorSubject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + observer.onNext(this.value); + return new InnerSubscription(this, observer); + } + var ex = this.exception; + if (ex) { + observer.onError(ex); + } else { + observer.onCompleted(); + } + return disposableEmpty; + } + + inherits(BehaviorSubject, _super); + + /** + * @constructor + * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. + * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. + */ + function BehaviorSubject(value) { + _super.call(this, subscribe); + + this.value = value, + this.observers = [], + this.isDisposed = false, + this.isStopped = false, + this.exception = null; + } + + addProperties(BehaviorSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.exception = null; + } + }); + + return BehaviorSubject; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. + */ + var ReplaySubject = Rx.ReplaySubject = (function (_super) { + + function RemovableDisposable (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + RemovableDisposable.prototype.dispose = function () { + this.observer.dispose(); + if (!this.subject.isDisposed) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + } + }; + + function subscribe(observer) { + var so = new ScheduledObserver(this.scheduler, observer), + subscription = new RemovableDisposable(this, so); + checkDisposed.call(this); + this._trim(this.scheduler.now()); + this.observers.push(so); + + var n = this.q.length; + + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } + + if (this.hasError) { + n++; + so.onError(this.error); + } else if (this.isStopped) { + n++; + so.onCompleted(); + } + + so.ensureActive(n); + return subscription; + } + + inherits(ReplaySubject, _super); + + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; + this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + _super.call(this, subscribe); + } + + addProperties(ReplaySubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /* @private */ + _trim: function (now) { + while (this.q.length > this.bufferSize) { + this.q.shift(); + } + while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { + this.q.shift(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); + + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onNext(value); + observer.ensureActive(); + } + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } +}.call(this)); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.lite.min.js b/ajax/libs/rxjs/2.3.9/rx.lite.min.js new file mode 100644 index 000000000..d5ffeb390 --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.lite.min.js @@ -0,0 +1,2 @@ +(function(a){function b(){if(this.isDisposed)throw new Error(V)}function c(a){var b=typeof a;return a&&("function"==b||"object"==b)||!1}function d(a){var b=[];if(!c(a))return b;qb.nonEnumArgs&&a.length&&h(a)&&(a=sb.call(a));var d=qb.enumPrototypes&&"function"==typeof a,e=qb.enumErrorProps&&(a===kb||a instanceof Error);for(var f in a)d&&"prototype"==f||e&&("message"==f||"name"==f)||b.push(f);if(qb.nonEnumShadows&&a!==lb){var g=a.constructor,i=-1,j=ob.length;if(a===(g&&g.prototype))var k=a===stringProto?gb:a===kb?bb:hb.call(a),l=pb[k];for(;++i-1:void 0});return c.pop(),d.pop(),result}function k(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:sb.call(a)}function l(a,b){for(var c=new Array(a),d=0;a>d;d++)c[d]=b();return c}function m(a){return"number"==typeof a&&G.isFinite(a)}function n(b){return b[W]!==a}function o(a){var b=+a;return 0===b?b:isNaN(b)?b:0>b?-1:1}function p(a){var b=+a.length;return isNaN(b)?0:0!==b&&m(b)?(b=o(b)*Math.floor(Math.abs(b)),0>=b?0:b>bc?bc:b):b}function q(a){return"[object Function]"===Object.prototype.toString.call(a)&&"function"==typeof a}function r(a,b){return new wc(function(c){var d=new Db,e=new SerialDisposable;return e.setDisposable(d),d.setDisposable(a.subscribe(c.onNext.bind(c),function(a){var d,f;try{f=b(a)}catch(g){return void c.onError(g)}T(f)&&(f=oc(f)),d=new Db,e.setDisposable(d),d.setDisposable(f.subscribe(c))},c.onCompleted.bind(c))),e})}function s(a,b){var c=this;return new wc(function(d){var e=0,f=a.length;return c.subscribe(function(c){if(f>e){var g,h=a[e++];try{g=b(c,h)}catch(i){return void d.onError(i)}d.onNext(g)}else d.onCompleted()},d.onError.bind(d),d.onCompleted.bind(d))})}function t(a,b,c){return a.map(function(a,d){var e=b.call(c,a,d);return T(e)?oc(e):e}).concatAll()}function u(a,b,c){return a.map(function(a,d){var e=b.call(c,a,d);return T(e)?oc(e):e}).mergeObservable()}function v(a,b,c){if(a.addEventListener)return a.addEventListener(b,c,!1),Bb(function(){a.removeEventListener(b,c,!1)});throw new Error("No listener found")}function w(a,b,c){var d=new yb;if("[object NodeList]"===Object.prototype.toString.call(a))for(var e=0,f=a.length;f>e;e++)d.add(w(a.item(e),b,c));else a&&d.add(v(a,b,c));return d}function x(a,b){return new wc(function(c){return b.scheduleWithAbsolute(a,function(){c.onNext(0),c.onCompleted()})})}function y(a,b,c){return new wc(function(d){var e=0,f=a,g=Gb(b);return c.scheduleRecursiveWithAbsolute(f,function(a){if(g>0){var b=c.now();f+=g,b>=f&&(f=b+g)}d.onNext(e++),a(f)})})}function z(a,b){return new wc(function(c){return b.scheduleWithRelative(Gb(a),function(){c.onNext(0),c.onCompleted()})})}function A(a,b,c){return a===b?new wc(function(a){return c.schedulePeriodicWithState(0,b,function(b){return a.onNext(b),b+1})}):_b(function(){return y(c.now()+a,b,c)})}function B(a,b,c){return new wc(function(d){var e,f=!1,g=new SerialDisposable,h=null,i=[],j=!1;return e=a.materialize().timestamp(c).subscribe(function(a){var e,k;"E"===a.value.kind?(i=[],i.push(a),h=a.value.exception,k=!j):(i.push({value:a.value,timestamp:a.timestamp+b}),k=!f,f=!0),k&&(null!==h?d.onError(h):(e=new Db,g.setDisposable(e),e.setDisposable(c.scheduleRecursiveWithRelative(b,function(a){var b,e,g,k;if(null===h){j=!0;do g=null,i.length>0&&i[0].timestamp-c.now()<=0&&(g=i.shift().value),null!==g&&g.accept(d);while(null!==g);k=!1,e=0,i.length>0?(k=!0,e=Math.max(0,i[0].timestamp-c.now())):f=!1,b=h,j=!1,null!==b?d.onError(b):k&&a(e)}}))))}),new yb(e,g)})}function C(a,b,c){return _b(function(){return B(a,b-c.now(),c)})}function D(a,b){return new wc(function(c){function d(){g&&(g=!1,c.onNext(f)),e&&c.onCompleted()}var e,f,g;return new yb(a.subscribe(function(a){g=!0,f=a},c.onError.bind(c),function(){e=!0}),b.subscribe(d,c.onError.bind(c),d))})}function E(a,b,c){return new wc(function(d){function e(a,b){j[b]=a;var e;if(g[b]=!0,h||(h=g.every(O))){try{e=c.apply(null,j)}catch(f){return void d.onError(f)}d.onNext(e)}else i&&d.onCompleted()}var f=2,g=[!1,!1],h=!1,i=!1,j=new Array(f);return new yb(a.subscribe(function(a){e(a,0)},d.onError.bind(d),function(){i=!0,d.onCompleted()}),b.subscribe(function(a){e(a,1)},d.onError.bind(d)))})}var F={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},G=F[typeof window]&&window||this,H=F[typeof exports]&&exports&&!exports.nodeType&&exports,I=F[typeof module]&&module&&!module.nodeType&&module,J=I&&I.exports===H&&H,K=F[typeof global]&&global;!K||K.global!==K&&K.window!==K||(G=K);var L={internals:{},config:{Promise:G.Promise},helpers:{}},M=L.helpers.noop=function(){},N=(L.helpers.notDefined=function(a){return"undefined"==typeof a},L.helpers.isScheduler=function(a){return a instanceof L.Scheduler}),O=L.helpers.identity=function(a){return a},P=(L.helpers.pluck=function(a){return function(b){return b[a]}},L.helpers.just=function(a){return function(){return a}},L.helpers.defaultNow=Date.now),Q=L.helpers.defaultComparer=function(a,b){return rb(a,b)},R=L.helpers.defaultSubComparer=function(a,b){return a>b?1:b>a?-1:0},S=(L.helpers.defaultKeySerializer=function(a){return a.toString()},L.helpers.defaultError=function(a){throw a}),T=L.helpers.isPromise=function(a){return!!a&&"function"==typeof a.then},U=(L.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},L.helpers.not=function(a){return!a},"Argument out of range"),V="Object has been disposed",W="function"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";G.Set&&"function"==typeof(new G.Set)["@@iterator"]&&(W="@@iterator");var X,Y={done:!0,value:a},Z="[object Arguments]",$="[object Array]",_="[object Boolean]",ab="[object Date]",bb="[object Error]",cb="[object Function]",db="[object Number]",eb="[object Object]",fb="[object RegExp]",gb="[object String]",hb=Object.prototype.toString,ib=Object.prototype.hasOwnProperty,jb=hb.call(arguments)==Z,kb=Error.prototype,lb=Object.prototype,mb=lb.propertyIsEnumerable;try{X=!(hb.call(document)==eb&&!({toString:0}+""))}catch(nb){X=!0}var ob=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],pb={};pb[$]=pb[ab]=pb[db]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},pb[_]=pb[gb]={constructor:!0,toString:!0,valueOf:!0},pb[bb]=pb[cb]=pb[fb]={constructor:!0,toString:!0},pb[eb]={constructor:!0};var qb={};!function(){var a=function(){this.x=1},b=[];a.prototype={valueOf:1,y:1};for(var c in new a)b.push(c);for(c in arguments);qb.enumErrorProps=mb.call(kb,"message")||mb.call(kb,"name"),qb.enumPrototypes=mb.call(a,"prototype"),qb.nonEnumArgs=0!=c,qb.nonEnumShadows=!/valueOf/.test(b)}(1),jb||(h=function(a){return a&&"object"==typeof a?ib.call(a,"callee"):!1}),i(/x/)&&(i=function(a){return"function"==typeof a&&hb.call(a)==cb});var rb=L.internals.isEqual=function(a,b){return j(a,b,[],[])},sb=Array.prototype.slice,tb=({}.hasOwnProperty,this.inherits=L.internals.inherits=function(a,b){function c(){this.constructor=a}c.prototype=b.prototype,a.prototype=new c}),ub=L.internals.addProperties=function(a){for(var b=sb.call(arguments,1),c=0,d=b.length;d>c;c++){var e=b[c];for(var f in e)a[f]=e[f]}},vb=(L.internals.addRef=function(a,b){return new wc(function(c){return new yb(b.getDisposable(),a.subscribe(c))})},function(a,b){this.id=a,this.value=b});vb.prototype.compareTo=function(a){var b=this.value.compareTo(a.value);return 0===b&&(b=this.id-a.id),b};var wb=L.internals.PriorityQueue=function(a){this.items=new Array(a),this.length=0},xb=wb.prototype;xb.isHigherPriority=function(a,b){return this.items[a].compareTo(this.items[b])<0},xb.percolate=function(a){if(!(a>=this.length||0>a)){var b=a-1>>1;if(!(0>b||b===a)&&this.isHigherPriority(a,b)){var c=this.items[a];this.items[a]=this.items[b],this.items[b]=c,this.percolate(b)}}},xb.heapify=function(b){if(b===a&&(b=0),!(b>=this.length||0>b)){var c=2*b+1,d=2*b+2,e=b;if(cb;b++)a[b].dispose()}},zb.toArray=function(){return this.disposables.slice(0)};var Ab=L.Disposable=function(a){this.isDisposed=!1,this.action=a||M};Ab.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var Bb=Ab.create=function(a){return new Ab(a)},Cb=Ab.empty={dispose:M},Db=L.SingleAssignmentDisposable=SerialDisposable=L.SerialDisposable=function(){function a(){this.isDisposed=!1,this.current=null}var b=a.prototype;return b.getDisposable=function(){return this.current},b.setDisposable=function(a){var b,c=this.isDisposed;c||(b=this.current,this.current=a),b&&b.dispose(),c&&a&&a.dispose()},b.dispose=function(){var a;this.isDisposed||(this.isDisposed=!0,a=this.current,this.current=null),a&&a.dispose()},a}(),Eb=(L.RefCountDisposable=function(){function a(a){this.disposable=a,this.disposable.count++,this.isInnerDisposed=!1}function b(a){this.underlyingDisposable=a,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return a.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},b.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},b.prototype.getDisposable=function(){return this.isDisposed?Cb:new a(this)},b}(),L.internals.ScheduledItem=function(a,b,c,d,e){this.scheduler=a,this.state=b,this.action=c,this.dueTime=d,this.comparer=e||R,this.disposable=new Db});Eb.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},Eb.prototype.compareTo=function(a){return this.comparer(this.dueTime,a.dueTime)},Eb.prototype.isCancelled=function(){return this.disposable.isDisposed},Eb.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var Fb=L.Scheduler=function(){function a(a,b,c,d){this.now=a,this._schedule=b,this._scheduleRelative=c,this._scheduleAbsolute=d}function b(a,b){return b(),Cb}var c=a.prototype;return c.schedule=function(a){return this._schedule(a,b)},c.scheduleWithState=function(a,b){return this._schedule(a,b)},c.scheduleWithRelative=function(a,c){return this._scheduleRelative(c,a,b)},c.scheduleWithRelativeAndState=function(a,b,c){return this._scheduleRelative(a,b,c)},c.scheduleWithAbsolute=function(a,c){return this._scheduleAbsolute(c,a,b)},c.scheduleWithAbsoluteAndState=function(a,b,c){return this._scheduleAbsolute(a,b,c)},a.now=P,a.normalize=function(a){return 0>a&&(a=0),a},a}(),Gb=Fb.normalize;!function(a){function b(a,b){var c=b.first,d=b.second,e=new yb,f=function(b){d(b,function(b){var c=!1,d=!1,g=a.scheduleWithState(b,function(a,b){return c?e.remove(g):d=!0,f(b),Cb});d||(e.add(g),c=!0)})};return f(c),e}function c(a,b,c){var d=b.first,e=b.second,f=new yb,g=function(b){e(b,function(b,d){var e=!1,h=!1,i=a[c].call(a,b,d,function(a,b){return e?f.remove(i):h=!0,g(b),Cb});h||(f.add(i),e=!0)})};return g(d),f}function d(a,b){a(function(c){b(a,c)})}a.scheduleRecursive=function(a){return this.scheduleRecursiveWithState(a,function(a,b){a(function(){b(a)})})},a.scheduleRecursiveWithState=function(a,c){return this.scheduleWithState({first:a,second:c},b)},a.scheduleRecursiveWithRelative=function(a,b){return this.scheduleRecursiveWithRelativeAndState(b,a,d)},a.scheduleRecursiveWithRelativeAndState=function(a,b,d){return this._scheduleRelative({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithRelativeAndState")})},a.scheduleRecursiveWithAbsolute=function(a,b){return this.scheduleRecursiveWithAbsoluteAndState(b,a,d)},a.scheduleRecursiveWithAbsoluteAndState=function(a,b,d){return this._scheduleAbsolute({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithAbsoluteAndState")})}}(Fb.prototype),function(){Fb.prototype.schedulePeriodic=function(a,b){return this.schedulePeriodicWithState(null,a,b)},Fb.prototype.schedulePeriodicWithState=function(a,b,c){var d=a,e=setInterval(function(){d=c(d)},b);return Bb(function(){clearInterval(e)})}}(Fb.prototype);var Hb,Ib=Fb.immediate=function(){function a(a,b){return b(this,a)}function b(a,b,c){for(var d=Gb(d);d-this.now()>0;);return c(this,a)}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new Fb(P,a,b,c)}(),Jb=Fb.currentThread=function(){function a(a){for(var b;a.length>0;)if(b=a.dequeue(),!b.isCancelled()){for(;b.dueTime-Fb.now()>0;);b.isCancelled()||b.invoke()}}function b(a,b){return this.scheduleWithRelativeAndState(a,0,b)}function c(b,c,d){var f=this.now()+Fb.normalize(c),g=new Eb(this,b,d,f);if(e)e.enqueue(g);else{e=new wb(4),e.enqueue(g);try{a(e)}catch(h){throw h}finally{e=null}}return g.disposable}function d(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}var e,f=new Fb(P,b,c,d);return f.scheduleRequired=function(){return!e},f.ensureTrampoline=function(a){e?a():this.schedule(a)},f}(),Kb=(L.internals.SchedulePeriodicRecursive=function(){function a(a,b){b(0,this._period);try{this._state=this._action(this._state)}catch(c){throw this._cancel.dispose(),c}}function b(a,b,c,d){this._scheduler=a,this._state=b,this._period=c,this._action=d}return b.prototype.start=function(){var b=new Db;return this._cancel=b,b.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,a.bind(this))),b},b}(),M);!function(){function a(){if(!G.postMessage||G.importScripts)return!1;var a=!1,b=G.onmessage;return G.onmessage=function(){a=!0},G.postMessage("","*"),G.onmessage=b,a}function b(a){if("string"==typeof a.data&&a.data.substring(0,f.length)===f){var b=a.data.substring(f.length),c=g[b];c(),delete g[b]}}var c=RegExp("^"+String(hb).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),d="function"==typeof(d=K&&J&&K.setImmediate)&&!c.test(d)&&d,e="function"==typeof(e=K&&J&&K.clearImmediate)&&!c.test(e)&&e;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))Hb=process.nextTick;else if("function"==typeof d)Hb=d,Kb=e;else if(a()){var f="ms.rx.schedule"+Math.random(),g={},h=0;G.addEventListener?G.addEventListener("message",b,!1):G.attachEvent("onmessage",b,!1),Hb=function(a){var b=h++;g[b]=a,G.postMessage(f+b,"*")}}else if(G.MessageChannel){var i=new G.MessageChannel,j={},k=0;i.port1.onmessage=function(a){var b=a.data,c=j[b];c(),delete j[b]},Hb=function(a){var b=k++;j[b]=a,i.port2.postMessage(b)}}else"document"in G&&"onreadystatechange"in G.document.createElement("script")?Hb=function(a){var b=G.document.createElement("script");b.onreadystatechange=function(){a(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},G.document.documentElement.appendChild(b)}:(Hb=function(a){return setTimeout(a,0)},Kb=clearTimeout)}();var Lb=Fb.timeout=function(){function a(a,b){var c=this,d=new Db,e=Hb(function(){d.isDisposed||d.setDisposable(b(c,a))});return new yb(d,Bb(function(){Kb(e)}))}function b(a,b,c){var d=this,e=Fb.normalize(b);if(0===e)return d.scheduleWithState(a,c);var f=new Db,g=setTimeout(function(){f.isDisposed||f.setDisposable(c(d,a))},e);return new yb(f,Bb(function(){clearTimeout(g)}))}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new Fb(P,a,b,c)}(),Mb=L.Notification=function(){function a(a,b){this.hasValue=null==b?!1:b,this.kind=a}return a.prototype.accept=function(a,b,c){return a&&"object"==typeof a?this._acceptObservable(a):this._accept(a,b,c)},a.prototype.toObservable=function(a){var b=this;return N(a)||(a=Ib),new wc(function(c){return a.schedule(function(){b._acceptObservable(c),"N"===b.kind&&c.onCompleted()})})},a}(),Nb=Mb.createOnNext=function(){function a(a){return a(this.value)}function b(a){return a.onNext(this.value)}function c(){return"OnNext("+this.value+")"}return function(d){var e=new Mb("N",!0);return e.value=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),Ob=Mb.createOnError=function(){function a(a,b){return b(this.exception)}function b(a){return a.onError(this.exception)}function c(){return"OnError("+this.exception+")"}return function(d){var e=new Mb("E");return e.exception=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),Pb=Mb.createOnCompleted=function(){function a(a,b,c){return c()}function b(a){return a.onCompleted()}function c(){return"OnCompleted()"}return function(){var d=new Mb("C");return d._accept=a,d._acceptObservable=b,d.toString=c,d}}(),Qb=L.internals.Enumerator=function(a){this._next=a};Qb.prototype.next=function(){return this._next()},Qb.prototype[W]=function(){return this};var Rb=L.internals.Enumerable=function(a){this._iterator=a};Rb.prototype[W]=function(){return this._iterator()},Rb.prototype.concat=function(){var a=this;return new wc(function(b){var c;try{c=a[W]()}catch(d){return void b.onError()}var e,f=new SerialDisposable,g=Ib.scheduleRecursive(function(a){var d;if(!e){try{d=c.next()}catch(g){return void b.onError(g)}if(d.done)return void b.onCompleted();var h=d.value;T(h)&&(h=oc(h));var i=new Db;f.setDisposable(i),i.setDisposable(h.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){a()}))}});return new yb(f,g,Bb(function(){e=!0}))})},Rb.prototype.catchException=function(){var a=this;return new wc(function(b){var c;try{c=a[W]()}catch(d){return void b.onError()}var e,f,g=new SerialDisposable,h=Ib.scheduleRecursive(function(a){if(!e){var d;try{d=c.next()}catch(h){return void b.onError(h)}if(d.done)return void(f?b.onError(f):b.onCompleted());var i=d.value;T(i)&&(i=oc(i));var j=new Db;g.setDisposable(j),j.setDisposable(i.subscribe(b.onNext.bind(b),function(b){f=b,a()},b.onCompleted.bind(b)))}});return new yb(g,h,Bb(function(){e=!0}))})};var Sb=Rb.repeat=function(a,b){return null==b&&(b=-1),new Rb(function(){var c=b;return new Qb(function(){return 0===c?Y:(c>0&&c--,{done:!1,value:a})})})},Tb=Rb.forEach=function(a,b,c){return b||(b=O),new Rb(function(){var d=-1;return new Qb(function(){return++d0&&(a=!this.isAcquired,this.isAcquired=!0),a&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(a){var c;if(!(b.queue.length>0))return void(b.isAcquired=!1);c=b.queue.shift();try{c()}catch(d){throw b.queue=[],b.hasFaulted=!0,d}a()}))},b.prototype.dispose=function(){a.prototype.dispose.call(this),this.disposable.dispose()},b}(Xb);Wb.toArray=function(){var a=this;return new wc(function(b){var c=[];return a.subscribe(c.push.bind(c),b.onError.bind(b),function(){b.onNext(c),b.onCompleted()})})},Zb.create=Zb.createWithDisposable=function(a){return new wc(a)};var _b=Zb.defer=function(a){return new wc(function(b){var c;try{c=a()}catch(d){return fc(d).subscribe(b)}return T(c)&&(c=oc(c)),c.subscribe(b)})},ac=Zb.empty=function(a){return N(a)||(a=Ib),new wc(function(b){return a.schedule(function(){b.onCompleted()})})},bc=Math.pow(2,53)-1;Zb.from=function(a,b,c,d){if(null==a)throw new Error("iterable cannot be null.");if(b&&!q(b))throw new Error("mapFn when provided must be a function");return N(d)||(d=Jb),new wc(function(e){var f=Object(a),g=n(f),h=g?0:p(f),i=g?f[W]():null,j=0;return d.scheduleRecursive(function(a){if(h>j||g){var d;if(g){var k=i.next();if(k.done)return void e.onCompleted();d=k.value}else d=f[j];if(b&&q(b))try{d=c?b.call(c,d,j):b(d,j)}catch(l){return void e.onError(l)}e.onNext(d),j++,a()}else e.onCompleted()})})};var cc=Zb.fromArray=function(a,b){return N(b)||(b=Jb),new wc(function(c){var d=0,e=a.length;return b.scheduleRecursive(function(b){e>d?(c.onNext(a[d++]),b()):c.onCompleted()})})},dc=Zb.never=function(){return new wc(function(){return Cb})};Zb.of=function(){for(var a=arguments.length,b=new Array(a),c=0;a>c;c++)b[c]=arguments[c];return cc(b)};Zb.ofWithScheduler=function(a){for(var b=arguments.length-1,c=new Array(b),d=0;b>d;d++)c[d]=arguments[d+1];return cc(c,a)};Zb.range=function(a,b,c){return N(c)||(c=Jb),new wc(function(d){return c.scheduleRecursiveWithState(0,function(c,e){b>c?(d.onNext(a+c),e(c+1)):d.onCompleted()})})},Zb.repeat=function(a,b,c){return N(c)||(c=Jb),ec(a,c).repeat(null==b?-1:b)};var ec=Zb["return"]=Zb.returnValue=Zb.just=function(a,b){return N(b)||(b=Ib),new wc(function(c){return b.schedule(function(){c.onNext(a),c.onCompleted()})})},fc=Zb["throw"]=Zb.throwException=function(a,b){return N(b)||(b=Ib),new wc(function(c){return b.schedule(function(){c.onError(a)})})};Wb["catch"]=Wb.catchException=function(a){return"function"==typeof a?r(this,a):gc([this,a])};var gc=Zb.catchException=Zb["catch"]=function(){var a=k(arguments,0);return Tb(a).catchException()};Wb.combineLatest=function(){var a=sb.call(arguments);return Array.isArray(a[0])?a[0].unshift(this):a.unshift(this),hc.apply(this,a)};var hc=Zb.combineLatest=function(){var a=sb.call(arguments),b=a.pop();return Array.isArray(a[0])&&(a=a[0]),new wc(function(c){function d(a){var d;if(h[a]=!0,i||(i=h.every(O))){try{d=b.apply(null,k)}catch(e){return void c.onError(e)}c.onNext(d)}else j.filter(function(b,c){return c!==a}).every(O)&&c.onCompleted()}function e(a){j[a]=!0,j.every(O)&&c.onCompleted()}for(var f=function(){return!1},g=a.length,h=l(g,f),i=!1,j=l(g,f),k=new Array(g),m=new Array(g),n=0;g>n;n++)!function(b){var f=a[b],g=new Db;T(f)&&(f=oc(f)),g.setDisposable(f.subscribe(function(a){k[b]=a,d(b)},c.onError.bind(c),function(){e(b)})),m[b]=g}(n);return new yb(m)})};Wb.concat=function(){var a=sb.call(arguments,0);return a.unshift(this),ic.apply(this,a)};var ic=Zb.concat=function(){var a=k(arguments,0);return Tb(a).concat()};Wb.concatObservable=Wb.concatAll=function(){return this.merge(1)},Wb.merge=function(a){if("number"!=typeof a)return jc(this,a);var b=this;return new wc(function(c){function d(a){var b=new Db;f.add(b),T(a)&&(a=oc(a)),b.setDisposable(a.subscribe(c.onNext.bind(c),c.onError.bind(c),function(){f.remove(b),h.length>0?d(h.shift()):(e--,g&&0===e&&c.onCompleted())}))}var e=0,f=new yb,g=!1,h=[];return f.add(b.subscribe(function(b){a>e?(e++,d(b)):h.push(b)},c.onError.bind(c),function(){g=!0,0===e&&c.onCompleted()})),f})};var jc=Zb.merge=function(){var a,b;return arguments[0]?arguments[0].now?(a=arguments[0],b=sb.call(arguments,1)):(a=Ib,b=sb.call(arguments,0)):(a=Ib,b=sb.call(arguments,1)),Array.isArray(b[0])&&(b=b[0]),cc(b,a).mergeObservable()};Wb.mergeObservable=Wb.mergeAll=function(){var a=this;return new wc(function(b){var c=new yb,d=!1,e=new Db;return c.add(e),e.setDisposable(a.subscribe(function(a){var e=new Db;c.add(e),T(a)&&(a=oc(a)),e.setDisposable(a.subscribe(function(a){b.onNext(a)},b.onError.bind(b),function(){c.remove(e),d&&1===c.length&&b.onCompleted()}))},b.onError.bind(b),function(){d=!0,1===c.length&&b.onCompleted()})),c})},Wb.skipUntil=function(a){var b=this;return new wc(function(c){var d=!1,e=new yb(b.subscribe(function(a){d&&c.onNext(a)},c.onError.bind(c),function(){d&&c.onCompleted()}));T(a)&&(a=oc(a));var f=new Db;return e.add(f),f.setDisposable(a.subscribe(function(){d=!0,f.dispose()},c.onError.bind(c),function(){f.dispose()})),e})},Wb["switch"]=Wb.switchLatest=function(){var a=this;return new wc(function(b){var c=!1,d=new SerialDisposable,e=!1,f=0,g=a.subscribe(function(a){var g=new Db,h=++f;c=!0,d.setDisposable(g),T(a)&&(a=oc(a)),g.setDisposable(a.subscribe(function(a){f===h&&b.onNext(a)},function(a){f===h&&b.onError(a)},function(){f===h&&(c=!1,e&&b.onCompleted())}))},b.onError.bind(b),function(){e=!0,c||b.onCompleted()});return new yb(g,d)})},Wb.takeUntil=function(a){var b=this;return new wc(function(c){return T(a)&&(a=oc(a)),new yb(b.subscribe(c),a.subscribe(c.onCompleted.bind(c),c.onError.bind(c),M))})},Wb.zip=function(){if(Array.isArray(arguments[0]))return s.apply(this,arguments);var a=this,b=sb.call(arguments),c=b.pop();return b.unshift(a),new wc(function(d){function e(b){var e,f;if(h.every(function(a){return a.length>0})){try{f=h.map(function(a){return a.shift()}),e=c.apply(a,f)}catch(g){return void d.onError(g)}d.onNext(e)}else i.filter(function(a,c){return c!==b}).every(O)&&d.onCompleted()}function f(a){i[a]=!0,i.every(function(a){return a})&&d.onCompleted()}for(var g=b.length,h=l(g,function(){return[]}),i=l(g,function(){return!1}),j=new Array(g),k=0;g>k;k++)!function(a){var c=b[a],g=new Db;T(c)&&(c=oc(c)),g.setDisposable(c.subscribe(function(b){h[a].push(b),e(a)},d.onError.bind(d),function(){f(a)})),j[a]=g}(k);return new yb(j)})},Zb.zip=function(){var a=sb.call(arguments,0),b=a.shift();return b.zip.apply(b,a)},Zb.zipArray=function(){var a=k(arguments,0);return new wc(function(b){function c(a){if(f.every(function(a){return a.length>0})){var c=f.map(function(a){return a.shift()});b.onNext(c)}else if(g.filter(function(b,c){return c!==a}).every(O))return void b.onCompleted()}function d(a){return g[a]=!0,g.every(O)?void b.onCompleted():void 0}for(var e=a.length,f=l(e,function(){return[]}),g=l(e,function(){return!1}),h=new Array(e),i=0;e>i;i++)!function(e){h[e]=new Db,h[e].setDisposable(a[e].subscribe(function(a){f[e].push(a),c(e)},b.onError.bind(b),function(){d(e)}))}(i);var j=new yb(h);return j.add(Bb(function(){for(var a=0,b=f.length;b>a;a++)f[a]=[]})),j})},Wb.asObservable=function(){var a=this;return new wc(function(b){return a.subscribe(b)})},Wb.dematerialize=function(){var a=this;return new wc(function(b){return a.subscribe(function(a){return a.accept(b)},b.onError.bind(b),b.onCompleted.bind(b))})},Wb.distinctUntilChanged=function(a,b){var c=this;return a||(a=O),b||(b=Q),new wc(function(d){var e,f=!1;return c.subscribe(function(c){var g,h=!1;try{g=a(c)}catch(i){return void d.onError(i)}if(f)try{h=b(e,g)}catch(i){return void d.onError(i)}f&&h||(f=!0,e=g,d.onNext(c))},d.onError.bind(d),d.onCompleted.bind(d))})},Wb["do"]=Wb.doAction=Wb.tap=function(a,b,c){var d,e=this;return"function"==typeof a?d=a:(d=a.onNext.bind(a),b=a.onError.bind(a),c=a.onCompleted.bind(a)),new wc(function(a){return e.subscribe(function(b){try{d(b)}catch(c){a.onError(c)}a.onNext(b)},function(c){if(b){try{b(c)}catch(d){a.onError(d)}a.onError(c)}else a.onError(c)},function(){if(c){try{c()}catch(b){a.onError(b)}a.onCompleted()}else a.onCompleted()})})},Wb["finally"]=Wb.finallyAction=function(a){var b=this;return new wc(function(c){var d;try{d=b.subscribe(c)}catch(e){throw a(),e}return Bb(function(){try{d.dispose()}catch(b){throw b}finally{a()}})})},Wb.ignoreElements=function(){var a=this;return new wc(function(b){return a.subscribe(M,b.onError.bind(b),b.onCompleted.bind(b))})},Wb.materialize=function(){var a=this;return new wc(function(b){return a.subscribe(function(a){b.onNext(Nb(a))},function(a){b.onNext(Ob(a)),b.onCompleted()},function(){b.onNext(Pb()),b.onCompleted()})})},Wb.repeat=function(a){return Sb(this,a).concat()},Wb.retry=function(a){return Sb(this,a).catchException()},Wb.scan=function(){var a,b,c=!1,d=this;return 2===arguments.length?(c=!0,a=arguments[0],b=arguments[1]):b=arguments[0],new wc(function(e){var f,g,h;return d.subscribe(function(d){try{h||(h=!0),f?g=b(g,d):(g=c?b(a,d):d,f=!0)}catch(i){return void e.onError(i)}e.onNext(g)},e.onError.bind(e),function(){!h&&c&&e.onNext(a),e.onCompleted()})})},Wb.skipLast=function(a){var b=this;return new wc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&c.onNext(d.shift())},c.onError.bind(c),c.onCompleted.bind(c))})},Wb.startWith=function(){var a,b,c=0;return arguments.length&&"now"in Object(arguments[0])?(b=arguments[0],c=1):b=Ib,a=sb.call(arguments,c),Tb([cc(a,b),this]).concat()},Wb.takeLast=function(a){var b=this;return new wc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&d.shift()},c.onError.bind(c),function(){for(;d.length>0;)c.onNext(d.shift());c.onCompleted()})})},Wb.selectConcat=Wb.concatMap=function(a,b,c){return b?this.concatMap(function(c,d){var e=a(c,d),f=T(e)?oc(e):e; +return f.map(function(a){return b(c,a,d)})}):"function"==typeof a?t(this,a,c):t(this,function(){return a})},Wb.select=Wb.map=function(a,b){var c=this;return new wc(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},Wb.pluck=function(a){return this.select(function(b){return b[a]})},Wb.selectMany=Wb.flatMap=function(a,b,c){return b?this.flatMap(function(c,d){var e=a(c,d),f=T(e)?oc(e):e;return f.map(function(a){return b(c,a,d)})},c):"function"==typeof a?u(this,a,c):u(this,function(){return a})},Wb.selectSwitch=Wb.flatMapLatest=Wb.switchMap=function(a,b){return this.select(a,b).switchLatest()},Wb.skip=function(a){if(0>a)throw new Error(U);var b=this;return new wc(function(c){var d=a;return b.subscribe(function(a){0>=d?c.onNext(a):d--},c.onError.bind(c),c.onCompleted.bind(c))})},Wb.skipWhile=function(a,b){var c=this;return new wc(function(d){var e=0,f=!1;return c.subscribe(function(g){if(!f)try{f=!a.call(b,g,e++,c)}catch(h){return void d.onError(h)}f&&d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},Wb.take=function(a,b){if(0>a)throw new Error(U);if(0===a)return ac(b);var c=this;return new wc(function(b){var d=a;return c.subscribe(function(a){d>0&&(d--,b.onNext(a),0===d&&b.onCompleted())},b.onError.bind(b),b.onCompleted.bind(b))})},Wb.takeWhile=function(a,b){var c=this;return new wc(function(d){var e=0,f=!0;return c.subscribe(function(g){if(f){try{f=a.call(b,g,e++,c)}catch(h){return void d.onError(h)}f?d.onNext(g):d.onCompleted()}},d.onError.bind(d),d.onCompleted.bind(d))})},Wb.where=Wb.filter=function(a,b){var c=this;return new wc(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}g&&d.onNext(f)},d.onError.bind(d),d.onCompleted.bind(d))})},Zb.fromCallback=function(a,b,c){return function(){var d=sb.call(arguments,0);return new wc(function(e){function f(a){var b=a;if(c){try{b=c(arguments)}catch(d){return void e.onError(d)}e.onNext(b)}else b.length<=1?e.onNext.apply(e,b):e.onNext(b);e.onCompleted()}d.push(f),a.apply(b,d)}).publishLast().refCount()}},Zb.fromNodeCallback=function(a,b,c){return function(){var d=sb.call(arguments,0);return new wc(function(e){function f(a){if(a)return void e.onError(a);var b=sb.call(arguments,1);if(c){try{b=c(b)}catch(d){return void e.onError(d)}e.onNext(b)}else b.length<=1?e.onNext.apply(e,b):e.onNext(b);e.onCompleted()}d.push(f),a.apply(b,d)}).publishLast().refCount()}},L.config.useNativeEvents=!1;var kc=G.angular&&angular.element?angular.element:G.jQuery?G.jQuery:G.Zepto?G.Zepto:null,lc=!!G.Ember&&"function"==typeof G.Ember.addListener,mc=!!G.Backbone&&!!G.Backbone.Marionette;Zb.fromEvent=function(a,b,c){if(a.addListener)return nc(function(c){a.addListener(b,c)},function(c){a.removeListener(b,c)},c);if(!L.config.useNativeEvents){if(mc)return nc(function(c){a.on(b,c)},function(c){a.off(b,c)},c);if(lc)return nc(function(c){Ember.addListener(a,b,c)},function(c){Ember.removeListener(a,b,c)},c);if(kc){var d=kc(a);return nc(function(a){d.on(b,a)},function(a){d.off(b,a)},c)}}return new wc(function(d){return w(a,b,function(a){var b=a;if(c)try{b=c(arguments)}catch(e){return void d.onError(e)}d.onNext(b)})}).publish().refCount()};var nc=Zb.fromEventPattern=function(a,b,c){return new wc(function(d){function e(a){var b=a;if(c)try{b=c(arguments)}catch(e){return void d.onError(e)}d.onNext(b)}var f=a(e);return Bb(function(){b&&b(e,f)})}).publish().refCount()},oc=Zb.fromPromise=function(a){return _b(function(){var b=new L.AsyncSubject;return a.then(function(a){b.isDisposed||(b.onNext(a),b.onCompleted())},b.onError.bind(b)),b})};Wb.toPromise=function(a){if(a||(a=L.config.Promise),!a)throw new Error("Promise type not provided nor in Rx.config.Promise");var b=this;return new a(function(a,c){var d,e=!1;b.subscribe(function(a){d=a,e=!0},function(a){c(a)},function(){e&&a(d)})})},Zb.startAsync=function(a){var b;try{b=a()}catch(c){return fc(c)}return oc(b)},Wb.multicast=function(a,b){var c=this;return"function"==typeof a?new wc(function(d){var e=c.multicast(a());return new yb(b(e).subscribe(d),e.connect())}):new pc(c,a)},Wb.publish=function(a){return a?this.multicast(function(){return new zc},a):this.multicast(new zc)},Wb.share=function(){return this.publish(null).refCount()},Wb.publishLast=function(a){return a?this.multicast(function(){return new Ac},a):this.multicast(new Ac)},Wb.publishValue=function(a,b){return 2===arguments.length?this.multicast(function(){return new Cc(b)},a):this.multicast(new Cc(a))},Wb.shareValue=function(a){return this.publishValue(a).refCount()},Wb.replay=function(a,b,c,d){return a?this.multicast(function(){return new Dc(b,c,d)},a):this.multicast(new Dc(b,c,d))},Wb.shareReplay=function(a,b,c){return this.replay(null,a,b,c).refCount()};var pc=L.ConnectableObservable=function(a){function b(b,c){var d,e=!1,f=b.asObservable();this.connect=function(){return e||(e=!0,d=new yb(f.subscribe(c),Bb(function(){e=!1}))),d},a.call(this,c.subscribe.bind(c))}return tb(b,a),b.prototype.refCount=function(){var a,b=0,c=this;return new wc(function(d){var e=1===++b,f=c.subscribe(d);return e&&(a=c.connect()),function(){f.dispose(),0===--b&&a.dispose()}})},b}(Zb),qc=Zb.interval=function(a,b){return A(a,a,N(b)?b:Lb)},rc=Zb.timer=function(b,c,d){var e;return N(d)||(d=Lb),c!==a&&"number"==typeof c?e=c:c!==a&&"object"==typeof c&&(d=c),b instanceof Date&&e===a?x(b.getTime(),d):b instanceof Date&&e!==a?(e=c,y(b.getTime(),e,d)):e===a?z(b,d):A(b,e,d)};Wb.delay=function(a,b){return N(b)||(b=Lb),a instanceof Date?C(this,a.getTime(),b):B(this,a,b)},Wb.throttle=function(a,b){return N(b)||(b=Lb),this.throttleWithSelector(function(){return rc(a,b)})},Wb.timestamp=function(a){return N(a)||(a=Lb),this.map(function(b){return{value:b,timestamp:a.now()}})},Wb.sample=function(a,b){return N(b)||(b=Lb),"number"==typeof a?D(this,qc(a,b)):D(this,a)},Wb.timeout=function(a,b,c){b||(b=fc(new Error("Timeout"))),N(c)||(c=Lb);var d=this,e=a instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new wc(function(f){var g=0,h=new Db,i=new SerialDisposable,j=!1,k=new SerialDisposable;i.setDisposable(h);var l=function(){var d=g;k.setDisposable(c[e](a,function(){g===d&&(T(b)&&(b=oc(b)),i.setDisposable(b.subscribe(f)))}))};return l(),h.setDisposable(d.subscribe(function(a){j||(g++,f.onNext(a),l())},function(a){j||(g++,f.onError(a))},function(){j||(g++,f.onCompleted())})),new yb(i,k)})},Wb.delaySubscription=function(a,b){return this.delayWithSelector(rc(a,N(b)?b:Lb),ac)},Wb.delayWithSelector=function(a,b){var c,d,e=this;return"function"==typeof a?d=a:(c=a,d=b),new wc(function(a){var b=new yb,f=!1,g=function(){f&&0===b.length&&a.onCompleted()},h=new SerialDisposable,i=function(){h.setDisposable(e.subscribe(function(c){var e;try{e=d(c)}catch(f){return void a.onError(f)}var h=new Db;b.add(h),h.setDisposable(e.subscribe(function(){a.onNext(c),b.remove(h),g()},a.onError.bind(a),function(){a.onNext(c),b.remove(h),g()}))},a.onError.bind(a),function(){f=!0,h.dispose(),g()}))};return c?h.setDisposable(c.subscribe(function(){i()},a.onError.bind(a),function(){i()})):i(),new yb(h,b)})},Wb.timeoutWithSelector=function(a,b,c){if(1===arguments.length){b=a;var a=dc()}c||(c=fc(new Error("Timeout")));var d=this;return new wc(function(e){var f=new SerialDisposable,g=new SerialDisposable,h=new Db;f.setDisposable(h);var i=0,j=!1,k=function(a){var b=i,d=function(){return i===b},h=new Db;g.setDisposable(h),h.setDisposable(a.subscribe(function(){d()&&f.setDisposable(c.subscribe(e)),h.dispose()},function(a){d()&&e.onError(a)},function(){d()&&f.setDisposable(c.subscribe(e))}))};k(a);var l=function(){var a=!j;return a&&i++,a};return h.setDisposable(d.subscribe(function(a){if(l()){e.onNext(a);var c;try{c=b(a)}catch(d){return void e.onError(d)}k(c)}},function(a){l()&&e.onError(a)},function(){l()&&e.onCompleted()})),new yb(f,g)})},Wb.throttleWithSelector=function(a){var b=this;return new wc(function(c){var d,e=!1,f=new SerialDisposable,g=0,h=b.subscribe(function(b){var h;try{h=a(b)}catch(i){return void c.onError(i)}e=!0,d=b,g++;var j=g,k=new Db;f.setDisposable(k),k.setDisposable(h.subscribe(function(){e&&g===j&&c.onNext(d),e=!1,k.dispose()},c.onError.bind(c),function(){e&&g===j&&c.onNext(d),e=!1,k.dispose()}))},function(a){f.dispose(),c.onError(a),e=!1,g++},function(){f.dispose(),e&&c.onNext(d),c.onCompleted(),e=!1,g++});return new yb(h,f)})},Wb.skipLastWithTime=function(a,b){N(b)||(b=Lb);var c=this;return new wc(function(d){var e=[];return c.subscribe(function(c){var f=b.now();for(e.push({interval:f,value:c});e.length>0&&f-e[0].interval>=a;)d.onNext(e.shift().value)},d.onError.bind(d),function(){for(var c=b.now();e.length>0&&c-e[0].interval>=a;)d.onNext(e.shift().value);d.onCompleted()})})},Wb.takeLastWithTime=function(a,b){var c=this;return N(b)||(b=Lb),new wc(function(d){var e=[];return c.subscribe(function(c){var d=b.now();for(e.push({interval:d,value:c});e.length>0&&d-e[0].interval>=a;)e.shift()},d.onError.bind(d),function(){for(var c=b.now();e.length>0;){var f=e.shift();c-f.interval<=a&&d.onNext(f.value)}d.onCompleted()})})},Wb.takeWithTime=function(a,b){var c=this;return N(b)||(b=Lb),new wc(function(d){return new yb(b.scheduleWithRelative(a,d.onCompleted.bind(d)),c.subscribe(d))})},Wb.skipWithTime=function(a,b){var c=this;return N(b)||(b=Lb),new wc(function(d){var e=!1;return new yb(b.scheduleWithRelative(a,function(){e=!0}),c.subscribe(function(a){e&&d.onNext(a)},d.onError.bind(d),d.onCompleted.bind(d)))})};var sc=function(a){function b(a){var b=this.source.publish(),c=b.subscribe(a),d=Cb,e=this.pauser.distinctUntilChanged().subscribe(function(a){a?d=b.connect():(d.dispose(),d=Cb)});return new yb(c,d,e)}function c(c,d){this.source=c,this.controller=new zc,this.pauser=d&&d.subscribe?this.controller.merge(d):this.controller,a.call(this,b)}return tb(c,a),c.prototype.pause=function(){this.controller.onNext(!1)},c.prototype.resume=function(){this.controller.onNext(!0)},c}(Zb);Wb.pausable=function(a){return new sc(this,a)};var tc=function(b){function c(b){var c,d=[],e=E(this.source,this.pauser.distinctUntilChanged().startWith(!1),function(a,b){return{data:a,shouldFire:b}}).subscribe(function(e){if(c!==a&&e.shouldFire!=c){if(e.shouldFire)for(;d.length>0;)b.onNext(d.shift())}else e.shouldFire?b.onNext(e.data):d.push(e.data);c=e.shouldFire},function(a){for(;d.length>0;)b.onNext(d.shift());b.onError(a)},function(){for(;d.length>0;)b.onNext(d.shift());b.onCompleted()});return e}function d(a,d){this.source=a,this.controller=new zc,this.pauser=d&&d.subscribe?this.controller.merge(d):this.controller,b.call(this,c)}return tb(d,b),d.prototype.pause=function(){this.controller.onNext(!1)},d.prototype.resume=function(){this.controller.onNext(!0)},d}(Zb);Wb.pausableBuffered=function(a){return new tc(this,a)},Wb.controlled=function(a){return null==a&&(a=!0),new uc(this,a)};var uc=function(a){function b(a){return this.source.subscribe(a)}function c(c,d){a.call(this,b),this.subject=new vc(d),this.source=c.multicast(this.subject).refCount()}return tb(c,a),c.prototype.request=function(a){return null==a&&(a=-1),this.subject.request(a)},c}(Zb),vc=L.ControlledSubject=function(a){function c(a){return this.subject.subscribe(a)}function d(b){null==b&&(b=!0),a.call(this,c),this.subject=new zc,this.enableQueue=b,this.queue=b?[]:null,this.requestedCount=0,this.requestedDisposable=Cb,this.error=null,this.hasFailed=!1,this.hasCompleted=!1,this.controlledDisposable=Cb}return tb(d,a),ub(d.prototype,Ub,{onCompleted:function(){b.call(this),this.hasCompleted=!0,this.enableQueue&&0!==this.queue.length||this.subject.onCompleted()},onError:function(a){b.call(this),this.hasFailed=!0,this.error=a,this.enableQueue&&0!==this.queue.length||this.subject.onError(a)},onNext:function(a){b.call(this);var c=!1;0===this.requestedCount?this.enableQueue&&this.queue.push(a):(-1!==this.requestedCount&&0===this.requestedCount--&&this.disposeCurrentRequest(),c=!0),c&&this.subject.onNext(a)},_processRequest:function(a){if(this.enableQueue){for(;this.queue.length>=a&&a>0;)this.subject.onNext(this.queue.shift()),a--;return 0!==this.queue.length?{numberOfItems:a,returnValue:!0}:{numberOfItems:a,returnValue:!1}}return this.hasFailed?(this.subject.onError(this.error),this.controlledDisposable.dispose(),this.controlledDisposable=Cb):this.hasCompleted&&(this.subject.onCompleted(),this.controlledDisposable.dispose(),this.controlledDisposable=Cb),{numberOfItems:a,returnValue:!1}},request:function(a){b.call(this),this.disposeCurrentRequest();var c=this,d=this._processRequest(a);return a=d.numberOfItems,d.returnValue?Cb:(this.requestedCount=a,this.requestedDisposable=Bb(function(){c.requestedCount=0}),this.requestedDisposable)},disposeCurrentRequest:function(){this.requestedDisposable.dispose(),this.requestedDisposable=Cb},dispose:function(){this.isDisposed=!0,this.error=null,this.subject.dispose(),this.requestedDisposable.dispose()}}),d}(Zb);Wb.exclusive=function(){var a=this;return new wc(function(b){var c=!1,d=!1,e=new Db,f=new yb;return f.add(e),e.setDisposable(a.subscribe(function(a){if(!c){c=!0,T(a)&&(a=oc(a));var e=new Db;f.add(e),e.setDisposable(a.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){f.remove(e),c=!1,d&&1===f.length&&b.onCompleted()}))}},b.onError.bind(b),function(){d=!0,c||1!==f.length||b.onCompleted()})),f})},Wb.exclusiveMap=function(a,b){var c=this;return new wc(function(d){var e=0,f=!1,g=!0,h=new Db,i=new yb;return i.add(h),h.setDisposable(c.subscribe(function(c){f||(f=!0,innerSubscription=new Db,i.add(innerSubscription),T(c)&&(c=oc(c)),innerSubscription.setDisposable(c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}d.onNext(g)},d.onError.bind(d),function(){i.remove(innerSubscription),f=!1,g&&1===i.length&&d.onCompleted()})))},d.onError.bind(d),function(){g=!0,1!==i.length||f||d.onCompleted()})),i})};var wc=L.AnonymousObservable=function(a){function b(a){return a&&"function"==typeof a.dispose?a:"function"==typeof a?Bb(a):Cb}function c(d){function e(a){var c=function(){try{e.setDisposable(b(d(e)))}catch(a){if(!e.fail(a))throw a}},e=new xc(a);return Jb.scheduleRequired()?Jb.schedule(c):c(),e}return this instanceof c?void a.call(this,e):new c(d)}return tb(c,a),c}(Zb),xc=function(a){function b(b){a.call(this),this.observer=b,this.m=new Db}tb(b,a);var c=b.prototype;return c.next=function(a){var b=!1;try{this.observer.onNext(a),b=!0}catch(c){throw c}finally{b||this.dispose()}},c.error=function(a){try{this.observer.onError(a)}catch(b){throw b}finally{this.dispose()}},c.completed=function(){try{this.observer.onCompleted()}catch(a){throw a}finally{this.dispose()}},c.setDisposable=function(a){this.m.setDisposable(a)},c.getDisposable=function(){return this.m.getDisposable()},c.disposable=function(a){return arguments.length?this.getDisposable():setDisposable(a)},c.dispose=function(){a.prototype.dispose.call(this),this.m.dispose()},b}(Xb),yc=function(a,b){this.subject=a,this.observer=b};yc.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1),this.observer=null}};var zc=L.Subject=function(a){function c(a){return b.call(this),this.isStopped?this.exception?(a.onError(this.exception),Cb):(a.onCompleted(),Cb):(this.observers.push(a),new yc(this,a))}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return tb(d,a),ub(d.prototype,Ub,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped)for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)},dispose:function(){this.isDisposed=!0,this.observers=null}}),d.create=function(a,b){return new Bc(a,b)},d}(Zb),Ac=L.AsyncSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),new yc(this,a);var c=this.exception,d=this.hasValue,e=this.value;return c?a.onError(c):d?(a.onNext(e),a.onCompleted()):a.onCompleted(),Cb}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return tb(d,a),ub(d.prototype,Ub,{hasObservers:function(){return b.call(this),this.observers.length>0},onCompleted:function(){var a,c,d;if(b.call(this),!this.isStopped){this.isStopped=!0;var e=this.observers.slice(0),f=this.value,g=this.hasValue;if(g)for(c=0,d=e.length;d>c;c++)a=e[c],a.onNext(f),a.onCompleted();else for(c=0,d=e.length;d>c;c++)e[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){b.call(this),this.isStopped||(this.value=a,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),d}(Zb),Bc=L.AnonymousSubject=function(a){function b(b,c){this.observer=b,this.observable=c,a.call(this,this.observable.subscribe.bind(this.observable))}return tb(b,a),ub(b.prototype,Ub,{onCompleted:function(){this.observer.onCompleted()},onError:function(a){this.observer.onError(a)},onNext:function(a){this.observer.onNext(a)}}),b}(Zb),Cc=L.BehaviorSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),a.onNext(this.value),new yc(this,a);var c=this.exception;return c?a.onError(c):a.onCompleted(),Cb}function d(b){a.call(this,c),this.value=b,this.observers=[],this.isDisposed=!1,this.isStopped=!1,this.exception=null}return tb(d,a),ub(d.prototype,Ub,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped){this.value=a;for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)}},dispose:function(){this.isDisposed=!0,this.observers=null,this.value=null,this.exception=null}}),d}(Zb),Dc=L.ReplaySubject=function(a){function c(a,b){this.subject=a,this.observer=b}function d(a){var d=new $b(this.scheduler,a),e=new c(this,d);b.call(this),this._trim(this.scheduler.now()),this.observers.push(d);for(var f=this.q.length,g=0,h=this.q.length;h>g;g++)d.onNext(this.q[g].value);return this.hasError?(f++,d.onError(this.error)):this.isStopped&&(f++,d.onCompleted()),d.ensureActive(f),e}function e(b,c,e){this.bufferSize=null==b?Number.MAX_VALUE:b,this.windowSize=null==c?Number.MAX_VALUE:c,this.scheduler=e||Jb,this.q=[],this.observers=[],this.isStopped=!1,this.isDisposed=!1,this.hasError=!1,this.error=null,a.call(this,d)}return c.prototype.dispose=function(){if(this.observer.dispose(),!this.subject.isDisposed){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1)}},tb(e,a),ub(e.prototype,Ub,{hasObservers:function(){return this.observers.length>0},_trim:function(a){for(;this.q.length>this.bufferSize;)this.q.shift();for(;this.q.length>0&&a-this.q[0].interval>this.windowSize;)this.q.shift()},onNext:function(a){var c;if(b.call(this),!this.isStopped){var d=this.scheduler.now();this.q.push({interval:d,value:a}),this._trim(d);for(var e=this.observers.slice(0),f=0,g=e.length;g>f;f++)c=e[f],c.onNext(a),c.ensureActive()}},onError:function(a){var c;if(b.call(this),!this.isStopped){this.isStopped=!0,this.error=a,this.hasError=!0;var d=this.scheduler.now();this._trim(d);for(var e=this.observers.slice(0),f=0,g=e.length;g>f;f++)c=e[f],c.onError(a),c.ensureActive();this.observers=[]}},onCompleted:function(){var a;if(b.call(this),!this.isStopped){this.isStopped=!0;var c=this.scheduler.now();this._trim(c);for(var d=this.observers.slice(0),e=0,f=d.length;f>e;e++)a=d[e],a.onCompleted(),a.ensureActive();this.observers=[]}},dispose:function(){this.isDisposed=!0,this.observers=null}}),e}(Zb);"function"==typeof define&&"object"==typeof define.amd&&define.amd?(G.Rx=L,define(function(){return L})):H&&I?J?(I.exports=L).Rx=L:H.Rx=L:G.Rx=L}).call(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.min.js b/ajax/libs/rxjs/2.3.9/rx.min.js new file mode 100644 index 000000000..0f310fd9b --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.min.js @@ -0,0 +1,2 @@ +(function(a){function b(){if(this.isDisposed)throw new Error(O)}function c(a){var b=typeof a;return a&&("function"==b||"object"==b)||!1}function d(a){var b=[];if(!c(a))return b;jb.nonEnumArgs&&a.length&&h(a)&&(a=lb.call(a));var d=jb.enumPrototypes&&"function"==typeof a,e=jb.enumErrorProps&&(a===db||a instanceof Error);for(var f in a)d&&"prototype"==f||e&&("message"==f||"name"==f)||b.push(f);if(jb.nonEnumShadows&&a!==eb){var g=a.constructor,i=-1,j=hb.length;if(a===(g&&g.prototype))var k=a===stringProto?_:a===db?W:ab.call(a),l=ib[k];for(;++i-1:void 0});return c.pop(),d.pop(),result}function k(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:lb.call(a)}function l(a,b){for(var c=new Array(a),d=0;a>d;d++)c[d]=b();return c}function m(a,b){this.scheduler=a,this.disposable=b,this.isDisposed=!1}function n(a){return"number"==typeof a&&z.isFinite(a)}function o(b){return b[P]!==a}function p(a){var b=+a;return 0===b?b:isNaN(b)?b:0>b?-1:1}function q(a){var b=+a.length;return isNaN(b)?0:0!==b&&n(b)?(b=p(b)*Math.floor(Math.abs(b)),0>=b?0:b>_b?_b:b):b}function r(a){return"[object Function]"===Object.prototype.toString.call(a)&&"function"==typeof a}function s(a,b){return new jc(function(c){var d=new xb,e=new SerialDisposable;return e.setDisposable(d),d.setDisposable(a.subscribe(c.onNext.bind(c),function(a){var d,f;try{f=b(a)}catch(g){return void c.onError(g)}M(f)&&(f=Yb(f)),d=new xb,e.setDisposable(d),d.setDisposable(f.subscribe(c))},c.onCompleted.bind(c))),e})}function t(a,b){var c=this;return new jc(function(d){var e=0,f=a.length;return c.subscribe(function(c){if(f>e){var g,h=a[e++];try{g=b(c,h)}catch(i){return void d.onError(i)}d.onNext(g)}else d.onCompleted()},d.onError.bind(d),d.onCompleted.bind(d))})}function u(a,b,c){return a.map(function(a,d){var e=b.call(c,a,d);return M(e)?Yb(e):e}).concatAll()}function v(a,b,c){for(var d=0,e=a.length;e>d;d++)if(c(a[d],b))return d;return-1}function w(a){this.comparer=a,this.set=[]}function x(a,b,c){return a.map(function(a,d){var e=b.call(c,a,d);return M(e)?Yb(e):e}).mergeObservable()}var y={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},z=y[typeof window]&&window||this,A=y[typeof exports]&&exports&&!exports.nodeType&&exports,B=y[typeof module]&&module&&!module.nodeType&&module,C=B&&B.exports===A&&A,D=y[typeof global]&&global;!D||D.global!==D&&D.window!==D||(z=D);var E={internals:{},config:{Promise:z.Promise},helpers:{}},F=E.helpers.noop=function(){},G=(E.helpers.notDefined=function(a){return"undefined"==typeof a},E.helpers.isScheduler=function(a){return a instanceof E.Scheduler}),H=E.helpers.identity=function(a){return a},I=(E.helpers.pluck=function(a){return function(b){return b[a]}},E.helpers.just=function(a){return function(){return a}},E.helpers.defaultNow=Date.now),J=E.helpers.defaultComparer=function(a,b){return kb(a,b)},K=E.helpers.defaultSubComparer=function(a,b){return a>b?1:b>a?-1:0},L=(E.helpers.defaultKeySerializer=function(a){return a.toString()},E.helpers.defaultError=function(a){throw a}),M=E.helpers.isPromise=function(a){return!!a&&"function"==typeof a.then},N=(E.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},E.helpers.not=function(a){return!a},"Argument out of range"),O="Object has been disposed",P="function"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";z.Set&&"function"==typeof(new z.Set)["@@iterator"]&&(P="@@iterator");var Q,R={done:!0,value:a},S="[object Arguments]",T="[object Array]",U="[object Boolean]",V="[object Date]",W="[object Error]",X="[object Function]",Y="[object Number]",Z="[object Object]",$="[object RegExp]",_="[object String]",ab=Object.prototype.toString,bb=Object.prototype.hasOwnProperty,cb=ab.call(arguments)==S,db=Error.prototype,eb=Object.prototype,fb=eb.propertyIsEnumerable;try{Q=!(ab.call(document)==Z&&!({toString:0}+""))}catch(gb){Q=!0}var hb=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ib={};ib[T]=ib[V]=ib[Y]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},ib[U]=ib[_]={constructor:!0,toString:!0,valueOf:!0},ib[W]=ib[X]=ib[$]={constructor:!0,toString:!0},ib[Z]={constructor:!0};var jb={};!function(){var a=function(){this.x=1},b=[];a.prototype={valueOf:1,y:1};for(var c in new a)b.push(c);for(c in arguments);jb.enumErrorProps=fb.call(db,"message")||fb.call(db,"name"),jb.enumPrototypes=fb.call(a,"prototype"),jb.nonEnumArgs=0!=c,jb.nonEnumShadows=!/valueOf/.test(b)}(1),cb||(h=function(a){return a&&"object"==typeof a?bb.call(a,"callee"):!1}),i(/x/)&&(i=function(a){return"function"==typeof a&&ab.call(a)==X});var kb=E.internals.isEqual=function(a,b){return j(a,b,[],[])},lb=Array.prototype.slice,mb=({}.hasOwnProperty,this.inherits=E.internals.inherits=function(a,b){function c(){this.constructor=a}c.prototype=b.prototype,a.prototype=new c}),nb=E.internals.addProperties=function(a){for(var b=lb.call(arguments,1),c=0,d=b.length;d>c;c++){var e=b[c];for(var f in e)a[f]=e[f]}},ob=E.internals.addRef=function(a,b){return new jc(function(c){return new sb(b.getDisposable(),a.subscribe(c))})},pb=function(a,b){this.id=a,this.value=b};pb.prototype.compareTo=function(a){var b=this.value.compareTo(a.value);return 0===b&&(b=this.id-a.id),b};var qb=E.internals.PriorityQueue=function(a){this.items=new Array(a),this.length=0},rb=qb.prototype;rb.isHigherPriority=function(a,b){return this.items[a].compareTo(this.items[b])<0},rb.percolate=function(a){if(!(a>=this.length||0>a)){var b=a-1>>1;if(!(0>b||b===a)&&this.isHigherPriority(a,b)){var c=this.items[a];this.items[a]=this.items[b],this.items[b]=c,this.percolate(b)}}},rb.heapify=function(b){if(b===a&&(b=0),!(b>=this.length||0>b)){var c=2*b+1,d=2*b+2,e=b;if(cb;b++)a[b].dispose()}},tb.toArray=function(){return this.disposables.slice(0)};var ub=E.Disposable=function(a){this.isDisposed=!1,this.action=a||F};ub.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var vb=ub.create=function(a){return new ub(a)},wb=ub.empty={dispose:F},xb=E.SingleAssignmentDisposable=SerialDisposable=E.SerialDisposable=function(){function a(){this.isDisposed=!1,this.current=null}var b=a.prototype;return b.getDisposable=function(){return this.current},b.setDisposable=function(a){var b,c=this.isDisposed;c||(b=this.current,this.current=a),b&&b.dispose(),c&&a&&a.dispose()},b.dispose=function(){var a;this.isDisposed||(this.isDisposed=!0,a=this.current,this.current=null),a&&a.dispose()},a}(),yb=E.RefCountDisposable=function(){function a(a){this.disposable=a,this.disposable.count++,this.isInnerDisposed=!1}function b(a){this.underlyingDisposable=a,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return a.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},b.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},b.prototype.getDisposable=function(){return this.isDisposed?wb:new a(this)},b}();m.prototype.dispose=function(){var a=this;this.scheduler.schedule(function(){a.isDisposed||(a.isDisposed=!0,a.disposable.dispose())})};var zb=E.internals.ScheduledItem=function(a,b,c,d,e){this.scheduler=a,this.state=b,this.action=c,this.dueTime=d,this.comparer=e||K,this.disposable=new xb};zb.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},zb.prototype.compareTo=function(a){return this.comparer(this.dueTime,a.dueTime)},zb.prototype.isCancelled=function(){return this.disposable.isDisposed},zb.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var Ab=E.Scheduler=function(){function a(a,b,c,d){this.now=a,this._schedule=b,this._scheduleRelative=c,this._scheduleAbsolute=d}function b(a,b){return b(),wb}var c=a.prototype;return c.schedule=function(a){return this._schedule(a,b)},c.scheduleWithState=function(a,b){return this._schedule(a,b)},c.scheduleWithRelative=function(a,c){return this._scheduleRelative(c,a,b)},c.scheduleWithRelativeAndState=function(a,b,c){return this._scheduleRelative(a,b,c)},c.scheduleWithAbsolute=function(a,c){return this._scheduleAbsolute(c,a,b)},c.scheduleWithAbsoluteAndState=function(a,b,c){return this._scheduleAbsolute(a,b,c)},a.now=I,a.normalize=function(a){return 0>a&&(a=0),a},a}(),Bb=Ab.normalize;!function(a){function b(a,b){var c=b.first,d=b.second,e=new sb,f=function(b){d(b,function(b){var c=!1,d=!1,g=a.scheduleWithState(b,function(a,b){return c?e.remove(g):d=!0,f(b),wb});d||(e.add(g),c=!0)})};return f(c),e}function c(a,b,c){var d=b.first,e=b.second,f=new sb,g=function(b){e(b,function(b,d){var e=!1,h=!1,i=a[c].call(a,b,d,function(a,b){return e?f.remove(i):h=!0,g(b),wb});h||(f.add(i),e=!0)})};return g(d),f}function d(a,b){a(function(c){b(a,c)})}a.scheduleRecursive=function(a){return this.scheduleRecursiveWithState(a,function(a,b){a(function(){b(a)})})},a.scheduleRecursiveWithState=function(a,c){return this.scheduleWithState({first:a,second:c},b)},a.scheduleRecursiveWithRelative=function(a,b){return this.scheduleRecursiveWithRelativeAndState(b,a,d)},a.scheduleRecursiveWithRelativeAndState=function(a,b,d){return this._scheduleRelative({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithRelativeAndState")})},a.scheduleRecursiveWithAbsolute=function(a,b){return this.scheduleRecursiveWithAbsoluteAndState(b,a,d)},a.scheduleRecursiveWithAbsoluteAndState=function(a,b,d){return this._scheduleAbsolute({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithAbsoluteAndState")})}}(Ab.prototype),function(){Ab.prototype.schedulePeriodic=function(a,b){return this.schedulePeriodicWithState(null,a,b)},Ab.prototype.schedulePeriodicWithState=function(a,b,c){var d=a,e=setInterval(function(){d=c(d)},b);return vb(function(){clearInterval(e)})}}(Ab.prototype),function(a){a.catchError=a["catch"]=function(a){return new Gb(this,a)}}(Ab.prototype);var Cb,Db=(E.internals.SchedulePeriodicRecursive=function(){function a(a,b){b(0,this._period);try{this._state=this._action(this._state)}catch(c){throw this._cancel.dispose(),c}}function b(a,b,c,d){this._scheduler=a,this._state=b,this._period=c,this._action=d}return b.prototype.start=function(){var b=new xb;return this._cancel=b,b.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,a.bind(this))),b},b}(),Ab.immediate=function(){function a(a,b){return b(this,a)}function b(a,b,c){for(var d=Bb(d);d-this.now()>0;);return c(this,a)}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new Ab(I,a,b,c)}()),Eb=Ab.currentThread=function(){function a(a){for(var b;a.length>0;)if(b=a.dequeue(),!b.isCancelled()){for(;b.dueTime-Ab.now()>0;);b.isCancelled()||b.invoke()}}function b(a,b){return this.scheduleWithRelativeAndState(a,0,b)}function c(b,c,d){var f=this.now()+Ab.normalize(c),g=new zb(this,b,d,f);if(e)e.enqueue(g);else{e=new qb(4),e.enqueue(g);try{a(e)}catch(h){throw h}finally{e=null}}return g.disposable}function d(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}var e,f=new Ab(I,b,c,d);return f.scheduleRequired=function(){return!e},f.ensureTrampoline=function(a){e?a():this.schedule(a)},f}(),Fb=F;!function(){function a(){if(!z.postMessage||z.importScripts)return!1;var a=!1,b=z.onmessage;return z.onmessage=function(){a=!0},z.postMessage("","*"),z.onmessage=b,a}function b(a){if("string"==typeof a.data&&a.data.substring(0,f.length)===f){var b=a.data.substring(f.length),c=g[b];c(),delete g[b]}}var c=RegExp("^"+String(ab).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),d="function"==typeof(d=D&&C&&D.setImmediate)&&!c.test(d)&&d,e="function"==typeof(e=D&&C&&D.clearImmediate)&&!c.test(e)&&e;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))Cb=process.nextTick;else if("function"==typeof d)Cb=d,Fb=e;else if(a()){var f="ms.rx.schedule"+Math.random(),g={},h=0;z.addEventListener?z.addEventListener("message",b,!1):z.attachEvent("onmessage",b,!1),Cb=function(a){var b=h++;g[b]=a,z.postMessage(f+b,"*")}}else if(z.MessageChannel){var i=new z.MessageChannel,j={},k=0;i.port1.onmessage=function(a){var b=a.data,c=j[b];c(),delete j[b]},Cb=function(a){var b=k++;j[b]=a,i.port2.postMessage(b)}}else"document"in z&&"onreadystatechange"in z.document.createElement("script")?Cb=function(a){var b=z.document.createElement("script");b.onreadystatechange=function(){a(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},z.document.documentElement.appendChild(b)}:(Cb=function(a){return setTimeout(a,0)},Fb=clearTimeout)}();var Gb=(Ab.timeout=function(){function a(a,b){var c=this,d=new xb,e=Cb(function(){d.isDisposed||d.setDisposable(b(c,a))});return new sb(d,vb(function(){Fb(e)}))}function b(a,b,c){var d=this,e=Ab.normalize(b);if(0===e)return d.scheduleWithState(a,c);var f=new xb,g=setTimeout(function(){f.isDisposed||f.setDisposable(c(d,a))},e);return new sb(f,vb(function(){clearTimeout(g)}))}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new Ab(I,a,b,c)}(),function(a){function b(){return this._scheduler.now()}function c(a,b){return this._scheduler.scheduleWithState(a,this._wrap(b))}function d(a,b,c){return this._scheduler.scheduleWithRelativeAndState(a,b,this._wrap(c))}function e(a,b,c){return this._scheduler.scheduleWithAbsoluteAndState(a,b,this._wrap(c))}function f(f,g){this._scheduler=f,this._handler=g,this._recursiveOriginal=null,this._recursiveWrapper=null,a.call(this,b,c,d,e)}return mb(f,a),f.prototype._clone=function(a){return new f(a,this._handler)},f.prototype._wrap=function(a){var b=this;return function(c,d){try{return a(b._getRecursiveWrapper(c),d)}catch(e){if(!b._handler(e))throw e;return wb}}},f.prototype._getRecursiveWrapper=function(a){if(this._recursiveOriginal!==a){this._recursiveOriginal=a;var b=this._clone(a);b._recursiveOriginal=a,b._recursiveWrapper=b,this._recursiveWrapper=b}return this._recursiveWrapper},f.prototype.schedulePeriodicWithState=function(a,b,c){var d=this,e=!1,f=new xb;return f.setDisposable(this._scheduler.schedulePeriodicWithState(a,b,function(a){if(e)return null;try{return c(a)}catch(b){if(e=!0,!d._handler(b))throw b;return f.dispose(),null}})),f},f}(Ab)),Hb=E.Notification=function(){function a(a,b){this.hasValue=null==b?!1:b,this.kind=a}return a.prototype.accept=function(a,b,c){return a&&"object"==typeof a?this._acceptObservable(a):this._accept(a,b,c)},a.prototype.toObservable=function(a){var b=this;return G(a)||(a=Db),new jc(function(c){return a.schedule(function(){b._acceptObservable(c),"N"===b.kind&&c.onCompleted()})})},a}(),Ib=Hb.createOnNext=function(){function a(a){return a(this.value)}function b(a){return a.onNext(this.value)}function c(){return"OnNext("+this.value+")"}return function(d){var e=new Hb("N",!0);return e.value=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),Jb=Hb.createOnError=function(){function a(a,b){return b(this.exception)}function b(a){return a.onError(this.exception)}function c(){return"OnError("+this.exception+")"}return function(d){var e=new Hb("E");return e.exception=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),Kb=Hb.createOnCompleted=function(){function a(a,b,c){return c()}function b(a){return a.onCompleted()}function c(){return"OnCompleted()"}return function(){var d=new Hb("C");return d._accept=a,d._acceptObservable=b,d.toString=c,d}}(),Lb=E.internals.Enumerator=function(a){this._next=a};Lb.prototype.next=function(){return this._next()},Lb.prototype[P]=function(){return this};var Mb=E.internals.Enumerable=function(a){this._iterator=a};Mb.prototype[P]=function(){return this._iterator()},Mb.prototype.concat=function(){var a=this;return new jc(function(b){var c;try{c=a[P]()}catch(d){return void b.onError()}var e,f=new SerialDisposable,g=Db.scheduleRecursive(function(a){var d;if(!e){try{d=c.next()}catch(g){return void b.onError(g)}if(d.done)return void b.onCompleted();var h=d.value;M(h)&&(h=Yb(h));var i=new xb;f.setDisposable(i),i.setDisposable(h.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){a()}))}});return new sb(f,g,vb(function(){e=!0}))})},Mb.prototype.catchException=function(){var a=this;return new jc(function(b){var c;try{c=a[P]()}catch(d){return void b.onError()}var e,f,g=new SerialDisposable,h=Db.scheduleRecursive(function(a){if(!e){var d;try{d=c.next()}catch(h){return void b.onError(h)}if(d.done)return void(f?b.onError(f):b.onCompleted());var i=d.value;M(i)&&(i=Yb(i));var j=new xb;g.setDisposable(j),j.setDisposable(i.subscribe(b.onNext.bind(b),function(b){f=b,a()},b.onCompleted.bind(b)))}});return new sb(g,h,vb(function(){e=!0}))})};var Nb=Mb.repeat=function(a,b){return null==b&&(b=-1),new Mb(function(){var c=b;return new Lb(function(){return 0===c?R:(c>0&&c--,{done:!1,value:a})})})},Ob=Mb.forEach=function(a,b,c){return b||(b=H),new Mb(function(){var d=-1;return new Lb(function(){return++d0&&(a=!this.isAcquired,this.isAcquired=!0),a&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(a){var c;if(!(b.queue.length>0))return void(b.isAcquired=!1);c=b.queue.shift();try{c()}catch(d){throw b.queue=[],b.hasFaulted=!0,d}a()}))},b.prototype.dispose=function(){a.prototype.dispose.call(this),this.disposable.dispose()},b}(Sb),Wb=function(a){function b(){a.apply(this,arguments)}return mb(b,a),b.prototype.next=function(b){a.prototype.next.call(this,b),this.ensureActive()},b.prototype.error=function(b){a.prototype.error.call(this,b),this.ensureActive()},b.prototype.completed=function(){a.prototype.completed.call(this),this.ensureActive()},b}(Vb),Xb=E.Observable=function(){function a(a){this._subscribe=a}return Rb=a.prototype,Rb.subscribe=Rb.forEach=function(a,b,c){var d="object"==typeof a?a:Qb(a,b,c);return this._subscribe(d)},a}();Rb.observeOn=function(a){var b=this;return new jc(function(c){return b.subscribe(new Wb(a,c))})},Rb.subscribeOn=function(a){var b=this;return new jc(function(c){var d=new xb,e=new SerialDisposable;return e.setDisposable(d),d.setDisposable(a.schedule(function(){e.setDisposable(new m(a,b.subscribe(c)))})),e})};var Yb=Xb.fromPromise=function(a){return Zb(function(){var b=new E.AsyncSubject;return a.then(function(a){b.isDisposed||(b.onNext(a),b.onCompleted())},b.onError.bind(b)),b})};Rb.toPromise=function(a){if(a||(a=E.config.Promise),!a)throw new Error("Promise type not provided nor in Rx.config.Promise");var b=this;return new a(function(a,c){var d,e=!1;b.subscribe(function(a){d=a,e=!0},function(a){c(a)},function(){e&&a(d)})})},Rb.toArray=function(){var a=this;return new jc(function(b){var c=[];return a.subscribe(c.push.bind(c),b.onError.bind(b),function(){b.onNext(c),b.onCompleted()})})},Xb.create=Xb.createWithDisposable=function(a){return new jc(a)};var Zb=Xb.defer=function(a){return new jc(function(b){var c;try{c=a()}catch(d){return dc(d).subscribe(b)}return M(c)&&(c=Yb(c)),c.subscribe(b)})},$b=Xb.empty=function(a){return G(a)||(a=Db),new jc(function(b){return a.schedule(function(){b.onCompleted()})})},_b=Math.pow(2,53)-1;Xb.from=function(a,b,c,d){if(null==a)throw new Error("iterable cannot be null.");if(b&&!r(b))throw new Error("mapFn when provided must be a function");return G(d)||(d=Eb),new jc(function(e){var f=Object(a),g=o(f),h=g?0:q(f),i=g?f[P]():null,j=0;return d.scheduleRecursive(function(a){if(h>j||g){var d;if(g){var k=i.next();if(k.done)return void e.onCompleted();d=k.value}else d=f[j];if(b&&r(b))try{d=c?b.call(c,d,j):b(d,j)}catch(l){return void e.onError(l)}e.onNext(d),j++,a()}else e.onCompleted()})})};var ac=Xb.fromArray=function(a,b){return G(b)||(b=Eb),new jc(function(c){var d=0,e=a.length;return b.scheduleRecursive(function(b){e>d?(c.onNext(a[d++]),b()):c.onCompleted()})})};Xb.generate=function(a,b,c,d,e){return G(e)||(e=Eb),new jc(function(f){var g=!0,h=a;return e.scheduleRecursive(function(a){var e,i;try{g?g=!1:h=c(h),e=b(h),e&&(i=d(h))}catch(j){return void f.onError(j)}e?(f.onNext(i),a()):f.onCompleted()})})};var bc=Xb.never=function(){return new jc(function(){return wb})};Xb.of=function(){for(var a=arguments.length,b=new Array(a),c=0;a>c;c++)b[c]=arguments[c];return ac(b)};Xb.ofWithScheduler=function(a){for(var b=arguments.length-1,c=new Array(b),d=0;b>d;d++)c[d]=arguments[d+1];return ac(c,a)};Xb.range=function(a,b,c){return G(c)||(c=Eb),new jc(function(d){return c.scheduleRecursiveWithState(0,function(c,e){b>c?(d.onNext(a+c),e(c+1)):d.onCompleted()})})},Xb.repeat=function(a,b,c){return G(c)||(c=Eb),cc(a,c).repeat(null==b?-1:b)};var cc=Xb["return"]=Xb.returnValue=Xb.just=function(a,b){return G(b)||(b=Db),new jc(function(c){return b.schedule(function(){c.onNext(a),c.onCompleted()})})},dc=Xb["throw"]=Xb.throwException=function(a,b){return G(b)||(b=Db),new jc(function(c){return b.schedule(function(){c.onError(a)})})};Xb.using=function(a,b){return new jc(function(c){var d,e,f=wb;try{d=a(),d&&(f=d),e=b(d)}catch(g){return new sb(dc(g).subscribe(c),f)}return new sb(e.subscribe(c),f)})},Rb.amb=function(a){var b=this;return new jc(function(c){function d(){f||(f=g,j.dispose())}function e(){f||(f=h,i.dispose())}var f,g="L",h="R",i=new xb,j=new xb;return M(a)&&(a=Yb(a)),i.setDisposable(b.subscribe(function(a){d(),f===g&&c.onNext(a)},function(a){d(),f===g&&c.onError(a)},function(){d(),f===g&&c.onCompleted()})),j.setDisposable(a.subscribe(function(a){e(),f===h&&c.onNext(a)},function(a){e(),f===h&&c.onError(a)},function(){e(),f===h&&c.onCompleted()})),new sb(i,j)})},Xb.amb=function(){function a(a,b){return a.amb(b)}for(var b=bc(),c=k(arguments,0),d=0,e=c.length;e>d;d++)b=a(b,c[d]);return b},Rb["catch"]=Rb.catchException=function(a){return"function"==typeof a?s(this,a):ec([this,a])};var ec=Xb.catchException=Xb["catch"]=function(){var a=k(arguments,0);return Ob(a).catchException()};Rb.combineLatest=function(){var a=lb.call(arguments);return Array.isArray(a[0])?a[0].unshift(this):a.unshift(this),fc.apply(this,a)};var fc=Xb.combineLatest=function(){var a=lb.call(arguments),b=a.pop();return Array.isArray(a[0])&&(a=a[0]),new jc(function(c){function d(a){var d;if(h[a]=!0,i||(i=h.every(H))){try{d=b.apply(null,k)}catch(e){return void c.onError(e)}c.onNext(d)}else j.filter(function(b,c){return c!==a}).every(H)&&c.onCompleted()}function e(a){j[a]=!0,j.every(H)&&c.onCompleted()}for(var f=function(){return!1},g=a.length,h=l(g,f),i=!1,j=l(g,f),k=new Array(g),m=new Array(g),n=0;g>n;n++)!function(b){var f=a[b],g=new xb;M(f)&&(f=Yb(f)),g.setDisposable(f.subscribe(function(a){k[b]=a,d(b)},c.onError.bind(c),function(){e(b)})),m[b]=g}(n);return new sb(m)})};Rb.concat=function(){var a=lb.call(arguments,0);return a.unshift(this),gc.apply(this,a)};var gc=Xb.concat=function(){var a=k(arguments,0);return Ob(a).concat()};Rb.concatObservable=Rb.concatAll=function(){return this.merge(1)},Rb.merge=function(a){if("number"!=typeof a)return hc(this,a);var b=this;return new jc(function(c){function d(a){var b=new xb;f.add(b),M(a)&&(a=Yb(a)),b.setDisposable(a.subscribe(c.onNext.bind(c),c.onError.bind(c),function(){f.remove(b),h.length>0?d(h.shift()):(e--,g&&0===e&&c.onCompleted())}))}var e=0,f=new sb,g=!1,h=[];return f.add(b.subscribe(function(b){a>e?(e++,d(b)):h.push(b)},c.onError.bind(c),function(){g=!0,0===e&&c.onCompleted()})),f})};var hc=Xb.merge=function(){var a,b;return arguments[0]?arguments[0].now?(a=arguments[0],b=lb.call(arguments,1)):(a=Db,b=lb.call(arguments,0)):(a=Db,b=lb.call(arguments,1)),Array.isArray(b[0])&&(b=b[0]),ac(b,a).mergeObservable()};Rb.mergeObservable=Rb.mergeAll=function(){var a=this;return new jc(function(b){var c=new sb,d=!1,e=new xb;return c.add(e),e.setDisposable(a.subscribe(function(a){var e=new xb;c.add(e),M(a)&&(a=Yb(a)),e.setDisposable(a.subscribe(function(a){b.onNext(a)},b.onError.bind(b),function(){c.remove(e),d&&1===c.length&&b.onCompleted()}))},b.onError.bind(b),function(){d=!0,1===c.length&&b.onCompleted()})),c})},Rb.onErrorResumeNext=function(a){if(!a)throw new Error("Second observable is required");return ic([this,a])};var ic=Xb.onErrorResumeNext=function(){var a=k(arguments,0);return new jc(function(b){var c=0,d=new SerialDisposable,e=Db.scheduleRecursive(function(e){var f,g;c0})){try{f=h.map(function(a){return a.shift()}),e=c.apply(a,f)}catch(g){return void d.onError(g)}d.onNext(e)}else i.filter(function(a,c){return c!==b}).every(H)&&d.onCompleted()}function f(a){i[a]=!0,i.every(function(a){return a})&&d.onCompleted()}for(var g=b.length,h=l(g,function(){return[]}),i=l(g,function(){return!1}),j=new Array(g),k=0;g>k;k++)!function(a){var c=b[a],g=new xb;M(c)&&(c=Yb(c)),g.setDisposable(c.subscribe(function(b){h[a].push(b),e(a)},d.onError.bind(d),function(){f(a)})),j[a]=g}(k);return new sb(j)})},Xb.zip=function(){var a=lb.call(arguments,0),b=a.shift();return b.zip.apply(b,a)},Xb.zipArray=function(){var a=k(arguments,0);return new jc(function(b){function c(a){if(f.every(function(a){return a.length>0})){var c=f.map(function(a){return a.shift()});b.onNext(c)}else if(g.filter(function(b,c){return c!==a}).every(H))return void b.onCompleted()}function d(a){return g[a]=!0,g.every(H)?void b.onCompleted():void 0}for(var e=a.length,f=l(e,function(){return[]}),g=l(e,function(){return!1}),h=new Array(e),i=0;e>i;i++)!function(e){h[e]=new xb,h[e].setDisposable(a[e].subscribe(function(a){f[e].push(a),c(e)},b.onError.bind(b),function(){d(e)}))}(i);var j=new sb(h);return j.add(vb(function(){for(var a=0,b=f.length;b>a;a++)f[a]=[]})),j})},Rb.asObservable=function(){var a=this;return new jc(function(b){return a.subscribe(b) +})},Rb.bufferWithCount=function(a,b){return"number"!=typeof b&&(b=a),this.windowWithCount(a,b).selectMany(function(a){return a.toArray()}).where(function(a){return a.length>0})},Rb.dematerialize=function(){var a=this;return new jc(function(b){return a.subscribe(function(a){return a.accept(b)},b.onError.bind(b),b.onCompleted.bind(b))})},Rb.distinctUntilChanged=function(a,b){var c=this;return a||(a=H),b||(b=J),new jc(function(d){var e,f=!1;return c.subscribe(function(c){var g,h=!1;try{g=a(c)}catch(i){return void d.onError(i)}if(f)try{h=b(e,g)}catch(i){return void d.onError(i)}f&&h||(f=!0,e=g,d.onNext(c))},d.onError.bind(d),d.onCompleted.bind(d))})},Rb["do"]=Rb.doAction=Rb.tap=function(a,b,c){var d,e=this;return"function"==typeof a?d=a:(d=a.onNext.bind(a),b=a.onError.bind(a),c=a.onCompleted.bind(a)),new jc(function(a){return e.subscribe(function(b){try{d(b)}catch(c){a.onError(c)}a.onNext(b)},function(c){if(b){try{b(c)}catch(d){a.onError(d)}a.onError(c)}else a.onError(c)},function(){if(c){try{c()}catch(b){a.onError(b)}a.onCompleted()}else a.onCompleted()})})},Rb["finally"]=Rb.finallyAction=function(a){var b=this;return new jc(function(c){var d;try{d=b.subscribe(c)}catch(e){throw a(),e}return vb(function(){try{d.dispose()}catch(b){throw b}finally{a()}})})},Rb.ignoreElements=function(){var a=this;return new jc(function(b){return a.subscribe(F,b.onError.bind(b),b.onCompleted.bind(b))})},Rb.materialize=function(){var a=this;return new jc(function(b){return a.subscribe(function(a){b.onNext(Ib(a))},function(a){b.onNext(Jb(a)),b.onCompleted()},function(){b.onNext(Kb()),b.onCompleted()})})},Rb.repeat=function(a){return Nb(this,a).concat()},Rb.retry=function(a){return Nb(this,a).catchException()},Rb.scan=function(){var a,b,c=!1,d=this;return 2===arguments.length?(c=!0,a=arguments[0],b=arguments[1]):b=arguments[0],new jc(function(e){var f,g,h;return d.subscribe(function(d){try{h||(h=!0),f?g=b(g,d):(g=c?b(a,d):d,f=!0)}catch(i){return void e.onError(i)}e.onNext(g)},e.onError.bind(e),function(){!h&&c&&e.onNext(a),e.onCompleted()})})},Rb.skipLast=function(a){var b=this;return new jc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&c.onNext(d.shift())},c.onError.bind(c),c.onCompleted.bind(c))})},Rb.startWith=function(){var a,b,c=0;return arguments.length&&"now"in Object(arguments[0])?(b=arguments[0],c=1):b=Db,a=lb.call(arguments,c),Ob([ac(a,b),this]).concat()},Rb.takeLast=function(a){var b=this;return new jc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&d.shift()},c.onError.bind(c),function(){for(;d.length>0;)c.onNext(d.shift());c.onCompleted()})})},Rb.takeLastBuffer=function(a){var b=this;return new jc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&d.shift()},c.onError.bind(c),function(){c.onNext(d),c.onCompleted()})})},Rb.windowWithCount=function(a,b){var c=this;if(0>=a)throw new Error(N);if(1===arguments.length&&(b=a),0>=b)throw new Error(N);return new jc(function(d){var e=new xb,f=new yb(e),g=0,h=[],i=function(){var a=new mc;h.push(a),d.onNext(ob(a,f))};return i(),e.setDisposable(c.subscribe(function(c){for(var d,e=0,f=h.length;f>e;e++)h[e].onNext(c);var j=g-a+1;j>=0&&j%b===0&&(d=h.shift(),d.onCompleted()),g++,g%b===0&&i()},function(a){for(;h.length>0;)h.shift().onError(a);d.onError(a)},function(){for(;h.length>0;)h.shift().onCompleted();d.onCompleted()})),f})},Rb.selectConcat=Rb.concatMap=function(a,b,c){return b?this.concatMap(function(c,d){var e=a(c,d),f=M(e)?Yb(e):e;return f.map(function(a){return b(c,a,d)})}):"function"==typeof a?u(this,a,c):u(this,function(){return a})},Rb.concatMapObserver=Rb.selectConcatObserver=function(a,b,c,d){var e=this;return new jc(function(f){var g=0;return e.subscribe(function(b){var c;try{c=a.call(d,b,g++)}catch(e){return void f.onError(e)}M(c)&&(c=Yb(c)),f.onNext(c)},function(a){var c;try{c=b.call(d,a)}catch(e){return void f.onError(e)}M(c)&&(c=Yb(c)),f.onNext(c),f.onCompleted()},function(){var a;try{a=c.call(d)}catch(b){return void f.onError(b)}M(a)&&(a=Yb(a)),f.onNext(a),f.onCompleted()})}).concatAll()},Rb.defaultIfEmpty=function(b){var c=this;return b===a&&(b=null),new jc(function(a){var d=!1;return c.subscribe(function(b){d=!0,a.onNext(b)},a.onError.bind(a),function(){d||a.onNext(b),a.onCompleted()})})},w.prototype.push=function(a){var b=-1===v(this.set,a,this.comparer);return b&&this.set.push(a),b},Rb.distinct=function(a,b){var c=this;return b||(b=J),new jc(function(d){var e=new w(b);return c.subscribe(function(b){var c=b;if(a)try{c=a(b)}catch(f){return void d.onError(f)}e.push(c)&&d.onNext(b)},d.onError.bind(d),d.onCompleted.bind(d))})},Rb.select=Rb.map=function(a,b){var c=this;return new jc(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},Rb.pluck=function(a){return this.select(function(b){return b[a]})},Rb.flatMapObserver=Rb.selectManyObserver=function(a,b,c,d){var e=this;return new jc(function(f){var g=0;return e.subscribe(function(b){var c;try{c=a.call(d,b,g++)}catch(e){return void f.onError(e)}M(c)&&(c=Yb(c)),f.onNext(c)},function(a){var c;try{c=b.call(d,a)}catch(e){return void f.onError(e)}M(c)&&(c=Yb(c)),f.onNext(c),f.onCompleted()},function(){var a;try{a=c.call(d)}catch(b){return void f.onError(b)}M(a)&&(a=Yb(a)),f.onNext(a),f.onCompleted()})}).mergeAll()},Rb.selectMany=Rb.flatMap=function(a,b,c){return b?this.flatMap(function(c,d){var e=a(c,d),f=M(e)?Yb(e):e;return f.map(function(a){return b(c,a,d)})},c):"function"==typeof a?x(this,a,c):x(this,function(){return a})},Rb.selectSwitch=Rb.flatMapLatest=Rb.switchMap=function(a,b){return this.select(a,b).switchLatest()},Rb.skip=function(a){if(0>a)throw new Error(N);var b=this;return new jc(function(c){var d=a;return b.subscribe(function(a){0>=d?c.onNext(a):d--},c.onError.bind(c),c.onCompleted.bind(c))})},Rb.skipWhile=function(a,b){var c=this;return new jc(function(d){var e=0,f=!1;return c.subscribe(function(g){if(!f)try{f=!a.call(b,g,e++,c)}catch(h){return void d.onError(h)}f&&d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},Rb.take=function(a,b){if(0>a)throw new Error(N);if(0===a)return $b(b);var c=this;return new jc(function(b){var d=a;return c.subscribe(function(a){d>0&&(d--,b.onNext(a),0===d&&b.onCompleted())},b.onError.bind(b),b.onCompleted.bind(b))})},Rb.takeWhile=function(a,b){var c=this;return new jc(function(d){var e=0,f=!0;return c.subscribe(function(g){if(f){try{f=a.call(b,g,e++,c)}catch(h){return void d.onError(h)}f?d.onNext(g):d.onCompleted()}},d.onError.bind(d),d.onCompleted.bind(d))})},Rb.where=Rb.filter=function(a,b){var c=this;return new jc(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}g&&d.onNext(f)},d.onError.bind(d),d.onCompleted.bind(d))})},Rb.exclusive=function(){var a=this;return new jc(function(b){var c=!1,d=!1,e=new xb,f=new sb;return f.add(e),e.setDisposable(a.subscribe(function(a){if(!c){c=!0,M(a)&&(a=Yb(a));var e=new xb;f.add(e),e.setDisposable(a.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){f.remove(e),c=!1,d&&1===f.length&&b.onCompleted()}))}},b.onError.bind(b),function(){d=!0,c||1!==f.length||b.onCompleted()})),f})},Rb.exclusiveMap=function(a,b){var c=this;return new jc(function(d){var e=0,f=!1,g=!0,h=new xb,i=new sb;return i.add(h),h.setDisposable(c.subscribe(function(c){f||(f=!0,innerSubscription=new xb,i.add(innerSubscription),M(c)&&(c=Yb(c)),innerSubscription.setDisposable(c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return void d.onError(h)}d.onNext(g)},d.onError.bind(d),function(){i.remove(innerSubscription),f=!1,g&&1===i.length&&d.onCompleted()})))},d.onError.bind(d),function(){g=!0,1!==i.length||f||d.onCompleted()})),i})};var jc=E.AnonymousObservable=function(a){function b(a){return a&&"function"==typeof a.dispose?a:"function"==typeof a?vb(a):wb}function c(d){function e(a){var c=function(){try{e.setDisposable(b(d(e)))}catch(a){if(!e.fail(a))throw a}},e=new kc(a);return Eb.scheduleRequired()?Eb.schedule(c):c(),e}return this instanceof c?void a.call(this,e):new c(d)}return mb(c,a),c}(Xb),kc=function(a){function b(b){a.call(this),this.observer=b,this.m=new xb}mb(b,a);var c=b.prototype;return c.next=function(a){var b=!1;try{this.observer.onNext(a),b=!0}catch(c){throw c}finally{b||this.dispose()}},c.error=function(a){try{this.observer.onError(a)}catch(b){throw b}finally{this.dispose()}},c.completed=function(){try{this.observer.onCompleted()}catch(a){throw a}finally{this.dispose()}},c.setDisposable=function(a){this.m.setDisposable(a)},c.getDisposable=function(){return this.m.getDisposable()},c.disposable=function(a){return arguments.length?this.getDisposable():setDisposable(a)},c.dispose=function(){a.prototype.dispose.call(this),this.m.dispose()},b}(Sb),lc=function(a,b){this.subject=a,this.observer=b};lc.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1),this.observer=null}};var mc=E.Subject=function(a){function c(a){return b.call(this),this.isStopped?this.exception?(a.onError(this.exception),wb):(a.onCompleted(),wb):(this.observers.push(a),new lc(this,a))}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return mb(d,a),nb(d.prototype,Pb,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped)for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)},dispose:function(){this.isDisposed=!0,this.observers=null}}),d.create=function(a,b){return new nc(a,b)},d}(Xb),nc=(E.AsyncSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),new lc(this,a);var c=this.exception,d=this.hasValue,e=this.value;return c?a.onError(c):d?(a.onNext(e),a.onCompleted()):a.onCompleted(),wb}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return mb(d,a),nb(d.prototype,Pb,{hasObservers:function(){return b.call(this),this.observers.length>0},onCompleted:function(){var a,c,d;if(b.call(this),!this.isStopped){this.isStopped=!0;var e=this.observers.slice(0),f=this.value,g=this.hasValue;if(g)for(c=0,d=e.length;d>c;c++)a=e[c],a.onNext(f),a.onCompleted();else for(c=0,d=e.length;d>c;c++)e[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){b.call(this),this.isStopped||(this.value=a,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),d}(Xb),E.AnonymousSubject=function(a){function b(b,c){this.observer=b,this.observable=c,a.call(this,this.observable.subscribe.bind(this.observable))}return mb(b,a),nb(b.prototype,Pb,{onCompleted:function(){this.observer.onCompleted()},onError:function(a){this.observer.onError(a)},onNext:function(a){this.observer.onNext(a)}}),b}(Xb));"function"==typeof define&&"object"==typeof define.amd&&define.amd?(z.Rx=E,define(function(){return E})):A&&B?C?(B.exports=E).Rx=E:A.Rx=E:z.Rx=E}).call(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.testing.js b/ajax/libs/rxjs/2.3.9/rx.testing.js new file mode 100644 index 000000000..f195998fe --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.testing.js @@ -0,0 +1,480 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx.virtualtime', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx.all')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // Defaults + var Observer = Rx.Observer, + Observable = Rx.Observable, + Notification = Rx.Notification, + VirtualTimeScheduler = Rx.VirtualTimeScheduler, + Disposable = Rx.Disposable, + disposableEmpty = Disposable.empty, + disposableCreate = Disposable.create, + CompositeDisposable = Rx.CompositeDisposable, + SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, + slice = Array.prototype.slice, + inherits = Rx.internals.inherits, + defaultComparer = Rx.internals.isEqual; + + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + + function OnNextPredicate(predicate) { + this.predicate = predicate; + }; + + OnNextPredicate.prototype.equals = function (other) { + if (other === this) { return true; } + if (other == null) { return false; } + if (other.kind !== 'N') { return false; } + return this.predicate(other.value); + }; + + function OnErrorPredicate(predicate) { + this.predicate = predicate; + }; + + OnErrorPredicate.prototype.equals = function (other) { + if (other === this) { return true; } + if (other == null) { return false; } + if (other.kind !== 'E') { return false; } + return this.predicate(other.exception); + }; + + var ReactiveTest = Rx.ReactiveTest = { + /** Default virtual time used for creation of observable sequences in unit tests. */ + created: 100, + /** Default virtual time used to subscribe to observable sequences in unit tests. */ + subscribed: 200, + /** Default virtual time used to dispose subscriptions in unit tests. */ + disposed: 1000, + + /** + * Factory method for an OnNext notification record at a given time with a given value or a predicate function. + * + * 1 - ReactiveTest.onNext(200, 42); + * 2 - ReactiveTest.onNext(200, function (x) { return x.length == 2; }); + * + * @param ticks Recorded virtual time the OnNext notification occurs. + * @param value Recorded value stored in the OnNext notification or a predicate. + * @return Recorded OnNext notification. + */ + onNext: function (ticks, value) { + if (typeof value === 'function') { + return new Recorded(ticks, new OnNextPredicate(value)); + } + return new Recorded(ticks, Notification.createOnNext(value)); + }, + /** + * Factory method for an OnError notification record at a given time with a given error. + * + * 1 - ReactiveTest.onNext(200, new Error('error')); + * 2 - ReactiveTest.onNext(200, function (e) { return e.message === 'error'; }); + * + * @param ticks Recorded virtual time the OnError notification occurs. + * @param exception Recorded exception stored in the OnError notification. + * @return Recorded OnError notification. + */ + onError: function (ticks, exception) { + if (typeof exception === 'function') { + return new Recorded(ticks, new OnErrorPredicate(exception)); + } + return new Recorded(ticks, Notification.createOnError(exception)); + }, + /** + * Factory method for an OnCompleted notification record at a given time. + * + * @param ticks Recorded virtual time the OnCompleted notification occurs. + * @return Recorded OnCompleted notification. + */ + onCompleted: function (ticks) { + return new Recorded(ticks, Notification.createOnCompleted()); + }, + /** + * Factory method for a subscription record based on a given subscription and disposal time. + * + * @param start Virtual time indicating when the subscription was created. + * @param end Virtual time indicating when the subscription was disposed. + * @return Subscription object. + */ + subscribe: function (start, end) { + return new Subscription(start, end); + } + }; + + /** + * Creates a new object recording the production of the specified value at the given virtual time. + * + * @constructor + * @param {Number} time Virtual time the value was produced on. + * @param {Mixed} value Value that was produced. + * @param {Function} comparer An optional comparer. + */ + var Recorded = Rx.Recorded = function (time, value, comparer) { + this.time = time; + this.value = value; + this.comparer = comparer || defaultComparer; + }; + + /** + * Checks whether the given recorded object is equal to the current instance. + * + * @param {Recorded} other Recorded object to check for equality. + * @returns {Boolean} true if both objects are equal; false otherwise. + */ + Recorded.prototype.equals = function (other) { + return this.time === other.time && this.comparer(this.value, other.value); + }; + + /** + * Returns a string representation of the current Recorded value. + * + * @returns {String} String representation of the current Recorded value. + */ + Recorded.prototype.toString = function () { + return this.value.toString() + '@' + this.time; + }; + + /** + * Creates a new subscription object with the given virtual subscription and unsubscription time. + * + * @constructor + * @param {Number} subscribe Virtual time at which the subscription occurred. + * @param {Number} unsubscribe Virtual time at which the unsubscription occurred. + */ + var Subscription = Rx.Subscription = function (start, end) { + this.subscribe = start; + this.unsubscribe = end || Number.MAX_VALUE; + }; + + /** + * Checks whether the given subscription is equal to the current instance. + * @param other Subscription object to check for equality. + * @returns {Boolean} true if both objects are equal; false otherwise. + */ + Subscription.prototype.equals = function (other) { + return this.subscribe === other.subscribe && this.unsubscribe === other.unsubscribe; + }; + + /** + * Returns a string representation of the current Subscription value. + * @returns {String} String representation of the current Subscription value. + */ + Subscription.prototype.toString = function () { + return '(' + this.subscribe + ', ' + (this.unsubscribe === Number.MAX_VALUE ? 'Infinite' : this.unsubscribe) + ')'; + }; + + /** @private */ + var MockDisposable = Rx.MockDisposable = function (scheduler) { + this.scheduler = scheduler; + this.disposes = []; + this.disposes.push(this.scheduler.clock); + }; + + /* + * @memberOf MockDisposable# + * @prviate + */ + MockDisposable.prototype.dispose = function () { + this.disposes.push(this.scheduler.clock); + }; + + /** @private */ + var MockObserver = (function (_super) { + inherits(MockObserver, _super); + + /* + * @constructor + * @prviate + */ + function MockObserver(scheduler) { + _super.call(this); + this.scheduler = scheduler; + this.messages = []; + } + + var MockObserverPrototype = MockObserver.prototype; + + /* + * @memberOf MockObserverPrototype# + * @prviate + */ + MockObserverPrototype.onNext = function (value) { + this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnNext(value))); + }; + + /* + * @memberOf MockObserverPrototype# + * @prviate + */ + MockObserverPrototype.onError = function (exception) { + this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnError(exception))); + }; + + /* + * @memberOf MockObserverPrototype# + * @prviate + */ + MockObserverPrototype.onCompleted = function () { + this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnCompleted())); + }; + + return MockObserver; + })(Observer); + + /** @private */ + var HotObservable = (function (_super) { + + function subscribe(observer) { + var observable = this; + this.observers.push(observer); + this.subscriptions.push(new Subscription(this.scheduler.clock)); + var index = this.subscriptions.length - 1; + return disposableCreate(function () { + var idx = observable.observers.indexOf(observer); + observable.observers.splice(idx, 1); + observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock); + }); + } + + inherits(HotObservable, _super); + + /** + * @private + * @constructor + */ + function HotObservable(scheduler, messages) { + _super.call(this, subscribe); + var message, notification, observable = this; + this.scheduler = scheduler; + this.messages = messages; + this.subscriptions = []; + this.observers = []; + for (var i = 0, len = this.messages.length; i < len; i++) { + message = this.messages[i]; + notification = message.value; + (function (innerNotification) { + scheduler.scheduleAbsoluteWithState(null, message.time, function () { + var obs = observable.observers.slice(0); + + for (var j = 0, jLen = obs.length; j < jLen; j++) { + innerNotification.accept(obs[j]); + } + return disposableEmpty; + }); + })(notification); + } + } + + return HotObservable; + })(Observable); + + /** @private */ + var ColdObservable = (function (_super) { + + function subscribe(observer) { + var message, notification, observable = this; + this.subscriptions.push(new Subscription(this.scheduler.clock)); + var index = this.subscriptions.length - 1; + var d = new CompositeDisposable(); + for (var i = 0, len = this.messages.length; i < len; i++) { + message = this.messages[i]; + notification = message.value; + (function (innerNotification) { + d.add(observable.scheduler.scheduleRelativeWithState(null, message.time, function () { + innerNotification.accept(observer); + return disposableEmpty; + })); + })(notification); + } + return disposableCreate(function () { + observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock); + d.dispose(); + }); + } + + inherits(ColdObservable, _super); + + /** + * @private + * @constructor + */ + function ColdObservable(scheduler, messages) { + _super.call(this, subscribe); + this.scheduler = scheduler; + this.messages = messages; + this.subscriptions = []; + } + + return ColdObservable; + })(Observable); + + /** Virtual time scheduler used for testing applications and libraries built using Reactive Extensions. */ + Rx.TestScheduler = (function (_super) { + inherits(TestScheduler, _super); + + function baseComparer(x, y) { + return x > y ? 1 : (x < y ? -1 : 0); + } + + /** @constructor */ + function TestScheduler() { + _super.call(this, 0, baseComparer); + } + + /** + * Schedules an action to be executed at the specified virtual time. + * + * @param state State passed to the action to be executed. + * @param dueTime Absolute virtual time at which to execute the action. + * @param action Action to be executed. + * @return Disposable object used to cancel the scheduled action (best effort). + */ + TestScheduler.prototype.scheduleAbsoluteWithState = function (state, dueTime, action) { + if (dueTime <= this.clock) { + dueTime = this.clock + 1; + } + return _super.prototype.scheduleAbsoluteWithState.call(this, state, dueTime, action); + }; + /** + * Adds a relative virtual time to an absolute virtual time value. + * + * @param absolute Absolute virtual time value. + * @param relative Relative virtual time value to add. + * @return Resulting absolute virtual time sum value. + */ + TestScheduler.prototype.add = function (absolute, relative) { + return absolute + relative; + }; + /** + * Converts the absolute virtual time value to a DateTimeOffset value. + * + * @param absolute Absolute virtual time value to convert. + * @return Corresponding DateTimeOffset value. + */ + TestScheduler.prototype.toDateTimeOffset = function (absolute) { + return new Date(absolute).getTime(); + }; + /** + * Converts the TimeSpan value to a relative virtual time value. + * + * @param timeSpan TimeSpan value to convert. + * @return Corresponding relative virtual time value. + */ + TestScheduler.prototype.toRelative = function (timeSpan) { + return timeSpan; + }; + /** + * Starts the test scheduler and uses the specified virtual times to invoke the factory function, subscribe to the resulting sequence, and dispose the subscription. + * + * @param create Factory method to create an observable sequence. + * @param created Virtual time at which to invoke the factory to create an observable sequence. + * @param subscribed Virtual time at which to subscribe to the created observable sequence. + * @param disposed Virtual time at which to dispose the subscription. + * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active. + */ + TestScheduler.prototype.startWithTiming = function (create, created, subscribed, disposed) { + var observer = this.createObserver(), source, subscription; + this.scheduleAbsoluteWithState(null, created, function () { + source = create(); + return disposableEmpty; + }); + this.scheduleAbsoluteWithState(null, subscribed, function () { + subscription = source.subscribe(observer); + return disposableEmpty; + }); + this.scheduleAbsoluteWithState(null, disposed, function () { + subscription.dispose(); + return disposableEmpty; + }); + this.start(); + return observer; + }; + /** + * Starts the test scheduler and uses the specified virtual time to dispose the subscription to the sequence obtained through the factory function. + * Default virtual times are used for factory invocation and sequence subscription. + * + * @param create Factory method to create an observable sequence. + * @param disposed Virtual time at which to dispose the subscription. + * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active. + */ + TestScheduler.prototype.startWithDispose = function (create, disposed) { + return this.startWithTiming(create, ReactiveTest.created, ReactiveTest.subscribed, disposed); + }; + /** + * Starts the test scheduler and uses default virtual times to invoke the factory function, to subscribe to the resulting sequence, and to dispose the subscription. + * + * @param create Factory method to create an observable sequence. + * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active. + */ + TestScheduler.prototype.startWithCreate = function (create) { + return this.startWithTiming(create, ReactiveTest.created, ReactiveTest.subscribed, ReactiveTest.disposed); + }; + /** + * Creates a hot observable using the specified timestamped notification messages either as an array or arguments. + * + * @param messages Notifications to surface through the created sequence at their specified absolute virtual times. + * @return Hot observable sequence that can be used to assert the timing of subscriptions and notifications. + */ + TestScheduler.prototype.createHotObservable = function () { + var messages = argsOrArray(arguments, 0); + return new HotObservable(this, messages); + }; + /** + * Creates a cold observable using the specified timestamped notification messages either as an array or arguments. + * + * @param messages Notifications to surface through the created sequence at their specified virtual time offsets from the sequence subscription time. + * @return Cold observable sequence that can be used to assert the timing of subscriptions and notifications. + */ + TestScheduler.prototype.createColdObservable = function () { + var messages = argsOrArray(arguments, 0); + return new ColdObservable(this, messages); + }; + /** + * Creates an observer that records received notification messages and timestamps those. + * + * @return Observer that can be used to assert the timing of received notifications. + */ + TestScheduler.prototype.createObserver = function () { + return new MockObserver(this); + }; + + return TestScheduler; + })(VirtualTimeScheduler); + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.testing.min.js b/ajax/libs/rxjs/2.3.9/rx.testing.min.js new file mode 100644 index 000000000..86fdb03cd --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.testing.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx.virtualtime","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx.all")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c){function d(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:o.call(a)}function e(a){this.predicate=a}function f(a){this.predicate=a}var g=c.Observer,h=c.Observable,i=c.Notification,j=c.VirtualTimeScheduler,k=c.Disposable,l=k.empty,m=k.create,n=c.CompositeDisposable,o=(c.SingleAssignmentDisposable,Array.prototype.slice),p=c.internals.inherits,q=c.internals.isEqual;e.prototype.equals=function(a){return a===this?!0:null==a?!1:"N"!==a.kind?!1:this.predicate(a.value)},f.prototype.equals=function(a){return a===this?!0:null==a?!1:"E"!==a.kind?!1:this.predicate(a.exception)};var r=c.ReactiveTest={created:100,subscribed:200,disposed:1e3,onNext:function(a,b){return"function"==typeof b?new s(a,new e(b)):new s(a,i.createOnNext(b))},onError:function(a,b){return"function"==typeof b?new s(a,new f(b)):new s(a,i.createOnError(b))},onCompleted:function(a){return new s(a,i.createOnCompleted())},subscribe:function(a,b){return new t(a,b)}},s=c.Recorded=function(a,b,c){this.time=a,this.value=b,this.comparer=c||q};s.prototype.equals=function(a){return this.time===a.time&&this.comparer(this.value,a.value)},s.prototype.toString=function(){return this.value.toString()+"@"+this.time};var t=c.Subscription=function(a,b){this.subscribe=a,this.unsubscribe=b||Number.MAX_VALUE};t.prototype.equals=function(a){return this.subscribe===a.subscribe&&this.unsubscribe===a.unsubscribe},t.prototype.toString=function(){return"("+this.subscribe+", "+(this.unsubscribe===Number.MAX_VALUE?"Infinite":this.unsubscribe)+")"};var u=c.MockDisposable=function(a){this.scheduler=a,this.disposes=[],this.disposes.push(this.scheduler.clock)};u.prototype.dispose=function(){this.disposes.push(this.scheduler.clock)};var v=function(a){function b(b){a.call(this),this.scheduler=b,this.messages=[]}p(b,a);var c=b.prototype;return c.onNext=function(a){this.messages.push(new s(this.scheduler.clock,i.createOnNext(a)))},c.onError=function(a){this.messages.push(new s(this.scheduler.clock,i.createOnError(a)))},c.onCompleted=function(){this.messages.push(new s(this.scheduler.clock,i.createOnCompleted()))},b}(g),w=function(a){function b(a){var b=this;this.observers.push(a),this.subscriptions.push(new t(this.scheduler.clock));var c=this.subscriptions.length-1;return m(function(){var d=b.observers.indexOf(a);b.observers.splice(d,1),b.subscriptions[c]=new t(b.subscriptions[c].subscribe,b.scheduler.clock)})}function c(c,d){a.call(this,b);var e,f,g=this;this.scheduler=c,this.messages=d,this.subscriptions=[],this.observers=[];for(var h=0,i=this.messages.length;i>h;h++)e=this.messages[h],f=e.value,function(a){c.scheduleAbsoluteWithState(null,e.time,function(){for(var b=g.observers.slice(0),c=0,d=b.length;d>c;c++)a.accept(b[c]);return l})}(f)}return p(c,a),c}(h),x=function(a){function b(a){var b,c,d=this;this.subscriptions.push(new t(this.scheduler.clock));for(var e=this.subscriptions.length-1,f=new n,g=0,h=this.messages.length;h>g;g++)b=this.messages[g],c=b.value,function(c){f.add(d.scheduler.scheduleRelativeWithState(null,b.time,function(){return c.accept(a),l}))}(c);return m(function(){d.subscriptions[e]=new t(d.subscriptions[e].subscribe,d.scheduler.clock),f.dispose()})}function c(c,d){a.call(this,b),this.scheduler=c,this.messages=d,this.subscriptions=[]}return p(c,a),c}(h);return c.TestScheduler=function(a){function b(a,b){return a>b?1:b>a?-1:0}function c(){a.call(this,0,b)}return p(c,a),c.prototype.scheduleAbsoluteWithState=function(b,c,d){return c<=this.clock&&(c=this.clock+1),a.prototype.scheduleAbsoluteWithState.call(this,b,c,d)},c.prototype.add=function(a,b){return a+b},c.prototype.toDateTimeOffset=function(a){return new Date(a).getTime()},c.prototype.toRelative=function(a){return a},c.prototype.startWithTiming=function(a,b,c,d){var e,f,g=this.createObserver();return this.scheduleAbsoluteWithState(null,b,function(){return e=a(),l}),this.scheduleAbsoluteWithState(null,c,function(){return f=e.subscribe(g),l}),this.scheduleAbsoluteWithState(null,d,function(){return f.dispose(),l}),this.start(),g},c.prototype.startWithDispose=function(a,b){return this.startWithTiming(a,r.created,r.subscribed,b)},c.prototype.startWithCreate=function(a){return this.startWithTiming(a,r.created,r.subscribed,r.disposed)},c.prototype.createHotObservable=function(){var a=d(arguments,0);return new w(this,a)},c.prototype.createColdObservable=function(){var a=d(arguments,0);return new x(this,a)},c.prototype.createObserver=function(){return new v(this)},c}(j),c}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.time.js b/ajax/libs/rxjs/2.3.9/rx.time.js new file mode 100644 index 000000000..ad1c76d58 --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.time.js @@ -0,0 +1,1149 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // Refernces + var Observable = Rx.Observable, + observableProto = Observable.prototype, + AnonymousObservable = Rx.AnonymousObservable, + observableDefer = Observable.defer, + observableEmpty = Observable.empty, + observableNever = Observable.never, + observableThrow = Observable.throwException, + observableFromArray = Observable.fromArray, + timeoutScheduler = Rx.Scheduler.timeout, + SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, + SerialDisposable = Rx.SerialDisposable, + CompositeDisposable = Rx.CompositeDisposable, + RefCountDisposable = Rx.RefCountDisposable, + Subject = Rx.Subject, + addRef = Rx.internals.addRef, + normalizeTime = Rx.Scheduler.normalize, + helpers = Rx.helpers, + isPromise = helpers.isPromise, + isScheduler = helpers.isScheduler, + observableFromPromise = Observable.fromPromise, + notDefined = helpers.notDefined; + + function observableTimerDate(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithAbsolute(dueTime, function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerDateAndPeriod(dueTime, period, scheduler) { + return new AnonymousObservable(function (observer) { + var count = 0, d = dueTime, p = normalizeTime(period); + return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { + if (p > 0) { + var now = scheduler.now(); + d = d + p; + d <= now && (d = now + p); + } + observer.onNext(count++); + self(d); + }); + }); + } + + function observableTimerTimeSpan(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { + return dueTime === period ? + new AnonymousObservable(function (observer) { + return scheduler.schedulePeriodicWithState(0, period, function (count) { + observer.onNext(count); + return count + 1; + }); + }) : + observableDefer(function () { + return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); + }); + } + + /** + * Returns an observable sequence that produces a value after each period. + * + * @example + * 1 - res = Rx.Observable.interval(1000); + * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); + * + * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. + * @returns {Observable} An observable sequence that produces a value after each period. + */ + var observableinterval = Observable.interval = function (period, scheduler) { + return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); + }; + + /** + * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. + * + * @example + * 1 - res = Rx.Observable.timer(new Date()); + * 2 - res = Rx.Observable.timer(new Date(), 1000); + * 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout); + * + * 5 - res = Rx.Observable.timer(5000); + * 6 - res = Rx.Observable.timer(5000, 1000); + * 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); + * 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. + * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. + */ + var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { + var period; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { + period = periodOrScheduler; + } else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') { + scheduler = periodOrScheduler; + } + if (dueTime instanceof Date && period === undefined) { + return observableTimerDate(dueTime.getTime(), scheduler); + } + if (dueTime instanceof Date && period !== undefined) { + period = periodOrScheduler; + return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); + } + return period === undefined ? + observableTimerTimeSpan(dueTime, scheduler) : + observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); + }; + + function observableDelayTimeSpan(source, dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + var active = false, + cancelable = new SerialDisposable(), + exception = null, + q = [], + running = false, + subscription; + subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { + var d, shouldRun; + if (notification.value.kind === 'E') { + q = []; + q.push(notification); + exception = notification.value.exception; + shouldRun = !running; + } else { + q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); + shouldRun = !active; + active = true; + } + if (shouldRun) { + if (exception !== null) { + observer.onError(exception); + } else { + d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { + var e, recurseDueTime, result, shouldRecurse; + if (exception !== null) { + return; + } + running = true; + do { + result = null; + if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { + result = q.shift().value; + } + if (result !== null) { + result.accept(observer); + } + } while (result !== null); + shouldRecurse = false; + recurseDueTime = 0; + if (q.length > 0) { + shouldRecurse = true; + recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); + } else { + active = false; + } + e = exception; + running = false; + if (e !== null) { + observer.onError(e); + } else if (shouldRecurse) { + self(recurseDueTime); + } + })); + } + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + } + + function observableDelayDate(source, dueTime, scheduler) { + return observableDefer(function () { + return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); + }); + } + + /** + * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. + * + * @example + * 1 - res = Rx.Observable.delay(new Date()); + * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); + * + * 3 - res = Rx.Observable.delay(5000); + * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); + * @memberOf Observable# + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. + * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delay = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return dueTime instanceof Date ? + observableDelayDate(this, dueTime.getTime(), scheduler) : + observableDelayTimeSpan(this, dueTime, scheduler); + }; + + /** + * Ignores values from an observable sequence which are followed by another value before dueTime. + * + * @example + * 1 - res = source.throttle(5000); // 5 seconds + * 2 - res = source.throttle(5000, scheduler); + * + * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttle = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. + * + * @example + * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second + * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds + * + * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + var source = this, timeShift; + + timeShiftOrScheduler == null && (timeShift = timeSpan); + isScheduler(scheduler) || (scheduler = timeoutScheduler); + if (typeof timeShiftOrScheduler === 'number') { + timeShift = timeShiftOrScheduler; + } else if (typeof timeShiftOrScheduler === 'object') { + timeShift = timeSpan; + scheduler = timeShiftOrScheduler; + } + return new AnonymousObservable(function (observer) { + var groupDisposable, + nextShift = timeShift, + nextSpan = timeSpan, + q = [], + refCountDisposable, + timerD = new SerialDisposable(), + totalTime = 0; + groupDisposable = new CompositeDisposable(timerD), + refCountDisposable = new RefCountDisposable(groupDisposable); + + + q.push(new Subject()); + observer.onNext(addRef(q[0], refCountDisposable)); + createTimer(); + groupDisposable.add(source.subscribe(function (x) { + var i, len; + for (i = 0, len = q.length; i < len; i++) { + q[i].onNext(x); + } + }, function (e) { + var i, len; + for (i = 0, len = q.length; i < len; i++) { + q[i].onError(e); + } + observer.onError(e); + }, function () { + var i, len; + for (i = 0, len = q.length; i < len; i++) { + q[i].onCompleted(); + } + observer.onCompleted(); + })); + + return refCountDisposable; + + function createTimer () { + var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; + timerD.setDisposable(m); + + if (nextSpan === nextShift) { + isSpan = true; + isShift = true; + } else if (nextSpan < nextShift) { + isSpan = true; + } else { + isShift = true; + } + + var newTotalTime = isSpan ? nextSpan : nextShift, + ts = newTotalTime - totalTime; + totalTime = newTotalTime; + isSpan && (nextSpan += timeShift); + isShift && (nextShift += timeShift); + + m.setDisposable(scheduler.scheduleWithRelative(ts, function () { + var s; + if (isShift) { + s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + } + if (isSpan) { + s = q.shift(); + s.onCompleted(); + } + createTimer(); + })); + } + }); + }; + + /** + * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. + * @example + * 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items + * 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items + * + * @memberOf Observable# + * @param {Number} timeSpan Maximum time length of a window. + * @param {Number} count Maximum element count of a window. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var createTimer, + groupDisposable, + n = 0, + refCountDisposable, + s = new Subject() + timerD = new SerialDisposable(), + windowId = 0; + groupDisposable = new CompositeDisposable(timerD); + refCountDisposable = new RefCountDisposable(groupDisposable); + + observer.onNext(addRef(s, refCountDisposable)); + createTimer(0); + groupDisposable.add(source.subscribe(function (x) { + var newId = 0, newWindow = false; + s.onNext(x); + n++; + if (n === count) { + newWindow = true; + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + } + newWindow && createTimer(newId); + }, function (e) { + s.onError(e); + observer.onError(e); + }, function () { + s.onCompleted(); + observer.onCompleted(); + })); + + return refCountDisposable; + + function createTimer(id) { + var m = new SingleAssignmentDisposable(); + timerD.setDisposable(m); + m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { + var newId; + if (id !== windowId) { return; } + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + createTimer(newId); + })); + } + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. + * + * @example + * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second + * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds + * + * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. + * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); + }; + + /** + * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. + * + * @example + * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array + * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array + * + * @param {Number} timeSpan Maximum time length of a buffer. + * @param {Number} count Maximum element count of a buffer. + * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { + return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { + return x.toArray(); + }); + }; + + /** + * Records the time interval between consecutive values in an observable sequence. + * + * @example + * 1 - res = source.timeInterval(); + * 2 - res = source.timeInterval(Rx.Scheduler.timeout); + * + * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with time interval information on values. + */ + observableProto.timeInterval = function (scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return observableDefer(function () { + var last = scheduler.now(); + return source.map(function (x) { + var now = scheduler.now(), span = now - last; + last = now; + return { value: x, interval: span }; + }); + }); + }; + + /** + * Records the timestamp for each value in an observable sequence. + * + * @example + * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } + * 2 - res = source.timestamp(Rx.Scheduler.timeout); + * + * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with timestamp information on values. + */ + observableProto.timestamp = function (scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return this.map(function (x) { + return { value: x, timestamp: scheduler.now() }; + }); + }; + + function sampleObservable(source, sampler) { + + return new AnonymousObservable(function (observer) { + var atEnd, value, hasValue; + + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + observer.onNext(value); + } + atEnd && observer.onCompleted(); + } + + return new CompositeDisposable( + source.subscribe(function (newValue) { + hasValue = true; + value = newValue; + }, observer.onError.bind(observer), function () { + atEnd = true; + }), + sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) + ); + }); + } + + /** + * Samples the observable sequence at each interval. + * + * @example + * 1 - res = source.sample(sampleObservable); // Sampler tick sequence + * 2 - res = source.sample(5000); // 5 seconds + * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. + * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Sampled observable sequence. + */ + observableProto.sample = function (intervalOrSampler, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return typeof intervalOrSampler === 'number' ? + sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : + sampleObservable(this, intervalOrSampler); + }; + + /** + * Returns the source observable sequence or the other observable sequence if dueTime elapses. + * + * @example + * 1 - res = source.timeout(new Date()); // As a date + * 2 - res = source.timeout(5000); // 5 seconds + * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable + * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable + * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable + * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. + * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. + * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeout = function (dueTime, other, scheduler) { + other || (other = observableThrow(new Error('Timeout'))); + isScheduler(scheduler) || (scheduler = timeoutScheduler); + + var source = this, schedulerMethod = dueTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + + return new AnonymousObservable(function (observer) { + var id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + + subscription.setDisposable(original); + + var createTimer = function () { + var myId = id; + timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { + if (id === myId) { + isPromise(other) && (other = observableFromPromise(other)); + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + createTimer(); + + original.setDisposable(source.subscribe(function (x) { + if (!switched) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + if (!switched) { + id++; + observer.onError(e); + } + }, function () { + if (!switched) { + id++; + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithAbsoluteTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return new Date(); } + * }); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { + hasResult && observer.onNext(result); + + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithRelativeTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return 500; } + * ); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithRelative(0, function (self) { + hasResult && observer.onNext(result); + + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Time shifts the observable sequence by delaying the subscription. + * + * @example + * 1 - res = source.delaySubscription(5000); // 5s + * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Number} dueTime Absolute or relative time to perform the subscription at. + * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delaySubscription = function (dueTime, scheduler) { + return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty); + }; + + /** + * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only + * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector + * + * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. + * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { + var source = this, subDelay, selector; + if (typeof subscriptionDelay === 'function') { + selector = subscriptionDelay; + } else { + subDelay = subscriptionDelay; + selector = delayDurationSelector; + } + return new AnonymousObservable(function (observer) { + var delays = new CompositeDisposable(), atEnd = false, done = function () { + if (atEnd && delays.length === 0) { + observer.onCompleted(); + } + }, subscription = new SerialDisposable(), start = function () { + subscription.setDisposable(source.subscribe(function (x) { + var delay; + try { + delay = selector(x); + } catch (error) { + observer.onError(error); + return; + } + var d = new SingleAssignmentDisposable(); + delays.add(d); + d.setDisposable(delay.subscribe(function () { + observer.onNext(x); + delays.remove(d); + done(); + }, observer.onError.bind(observer), function () { + observer.onNext(x); + delays.remove(d); + done(); + })); + }, observer.onError.bind(observer), function () { + atEnd = true; + subscription.dispose(); + done(); + })); + }; + + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(function () { + start(); + }, observer.onError.bind(observer), function () { start(); })); + } + + return new CompositeDisposable(subscription, delays); + }); + }; + + /** + * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. + * + * @example + * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); + * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); + * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); + * + * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). + * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. + * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { + if (arguments.length === 1) { + timeoutdurationSelector = firstTimeout; + var firstTimeout = observableNever(); + } + other || (other = observableThrow(new Error('Timeout'))); + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); + + subscription.setDisposable(original); + + var id = 0, switched = false, setTimer = function (timeout) { + var myId = id, timerWins = function () { + return id === myId; + }; + var d = new SingleAssignmentDisposable(); + timer.setDisposable(d); + d.setDisposable(timeout.subscribe(function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + d.dispose(); + }, function (e) { + if (timerWins()) { + observer.onError(e); + } + }, function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + setTimer(firstTimeout); + var observerWins = function () { + var res = !switched; + if (res) { + id++; + } + return res; + }; + + original.setDisposable(source.subscribe(function (x) { + if (observerWins()) { + observer.onNext(x); + var timeout; + try { + timeout = timeoutdurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + setTimer(timeout); + } + }, function (e) { + if (observerWins()) { + observer.onError(e); + } + }, function () { + if (observerWins()) { + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); + * + * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttleWithSelector = function (throttleDurationSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { + var throttle; + try { + throttle = throttleDurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + hasValue = true; + value = x; + id++; + var currentid = id, d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(throttle.subscribe(function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + }, observer.onError.bind(observer), function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + })); + }, function (e) { + cancelable.dispose(); + observer.onError(e); + hasValue = false; + id++; + }, function () { + cancelable.dispose(); + if (hasValue) { + observer.onNext(value); + } + observer.onCompleted(); + hasValue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * 1 - res = source.skipLastWithTime(5000); + * 2 - res = source.skipLastWithTime(5000, scheduler); + * + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for skipping elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. + */ + observableProto.skipLastWithTime = function (duration, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. + * + * @example + * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var q = []; + + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { + observer.onNext(next.value); + } + } + + observer.onCompleted(); + }); + }); + }; + + /** + * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastBufferWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var q = []; + + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(), res = []; + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { + res.push(next.value); + } + } + + observer.onNext(res); + observer.onCompleted(); + }); + }); + }; + + /** + * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + observableProto.takeWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), source.subscribe(observer)); + }); + }; + + /** + * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.skipWithTime(5000, [optional scheduler]); + * + * @description + * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. + * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded + * may not execute immediately, despite the zero due time. + * + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. + * @param {Number} duration Duration for skipping elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + observableProto.skipWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false; + return new CompositeDisposable( + scheduler.scheduleWithRelative(duration, function () { open = true; }), + source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); + }); + }; + + /** + * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. + * + * @examples + * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); + * 2 - res = source.skipUntilWithTime(5000, [optional scheduler]); + * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. + * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped until the specified start time. + */ + observableProto.skipUntilWithTime = function (startTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = startTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (observer) { + var open = false; + + return new CompositeDisposable( + scheduler[schedulerMethod](startTime, function () { open = true; }), + source.subscribe( + function (x) { open && observer.onNext(x); }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer))); + }); + }; + + /** + * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); + * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); + * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. + * @param {Scheduler} scheduler Scheduler to run the timer on. + * @returns {Observable} An observable sequence with the elements taken until the specified end time. + */ + observableProto.takeUntilWithTime = function (endTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = endTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { + observer.onCompleted(); + }), source.subscribe(observer)); + }); + }; + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.time.min.js b/ajax/libs/rxjs/2.3.9/rx.time.min.js new file mode 100644 index 000000000..25ea63dd1 --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.time.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c,d){function e(a,b){return new n(function(c){return b.scheduleWithAbsolute(a,function(){c.onNext(0),c.onCompleted()})})}function f(a,b,c){return new n(function(d){var e=0,f=a,g=z(b);return c.scheduleRecursiveWithAbsolute(f,function(a){if(g>0){var b=c.now();f+=g,b>=f&&(f=b+g)}d.onNext(e++),a(f)})})}function g(a,b){return new n(function(c){return b.scheduleWithRelative(z(a),function(){c.onNext(0),c.onCompleted()})})}function h(a,b,c){return a===b?new n(function(a){return c.schedulePeriodicWithState(0,b,function(b){return a.onNext(b),b+1})}):o(function(){return f(c.now()+a,b,c)})}function i(a,b,c){return new n(function(d){var e,f=!1,g=new u,h=null,i=[],j=!1;return e=a.materialize().timestamp(c).subscribe(function(a){var e,k;"E"===a.value.kind?(i=[],i.push(a),h=a.value.exception,k=!j):(i.push({value:a.value,timestamp:a.timestamp+b}),k=!f,f=!0),k&&(null!==h?d.onError(h):(e=new t,g.setDisposable(e),e.setDisposable(c.scheduleRecursiveWithRelative(b,function(a){var b,e,g,k;if(null===h){j=!0;do g=null,i.length>0&&i[0].timestamp-c.now()<=0&&(g=i.shift().value),null!==g&&g.accept(d);while(null!==g);k=!1,e=0,i.length>0?(k=!0,e=Math.max(0,i[0].timestamp-c.now())):f=!1,b=h,j=!1,null!==b?d.onError(b):k&&a(e)}}))))}),new v(e,g)})}function j(a,b,c){return o(function(){return i(a,b-c.now(),c)})}function k(a,b){return new n(function(c){function d(){g&&(g=!1,c.onNext(f)),e&&c.onCompleted()}var e,f,g;return new v(a.subscribe(function(a){g=!0,f=a},c.onError.bind(c),function(){e=!0}),b.subscribe(d,c.onError.bind(c),d))})}var l=c.Observable,m=l.prototype,n=c.AnonymousObservable,o=l.defer,p=l.empty,q=l.never,r=l.throwException,s=(l.fromArray,c.Scheduler.timeout),t=c.SingleAssignmentDisposable,u=c.SerialDisposable,v=c.CompositeDisposable,w=c.RefCountDisposable,x=c.Subject,y=c.internals.addRef,z=c.Scheduler.normalize,A=c.helpers,B=A.isPromise,C=A.isScheduler,D=l.fromPromise,E=(A.notDefined,l.interval=function(a,b){return h(a,a,C(b)?b:s)}),F=l.timer=function(a,b,c){var i;return C(c)||(c=s),b!==d&&"number"==typeof b?i=b:b!==d&&"object"==typeof b&&(c=b),a instanceof Date&&i===d?e(a.getTime(),c):a instanceof Date&&i!==d?(i=b,f(a.getTime(),i,c)):i===d?g(a,c):h(a,i,c)};return m.delay=function(a,b){return C(b)||(b=s),a instanceof Date?j(this,a.getTime(),b):i(this,a,b)},m.throttle=function(a,b){return C(b)||(b=s),this.throttleWithSelector(function(){return F(a,b)})},m.windowWithTime=function(a,b,c){var d,e=this;return null==b&&(d=a),C(c)||(c=s),"number"==typeof b?d=b:"object"==typeof b&&(d=a,c=b),new n(function(b){function f(){var a=new t,e=!1,g=!1;l.setDisposable(a),j===i?(e=!0,g=!0):i>j?e=!0:g=!0;var n=e?j:i,o=n-m;m=n,e&&(j+=d),g&&(i+=d),a.setDisposable(c.scheduleWithRelative(o,function(){var a;g&&(a=new x,k.push(a),b.onNext(y(a,h))),e&&(a=k.shift(),a.onCompleted()),f()}))}var g,h,i=d,j=a,k=[],l=new u,m=0;return g=new v(l),h=new w(g),k.push(new x),b.onNext(y(k[0],h)),f(),g.add(e.subscribe(function(a){var b,c;for(b=0,c=k.length;c>b;b++)k[b].onNext(a)},function(a){var c,d;for(c=0,d=k.length;d>c;c++)k[c].onError(a);b.onError(a)},function(){var a,c;for(a=0,c=k.length;c>a;a++)k[a].onCompleted();b.onCompleted()})),h})},m.windowWithTimeOrCount=function(a,b,c){var d=this;return C(c)||(c=s),new n(function(e){function f(b){var d=new t;timerD.setDisposable(d),d.setDisposable(c.scheduleWithRelative(a,function(){var a;b===windowId&&(i=0,a=++windowId,j.onCompleted(),j=new x,e.onNext(y(j,h)),f(a))}))}var f,g,h,i=0,j=new x;return timerD=new u,windowId=0,g=new v(timerD),h=new w(g),e.onNext(y(j,h)),f(0),g.add(d.subscribe(function(a){var c=0,d=!1;j.onNext(a),i++,i===b&&(d=!0,i=0,c=++windowId,j.onCompleted(),j=new x,e.onNext(y(j,h))),d&&f(c)},function(a){j.onError(a),e.onError(a)},function(){j.onCompleted(),e.onCompleted()})),h})},m.bufferWithTime=function(){return this.windowWithTime.apply(this,arguments).selectMany(function(a){return a.toArray()})},m.bufferWithTimeOrCount=function(a,b,c){return this.windowWithTimeOrCount(a,b,c).selectMany(function(a){return a.toArray()})},m.timeInterval=function(a){var b=this;return C(a)||(a=s),o(function(){var c=a.now();return b.map(function(b){var d=a.now(),e=d-c;return c=d,{value:b,interval:e}})})},m.timestamp=function(a){return C(a)||(a=s),this.map(function(b){return{value:b,timestamp:a.now()}})},m.sample=function(a,b){return C(b)||(b=s),"number"==typeof a?k(this,E(a,b)):k(this,a)},m.timeout=function(a,b,c){b||(b=r(new Error("Timeout"))),C(c)||(c=s);var d=this,e=a instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new n(function(f){var g=0,h=new t,i=new u,j=!1,k=new u;i.setDisposable(h);var l=function(){var d=g;k.setDisposable(c[e](a,function(){g===d&&(B(b)&&(b=D(b)),i.setDisposable(b.subscribe(f)))}))};return l(),h.setDisposable(d.subscribe(function(a){j||(g++,f.onNext(a),l())},function(a){j||(g++,f.onError(a))},function(){j||(g++,f.onCompleted())})),new v(i,k)})},l.generateWithAbsoluteTime=function(a,b,c,d,e,f){return C(f)||(f=s),new n(function(g){var h,i,j=!0,k=!1,l=a;return f.scheduleRecursiveWithAbsolute(f.now(),function(a){k&&g.onNext(h);try{j?j=!1:l=c(l),k=b(l),k&&(h=d(l),i=e(l))}catch(f){return void g.onError(f)}k?a(i):g.onCompleted()})})},l.generateWithRelativeTime=function(a,b,c,d,e,f){return C(f)||(f=s),new n(function(g){var h,i,j=!0,k=!1,l=a;return f.scheduleRecursiveWithRelative(0,function(a){k&&g.onNext(h);try{j?j=!1:l=c(l),k=b(l),k&&(h=d(l),i=e(l))}catch(f){return void g.onError(f)}k?a(i):g.onCompleted()})})},m.delaySubscription=function(a,b){return this.delayWithSelector(F(a,C(b)?b:s),p)},m.delayWithSelector=function(a,b){var c,d,e=this;return"function"==typeof a?d=a:(c=a,d=b),new n(function(a){var b=new v,f=!1,g=function(){f&&0===b.length&&a.onCompleted()},h=new u,i=function(){h.setDisposable(e.subscribe(function(c){var e;try{e=d(c)}catch(f){return void a.onError(f)}var h=new t;b.add(h),h.setDisposable(e.subscribe(function(){a.onNext(c),b.remove(h),g()},a.onError.bind(a),function(){a.onNext(c),b.remove(h),g()}))},a.onError.bind(a),function(){f=!0,h.dispose(),g()}))};return c?h.setDisposable(c.subscribe(function(){i()},a.onError.bind(a),function(){i()})):i(),new v(h,b)})},m.timeoutWithSelector=function(a,b,c){if(1===arguments.length){b=a;var a=q()}c||(c=r(new Error("Timeout")));var d=this;return new n(function(e){var f=new u,g=new u,h=new t;f.setDisposable(h);var i=0,j=!1,k=function(a){var b=i,d=function(){return i===b},h=new t;g.setDisposable(h),h.setDisposable(a.subscribe(function(){d()&&f.setDisposable(c.subscribe(e)),h.dispose()},function(a){d()&&e.onError(a)},function(){d()&&f.setDisposable(c.subscribe(e))}))};k(a);var l=function(){var a=!j;return a&&i++,a};return h.setDisposable(d.subscribe(function(a){if(l()){e.onNext(a);var c;try{c=b(a)}catch(d){return void e.onError(d)}k(c)}},function(a){l()&&e.onError(a)},function(){l()&&e.onCompleted()})),new v(f,g)})},m.throttleWithSelector=function(a){var b=this;return new n(function(c){var d,e=!1,f=new u,g=0,h=b.subscribe(function(b){var h;try{h=a(b)}catch(i){return void c.onError(i)}e=!0,d=b,g++;var j=g,k=new t;f.setDisposable(k),k.setDisposable(h.subscribe(function(){e&&g===j&&c.onNext(d),e=!1,k.dispose()},c.onError.bind(c),function(){e&&g===j&&c.onNext(d),e=!1,k.dispose()}))},function(a){f.dispose(),c.onError(a),e=!1,g++},function(){f.dispose(),e&&c.onNext(d),c.onCompleted(),e=!1,g++});return new v(h,f)})},m.skipLastWithTime=function(a,b){C(b)||(b=s);var c=this;return new n(function(d){var e=[];return c.subscribe(function(c){var f=b.now();for(e.push({interval:f,value:c});e.length>0&&f-e[0].interval>=a;)d.onNext(e.shift().value)},d.onError.bind(d),function(){for(var c=b.now();e.length>0&&c-e[0].interval>=a;)d.onNext(e.shift().value);d.onCompleted()})})},m.takeLastWithTime=function(a,b){var c=this;return C(b)||(b=s),new n(function(d){var e=[];return c.subscribe(function(c){var d=b.now();for(e.push({interval:d,value:c});e.length>0&&d-e[0].interval>=a;)e.shift()},d.onError.bind(d),function(){for(var c=b.now();e.length>0;){var f=e.shift();c-f.interval<=a&&d.onNext(f.value)}d.onCompleted()})})},m.takeLastBufferWithTime=function(a,b){var c=this;return C(b)||(b=s),new n(function(d){var e=[];return c.subscribe(function(c){var d=b.now();for(e.push({interval:d,value:c});e.length>0&&d-e[0].interval>=a;)e.shift()},d.onError.bind(d),function(){for(var c=b.now(),f=[];e.length>0;){var g=e.shift();c-g.interval<=a&&f.push(g.value)}d.onNext(f),d.onCompleted()})})},m.takeWithTime=function(a,b){var c=this;return C(b)||(b=s),new n(function(d){return new v(b.scheduleWithRelative(a,d.onCompleted.bind(d)),c.subscribe(d))})},m.skipWithTime=function(a,b){var c=this;return C(b)||(b=s),new n(function(d){var e=!1;return new v(b.scheduleWithRelative(a,function(){e=!0}),c.subscribe(function(a){e&&d.onNext(a)},d.onError.bind(d),d.onCompleted.bind(d)))})},m.skipUntilWithTime=function(a,b){C(b)||(b=s);var c=this,d=a instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new n(function(e){var f=!1;return new v(b[d](a,function(){f=!0}),c.subscribe(function(a){f&&e.onNext(a)},e.onError.bind(e),e.onCompleted.bind(e)))})},m.takeUntilWithTime=function(a,b){C(b)||(b=s);var c=this,d=a instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new n(function(e){return new v(b[d](a,function(){e.onCompleted()}),c.subscribe(e))})},c}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.virtualtime.js b/ajax/libs/rxjs/2.3.9/rx.virtualtime.js new file mode 100644 index 000000000..a7f46576f --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.virtualtime.js @@ -0,0 +1,320 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // Aliases + var Scheduler = Rx.Scheduler, + PriorityQueue = Rx.internals.PriorityQueue, + ScheduledItem = Rx.internals.ScheduledItem, + SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive, + disposableEmpty = Rx.Disposable.empty, + inherits = Rx.internals.inherits, + defaultSubComparer = Rx.helpers.defaultSubComparer; + + /** Provides a set of extension methods for virtual time scheduling. */ + Rx.VirtualTimeScheduler = (function (__super__) { + + function notImplemented() { + throw new Error('Not implemented'); + } + + function localNow() { + return this.toDateTimeOffset(this.clock); + } + + function scheduleNow(state, action) { + return this.scheduleAbsoluteWithState(state, this.clock, action); + } + + function scheduleRelative(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + inherits(VirtualTimeScheduler, __super__); + + /** + * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. + * + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function VirtualTimeScheduler(initialClock, comparer) { + this.clock = initialClock; + this.comparer = comparer; + this.isEnabled = false; + this.queue = new PriorityQueue(1024); + __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + VirtualTimeSchedulerPrototype.add = notImplemented; + + /** + * Converts an absolute time to a number + * @param {Any} The absolute time. + * @returns {Number} The absolute time in ms + */ + VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + VirtualTimeSchedulerPrototype.toRelative = notImplemented; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { + var s = new SchedulePeriodicRecursive(this, state, period, action); + return s.start(); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { + var runAt = this.add(this.clock, dueTime); + return this.scheduleAbsoluteWithState(state, runAt, action); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { + return this.scheduleRelativeWithState(action, dueTime, invokeAction); + }; + + /** + * Starts the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.start = function () { + if (!this.isEnabled) { + this.isEnabled = true; + do { + var next = this.getNext(); + if (next !== null) { + this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); + next.invoke(); + } else { + this.isEnabled = false; + } + } while (this.isEnabled); + } + }; + + /** + * Stops the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.stop = function () { + this.isEnabled = false; + }; + + /** + * Advances the scheduler's clock to the specified time, running all work till that point. + * @param {Number} time Absolute time to advance the scheduler's clock to. + */ + VirtualTimeSchedulerPrototype.advanceTo = function (time) { + var dueToClock = this.comparer(this.clock, time); + if (this.comparer(this.clock, time) > 0) { + throw new Error(argumentOutOfRange); + } + if (dueToClock === 0) { + return; + } + if (!this.isEnabled) { + this.isEnabled = true; + do { + var next = this.getNext(); + if (next !== null && this.comparer(next.dueTime, time) <= 0) { + this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); + next.invoke(); + } else { + this.isEnabled = false; + } + } while (this.isEnabled); + this.clock = time; + } + }; + + /** + * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.advanceBy = function (time) { + var dt = this.add(this.clock, time), + dueToClock = this.comparer(this.clock, dt); + if (dueToClock > 0) { throw new Error(argumentOutOfRange); } + if (dueToClock === 0) { return; } + + this.advanceTo(dt); + }; + + /** + * Advances the scheduler's clock by the specified relative time. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.sleep = function (time) { + var dt = this.add(this.clock, time); + if (this.comparer(this.clock, dt) >= 0) { throw new Error(argumentOutOfRange); } + + this.clock = dt; + }; + + /** + * Gets the next scheduled item to be executed. + * @returns {ScheduledItem} The next scheduled item. + */ + VirtualTimeSchedulerPrototype.getNext = function () { + while (this.queue.length > 0) { + var next = this.queue.peek(); + if (next.isCancelled()) { + this.queue.dequeue(); + } else { + return next; + } + } + return null; + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Scheduler} scheduler Scheduler to execute the action on. + * @param {Number} dueTime Absolute time at which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { + return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Absolute time at which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { + var self = this; + + function run(scheduler, state1) { + self.queue.remove(si); + return action(scheduler, state1); + } + + var si = new ScheduledItem(this, state, run, dueTime, this.comparer); + this.queue.enqueue(si); + + return si.disposable; + }; + + return VirtualTimeScheduler; + }(Scheduler)); + + /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ + Rx.HistoricalScheduler = (function (__super__) { + inherits(HistoricalScheduler, __super__); + + /** + * Creates a new historical scheduler with the specified initial clock value. + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function HistoricalScheduler(initialClock, comparer) { + var clock = initialClock == null ? 0 : initialClock; + var cmp = comparer || defaultSubComparer; + __super__.call(this, clock, cmp); + } + + var HistoricalSchedulerProto = HistoricalScheduler.prototype; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + HistoricalSchedulerProto.add = function (absolute, relative) { + return absolute + relative; + }; + + HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { + return new Date(absolute).getTime(); + }; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * @memberOf HistoricalScheduler + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + HistoricalSchedulerProto.toRelative = function (timeSpan) { + return timeSpan; + }; + + return HistoricalScheduler; + }(Rx.VirtualTimeScheduler)); + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.3.9/rx.virtualtime.min.js b/ajax/libs/rxjs/2.3.9/rx.virtualtime.min.js new file mode 100644 index 000000000..8f2003388 --- /dev/null +++ b/ajax/libs/rxjs/2.3.9/rx.virtualtime.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c){var d=c.Scheduler,e=c.internals.PriorityQueue,f=c.internals.ScheduledItem,g=c.internals.SchedulePeriodicRecursive,h=c.Disposable.empty,i=c.internals.inherits,j=c.helpers.defaultSubComparer;return c.VirtualTimeScheduler=function(a){function b(){throw new Error("Not implemented")}function c(){return this.toDateTimeOffset(this.clock)}function d(a,b){return this.scheduleAbsoluteWithState(a,this.clock,b)}function j(a,b,c){return this.scheduleRelativeWithState(a,this.toRelative(b),c)}function k(a,b,c){return this.scheduleRelativeWithState(a,this.toRelative(b-this.now()),c)}function l(a,b){return b(),h}function m(b,f){this.clock=b,this.comparer=f,this.isEnabled=!1,this.queue=new e(1024),a.call(this,c,d,j,k)}i(m,a);var n=m.prototype;return n.add=b,n.toDateTimeOffset=b,n.toRelative=b,n.schedulePeriodicWithState=function(a,b,c){var d=new g(this,a,b,c);return d.start()},n.scheduleRelativeWithState=function(a,b,c){var d=this.add(this.clock,b);return this.scheduleAbsoluteWithState(a,d,c)},n.scheduleRelative=function(a,b){return this.scheduleRelativeWithState(b,a,l)},n.start=function(){if(!this.isEnabled){this.isEnabled=!0;do{var a=this.getNext();null!==a?(this.comparer(a.dueTime,this.clock)>0&&(this.clock=a.dueTime),a.invoke()):this.isEnabled=!1}while(this.isEnabled)}},n.stop=function(){this.isEnabled=!1},n.advanceTo=function(a){var b=this.comparer(this.clock,a);if(this.comparer(this.clock,a)>0)throw new Error(argumentOutOfRange);if(0!==b&&!this.isEnabled){this.isEnabled=!0;do{var c=this.getNext();null!==c&&this.comparer(c.dueTime,a)<=0?(this.comparer(c.dueTime,this.clock)>0&&(this.clock=c.dueTime),c.invoke()):this.isEnabled=!1}while(this.isEnabled);this.clock=a}},n.advanceBy=function(a){var b=this.add(this.clock,a),c=this.comparer(this.clock,b);if(c>0)throw new Error(argumentOutOfRange);0!==c&&this.advanceTo(b)},n.sleep=function(a){var b=this.add(this.clock,a);if(this.comparer(this.clock,b)>=0)throw new Error(argumentOutOfRange);this.clock=b},n.getNext=function(){for(;this.queue.length>0;){var a=this.queue.peek();if(!a.isCancelled())return a;this.queue.dequeue()}return null},n.scheduleAbsolute=function(a,b){return this.scheduleAbsoluteWithState(b,a,l)},n.scheduleAbsoluteWithState=function(a,b,c){function d(a,b){return e.queue.remove(g),c(a,b)}var e=this,g=new f(this,a,d,b,this.comparer);return this.queue.enqueue(g),g.disposable},m}(d),c.HistoricalScheduler=function(a){function b(b,c){var d=null==b?0:b,e=c||j;a.call(this,d,e)}i(b,a);var c=b.prototype;return c.add=function(a,b){return a+b},c.toDateTimeOffset=function(a){return new Date(a).getTime()},c.toRelative=function(a){return a},b}(c.VirtualTimeScheduler),c}); \ No newline at end of file diff --git a/ajax/libs/rxjs/package.json b/ajax/libs/rxjs/package.json index d324b36bd..fc638e2d4 100644 --- a/ajax/libs/rxjs/package.json +++ b/ajax/libs/rxjs/package.json @@ -12,7 +12,7 @@ "filename": "rx.min.js", "title": "Reactive Extensions for JavaScript (RxJS)", "description": "Library for composing asynchronous and event-based operations in JavaScript", - "version": "2.3.8", + "version": "2.3.9", "homepage": "https://github.com/Reactive-Extensions/RxJS", "author": { "name": "Cloud Programmability Team",