diff --git a/ajax/libs/rxjs/2.1.18/rx.aggregates.js b/ajax/libs/rxjs/2.1.18/rx.aggregates.js new file mode 100644 index 000000000..1113a68b0 --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.aggregates.js @@ -0,0 +1,716 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +(function (root, factory) { + var freeExports = typeof exports == 'object' && exports, + freeModule = typeof module == 'object' && module && module.exports == freeExports && module, + freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal) { + window = 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); + } +}(this, function (global, exp, Rx, undefined) { + + // References + var Observable = Rx.Observable, + observableProto = Observable.prototype, + CompositeDisposable = Rx.CompositeDisposable, + AnonymousObservable = Rx.Internals.AnonymousObservable, + isEqual = Rx.Internals.isEqual; + + // Defaults + var argumentOutOfRange = 'Argument out of range'; + var sequenceContainsNoElements = "Sequence contains no elements."; + function defaultComparer(x, y) { return isEqual(x, y); } + function identity(x) { return x; } + function subComparer(x, y) { + if (x > y) { + return 1; + } + if (x < y) { + return -1 + } + return 0; + } + + 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; }); + * @memberOf Observable# + * @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); + * @memberOf Observable# + * @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.reduce = function () { + var seed, hasSeed, accumulator = arguments[0]; + 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. + * + * 1 - source.any(); + * 2 - source.any(function (x) { return x > 3; }); + * @memberOf Observable# + * @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.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(); + }); + }); + }; + observableProto.some = observableProto.any; + + /** + * Determines whether an observable sequence is empty. + * + * @memberOf Observable# + * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. + */ + observableProto.isEmpty = function () { + return this.any().select(function (b) { return !b; }); + }; + + /** + * 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.all = function (predicate, thisArg) { + return this.where(function (v) { + return !predicate(v); + }, thisArg).any().select(function (b) { + return !b; + }); + }; + observableProto.every = observableProto.all; + + /** + * Determines whether an observable sequence contains a specified element with an optional equality comparer. + * + * 1 - res = source.contains(42); + * 2 - res = source.contains({ value: 42 }, function (x, y) { return x.value === y.value; }); + * @memberOf Observable# + * @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. + * + * 1 - res = source.count(); + * 2 - res = source.count(function (x) { return x > 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 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. + * + * 1 - res = source.sum(); + * 2 - res = source.sum(function (x) { return x.value; }); + * @memberOf Observable# + * @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. + * + * 1 - source.minBy(function (x) { return x.value; }); + * 2 - source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); + * @memberOf Observable# + * @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 = subComparer); + 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. + * + * 1 - source.min(); + * 2 - source.min(function (x, y) { return x.value - y.value; }); + * @memberOf Observable# + * @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 + * 1 - source.maxBy(function (x) { return x.value; }); + * 2 - source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); + * @memberOf Observable# + * @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 = subComparer); + return extremaBy(this, keySelector, comparer); + }; + + /** + * Returns the maximum value in an observable sequence according to the specified comparer. + * + * @example + * 1 - source.max(); + * 2 - source.max(function (x, y) { return x.value - y.value; }); + * @memberOf Observable# + * @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 + * 1 - res = source.average(); + * 2 - res = source.average(function (x) { return x.value; }); + * @memberOf Observable# + * @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) { + 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 + * 1 - res = source.sequenceEqual([1,2,3]); + * 2 - 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; }); + * @memberOf Observable# + * @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(); + } + } + }); + 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 + * source.elementAt(5); + * @memberOf Observable# + * @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 + * source.elementAtOrDefault(5); + * source.elementAtOrDefault(5, 0); + * @memberOf Observable# + * @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 + * 1 - res = source.single(); + * 2 - res = source.single(function (x) { return x === 42; }); + * @memberOf Observable# + * @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) { + if (predicate) { + return this.where(predicate, thisArg).single(); + } + return 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 + * 1 - res = source.singleOrDefault(); + * 2 - res = source.singleOrDefault(function (x) { return x === 42; }); + * 3 - res = source.singleOrDefault(function (x) { return x === 42; }, 0); + * 4 - 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) { + if (predicate) { + return this.where(predicate, thisArg).singleOrDefault(null, defaultValue); + } + return 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 + * 1 - res = source.first(); + * 2 - res = source.first(function (x) { return x > 3; }); + * @memberOf Observable# + * @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) { + if (predicate) { + return this.where(predicate, thisArg).first(); + } + return 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 + * 1 - res = source.firstOrDefault(); + * 2 - res = source.firstOrDefault(function (x) { return x > 3; }); + * 3 - res = source.firstOrDefault(function (x) { return x > 3; }, 0); + * 4 - res = source.firstOrDefault(null, 0); + * @memberOf Observable# + * @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) { + if (predicate) { + return this.where(predicate).firstOrDefault(null, defaultValue); + } + return 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 + * 1 - res = source.last(); + * 2 - res = source.last(function (x) { return x > 3; }); + * @memberOf Observable# + * @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) { + if (predicate) { + return this.where(predicate, thisArg).last(); + } + return 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 + * 1 - res = source.lastOrDefault(); + * 2 - res = source.lastOrDefault(function (x) { return x > 3; }); + * 3 - res = source.lastOrDefault(function (x) { return x > 3; }, 0); + * 4 - res = source.lastOrDefault(null, 0); + * @memberOf Observable# + * @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) { + if (predicate) { + return this.where(predicate, thisArg).lastOrDefault(null, defaultValue); + } + return 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. + * + * @memberOf Observable# + * @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. + * + * @memberOf Observable# + * @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); + }; + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.1.18/rx.aggregates.min.js b/ajax/libs/rxjs/2.1.18/rx.aggregates.min.js new file mode 100644 index 000000000..0251e3ab5 --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.aggregates.min.js @@ -0,0 +1 @@ +(function(t,e){var n="object"==typeof exports&&exports,r=("object"==typeof module&&module&&module.exports==n&&module,"object"==typeof global&&global);r.global===r&&(window=r),"function"==typeof define&&define.amd?define(["rx","exports"],function(n,r){return t.Rx=e(t,r,n),t.Rx}):"object"==typeof module&&module&&module.exports===n?module.exports=e(t,module.exports,require("./rx")):t.Rx=e(t,{},t.Rx)})(this,function(t,e,n,r){function i(t,e){return w(t,e)}function o(t){return t}function s(t,e){return t>e?1:e>t?-1:0}function u(t,e,n){return new y(function(i){var o=!1,s=null,u=[];return t.subscribe(function(t){var c,a;try{a=e(t)}catch(h){return i.onError(h),r}if(c=0,o)try{c=n(a,s)}catch(l){return i.onError(l),r}else o=!0,s=a;c>0&&(s=a,u=[]),c>=0&&u.push(t)},i.onError.bind(i),function(){i.onNext(u),i.onCompleted()})})}function c(t){if(0===t.length)throw Error(E);return t[0]}function a(t,e,n){return new y(function(i){var o=0,s=e.length;return t.subscribe(function(t){var u=!1;try{s>o&&(u=n(t,e[o++]))}catch(c){return i.onError(c),r}u||(i.onNext(!1),i.onCompleted())},i.onError.bind(i),function(){i.onNext(o===s),i.onCompleted()})})}function h(t,e,n,r){if(0>e)throw Error(g);return new y(function(i){var o=e;return t.subscribe(function(t){0===o&&(i.onNext(t),i.onCompleted()),o--},i.onError.bind(i),function(){n?(i.onNext(r),i.onCompleted()):i.onError(Error(g))})})}function l(t,e,n){return new y(function(r){var i=n,o=!1;return t.subscribe(function(t){o?r.onError(Error("Sequence contains more than one element")):(i=t,o=!0)},r.onError.bind(r),function(){o||e?(r.onNext(i),r.onCompleted()):r.onError(Error(E))})})}function f(t,e,n){return new y(function(r){return t.subscribe(function(t){r.onNext(t),r.onCompleted()},r.onError.bind(r),function(){e?(r.onNext(n),r.onCompleted()):r.onError(Error(E))})})}function p(t,e,n){return new y(function(r){var i=n,o=!1;return t.subscribe(function(t){i=t,o=!0},r.onError.bind(r),function(){o||e?(r.onNext(i),r.onCompleted()):r.onError(Error(E))})})}function d(t,e,n,i){return new y(function(o){var s=0;return t.subscribe(function(u){var c;try{c=e.call(n,u,s,t)}catch(a){return o.onError(a),r}c?(o.onNext(i?s:u),o.onCompleted()):s++},o.onError.bind(o),function(){o.onNext(i?-1:r),o.onCompleted()})})}var b=n.Observable,v=b.prototype,m=n.CompositeDisposable,y=n.Internals.AnonymousObservable,w=n.Internals.isEqual,g="Argument out of range",E="Sequence contains no elements.";return v.aggregate=function(){var t,e,n;return 2===arguments.length?(t=arguments[0],e=!0,n=arguments[1]):n=arguments[0],e?this.scan(t,n).startWith(t).finalValue():this.scan(n).finalValue()},v.reduce=function(){var t,e,n=arguments[0];return 2===arguments.length&&(e=!0,t=arguments[1]),e?this.scan(t,n).startWith(t).finalValue():this.scan(n).finalValue()},v.any=function(t,e){var n=this;return t?n.where(t,e).any():new y(function(t){return n.subscribe(function(){t.onNext(!0),t.onCompleted()},t.onError.bind(t),function(){t.onNext(!1),t.onCompleted()})})},v.some=v.any,v.isEmpty=function(){return this.any().select(function(t){return!t})},v.all=function(t,e){return this.where(function(e){return!t(e)},e).any().select(function(t){return!t})},v.every=v.all,v.contains=function(t,e){return e||(e=i),this.where(function(n){return e(n,t)}).any()},v.count=function(t,e){return t?this.where(t,e).count():this.aggregate(0,function(t){return t+1})},v.sum=function(t,e){return t?this.select(t,e).sum():this.aggregate(0,function(t,e){return t+e})},v.minBy=function(t,e){return e||(e=s),u(this,t,function(t,n){return-1*e(t,n)})},v.min=function(t){return this.minBy(o,t).select(function(t){return c(t)})},v.maxBy=function(t,e){return e||(e=s),u(this,t,e)},v.max=function(t){return this.maxBy(o,t).select(function(t){return c(t)})},v.average=function(t,e){return t?this.select(t,e).average():this.scan({sum:0,count:0},function(t,e){return{sum:t.sum+e,count:t.count+1}}).finalValue().select(function(t){return t.sum/t.count})},v.sequenceEqual=function(t,e){var n=this;return e||(e=i),Array.isArray(t)?a(n,t,e):new y(function(i){var o=!1,s=!1,u=[],c=[],a=n.subscribe(function(t){var n,o;if(c.length>0){o=c.shift();try{n=e(o,t)}catch(a){return i.onError(a),r}n||(i.onNext(!1),i.onCompleted())}else s?(i.onNext(!1),i.onCompleted()):u.push(t)},i.onError.bind(i),function(){o=!0,0===u.length&&(c.length>0?(i.onNext(!1),i.onCompleted()):s&&(i.onNext(!0),i.onCompleted()))}),h=t.subscribe(function(t){var n,s;if(u.length>0){s=u.shift();try{n=e(s,t)}catch(a){return i.onError(a),r}n||(i.onNext(!1),i.onCompleted())}else o?(i.onNext(!1),i.onCompleted()):c.push(t)},i.onError.bind(i),function(){s=!0,0===c.length&&(u.length>0?(i.onNext(!1),i.onCompleted()):o&&(i.onNext(!0),i.onCompleted()))});return new m(a,h)})},v.elementAt=function(t){return h(this,t,!1)},v.elementAtOrDefault=function(t,e){return h(this,t,!0,e)},v.single=function(t,e){return t?this.where(t,e).single():l(this,!1)},v.singleOrDefault=function(t,e,n){return t?this.where(t,n).singleOrDefault(null,e):l(this,!0,e)},v.first=function(t,e){return t?this.where(t,e).first():f(this,!1)},v.firstOrDefault=function(t,e){return t?this.where(t).firstOrDefault(null,e):f(this,!0,e)},v.last=function(t,e){return t?this.where(t,e).last():p(this,!1)},v.lastOrDefault=function(t,e,n){return t?this.where(t,n).lastOrDefault(null,e):p(this,!0,e)},v.find=function(t,e){return d(this,t,e,!1)},v.findIndex=function(t,e){return d(this,t,e,!0)},n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.1.18/rx.binding.js b/ajax/libs/rxjs/2.1.18/rx.binding.js new file mode 100644 index 000000000..50a5e8292 --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.binding.js @@ -0,0 +1,534 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +(function (root, factory) { + var freeExports = typeof exports == 'object' && exports, + freeModule = typeof module == 'object' && module && module.exports == freeExports && module, + freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal) { + window = 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); + } +}(this, function (global, exp, Rx, undefined) { + + var Observable = Rx.Observable, + observableProto = Observable.prototype, + AnonymousObservable = Rx.Internals.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 {Mixed} 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. + * + * @memberOf BehaviorSubject# + */ + 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. + * + * @memberOf BehaviorSubject# + * @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. + * + * @memberOf BehaviorSubject# + * @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. + * + * @memberOf BehaviorSubject# + */ + 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) { + /** + * @private + * @constructor + */ + var RemovableDisposable = function (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + /* + * @private + * @memberOf RemovableDisposable# + */ + 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 and scheduler. + * + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [window] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, window, scheduler) { + this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; + this.window = window == null ? Number.MAX_VALUE : window; + 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. + * + * @memberOf ReplaySubject# + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /* + * @private + * @memberOf ReplaySubject# + */ + _trim: function (now) { + while (this.q.length > this.bufferSize) { + this.q.shift(); + } + while (this.q.length > 0 && (now - this.q[0].interval) > this.window) { + this.q.shift(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * + * @memberOf ReplaySubject# + * @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. + * + * @memberOf ReplaySubject# + * @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. + * + * @memberOf ReplaySubject# + */ + 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. + * + * @memberOf ReplaySubject# + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + /** @private */ + var ConnectableObservable = (function (_super) { + inherits(ConnectableObservable, _super); + + /** + * @constructor + * @private + */ + function ConnectableObservable(source, subject) { + var state = { + subject: subject, + source: source.asObservable(), + hasSubscription: false, + subscription: null + }; + + this.connect = function () { + if (!state.hasSubscription) { + state.hasSubscription = true; + state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () { + state.hasSubscription = false; + })); + } + return state.subscription; + }; + + function subscribe(observer) { + return state.subject.subscribe(observer); + } + + _super.call(this, subscribe); + } + + /** + * @private + * @memberOf ConnectableObservable + */ + ConnectableObservable.prototype.connect = function () { return this.connect(); }; + + /** + * @private + * @memberOf ConnectableObservable + */ + ConnectableObservable.prototype.refCount = function () { + var connectableSubscription = null, count = 0, source = this; + return new AnonymousObservable(function (observer) { + var shouldConnect, subscription; + count++; + shouldConnect = count === 1; + subscription = source.subscribe(observer); + if (shouldConnect) { + connectableSubscription = source.connect(); + } + return disposableCreate(function () { + subscription.dispose(); + count--; + if (count === 0) { + connectableSubscription.dispose(); + } + }); + }); + }; + + return ConnectableObservable; + }(Observable)); + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.1.18/rx.binding.min.js b/ajax/libs/rxjs/2.1.18/rx.binding.min.js new file mode 100644 index 000000000..6ab31ed05 --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.binding.min.js @@ -0,0 +1 @@ +(function(t,e){var n="object"==typeof exports&&exports,r=("object"==typeof module&&module&&module.exports==n&&module,"object"==typeof global&&global);r.global===r&&(window=r),"function"==typeof define&&define.amd?define(["rx","exports"],function(n,r){return t.Rx=e(t,r,n),t.Rx}):"object"==typeof module&&module&&module.exports===n?module.exports=e(t,module.exports,require("./rx")):t.Rx=e(t,{},t.Rx)})(this,function(t,e,n){function r(){if(this.isDisposed)throw Error(m)}var i=n.Observable,o=i.prototype,s=n.Internals.AnonymousObservable,u=n.Subject,c=n.AsyncSubject,a=n.Observer,h=n.Internals.ScheduledObserver,l=n.Disposable.create,f=n.Disposable.empty,p=n.CompositeDisposable,d=n.Scheduler.currentThread,b=n.Internals.inherits,v=n.Internals.addProperties,m="Object has been disposed";o.multicast=function(t,e){var n=this;return"function"==typeof t?new s(function(r){var i=n.multicast(t());return new p(e(i).subscribe(r),i.connect())}):new E(n,t)},o.publish=function(t){return t?this.multicast(function(){return new u},t):this.multicast(new u)},o.publishLast=function(t){return t?this.multicast(function(){return new c},t):this.multicast(new c)},o.publishValue=function(t,e){return 2===arguments.length?this.multicast(function(){return new w(e)},t):this.multicast(new w(t))},o.replay=function(t,e,n,r){return t?this.multicast(function(){return new g(e,n,r)},t):this.multicast(new g(e,n,r))};var y=function(t,e){this.subject=t,this.observer=e};y.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}};var w=n.BehaviorSubject=function(t){function e(t){var e;return r.call(this),this.isStopped?(e=this.exception,e?t.onError(e):t.onCompleted(),f):(this.observers.push(t),t.onNext(this.value),new y(this,t))}function n(n){t.call(this,e),this.value=n,this.observers=[],this.isDisposed=!1,this.isStopped=!1,this.exception=null}return b(n,t),v(n.prototype,a,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(r.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var e=0,n=t.length;n>e;e++)t[e].onCompleted();this.observers=[]}},onError:function(t){if(r.call(this),!this.isStopped){var e=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var n=0,i=e.length;i>n;n++)e[n].onError(t);this.observers=[]}},onNext:function(t){if(r.call(this),!this.isStopped){this.value=t;for(var e=this.observers.slice(0),n=0,i=e.length;i>n;n++)e[n].onNext(t)}},dispose:function(){this.isDisposed=!0,this.observers=null,this.value=null,this.exception=null}}),n}(i),g=n.ReplaySubject=function(t){function e(t){var e=new h(this.scheduler,t),n=new i(this,e);r.call(this),this._trim(this.scheduler.now()),this.observers.push(e);for(var o=this.q.length,s=0,u=this.q.length;u>s;s++)e.onNext(this.q[s].value);return this.hasError?(o++,e.onError(this.error)):this.isStopped&&(o++,e.onCompleted()),e.ensureActive(o),n}function n(n,r,i){this.bufferSize=null==n?Number.MAX_VALUE:n,this.window=null==r?Number.MAX_VALUE:r,this.scheduler=i||d,this.q=[],this.observers=[],this.isStopped=!1,this.isDisposed=!1,this.hasError=!1,this.error=null,t.call(this,e)}var i=function(t,e){this.subject=t,this.observer=e};return i.prototype.dispose=function(){if(this.observer.dispose(),!this.subject.isDisposed){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1)}},b(n,t),v(n.prototype,a,{hasObservers:function(){return this.observers.length>0},_trim:function(t){for(;this.q.length>this.bufferSize;)this.q.shift();for(;this.q.length>0&&t-this.q[0].interval>this.window;)this.q.shift()},onNext:function(t){var e;if(r.call(this),!this.isStopped){var n=this.scheduler.now();this.q.push({interval:n,value:t}),this._trim(n);for(var i=this.observers.slice(0),o=0,s=i.length;s>o;o++)e=i[o],e.onNext(t),e.ensureActive()}},onError:function(t){var e;if(r.call(this),!this.isStopped){this.isStopped=!0,this.error=t,this.hasError=!0;var n=this.scheduler.now();this._trim(n);for(var i=this.observers.slice(0),o=0,s=i.length;s>o;o++)e=i[o],e.onError(t),e.ensureActive();this.observers=[]}},onCompleted:function(){var t;if(r.call(this),!this.isStopped){this.isStopped=!0;var e=this.scheduler.now();this._trim(e);for(var n=this.observers.slice(0),i=0,o=n.length;o>i;i++)t=n[i],t.onCompleted(),t.ensureActive();this.observers=[]}},dispose:function(){this.isDisposed=!0,this.observers=null}}),n}(i),E=function(t){function e(e,n){function r(t){return i.subject.subscribe(t)}var i={subject:n,source:e.asObservable(),hasSubscription:!1,subscription:null};this.connect=function(){return i.hasSubscription||(i.hasSubscription=!0,i.subscription=new p(i.source.subscribe(i.subject),l(function(){i.hasSubscription=!1}))),i.subscription},t.call(this,r)}return b(e,t),e.prototype.connect=function(){return this.connect()},e.prototype.refCount=function(){var t=null,e=0,n=this;return new s(function(r){var i,o;return e++,i=1===e,o=n.subscribe(r),i&&(t=n.connect()),l(function(){o.dispose(),e--,0===e&&t.dispose()})})},e}(i);return n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.1.18/rx.coincidence.js b/ajax/libs/rxjs/2.1.18/rx.coincidence.js new file mode 100644 index 000000000..9485c6dad --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.coincidence.js @@ -0,0 +1,679 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +(function (root, factory) { + var freeExports = typeof exports == 'object' && exports, + freeModule = typeof module == 'object' && module && module.exports == freeExports && module, + freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal) { + window = 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); + } +}(this, function (global, 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, + AnonymousObservable = Rx.Internals.AnonymousObservable, + observerCreate = Rx.Observer.create, + addRef = Rx.Internals.addRef; + + // defaults + function noop() { } + function defaultComparer(x, y) { return x === y; } + + // Real Dictionary + 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]; + var noSuchkey = "no such key"; + var 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 obj.getTime(); + } + + 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 }; + } + + // Dictionary implementation + + var Dictionary = function (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; + }; + + Dictionary.prototype._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; + }; + Dictionary.prototype.count = function () { + return this.size; + }; + Dictionary.prototype.add = function (key, value) { + return this._insert(key, value, true); + }; + Dictionary.prototype._insert = function (key, value, add) { + if (!this.buckets) { + this._initialize(0); + } + var index3; + var num = getHashCode(key) & 2147483647; + var 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; + }; + + Dictionary.prototype._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; + }; + + Dictionary.prototype.remove = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647; + var index1 = num % this.buckets.length; + var 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; + }; + + Dictionary.prototype.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; + }; + + Dictionary.prototype._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; + }; + + Dictionary.prototype.count = function () { + return this.size - this.freeCount; + }; + + Dictionary.prototype.tryGetValue = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { + return this.entries[entry].value; + } + return undefined; + }; + + Dictionary.prototype.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; + }; + + Dictionary.prototype.get = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { + return this.entries[entry].value; + } + throw new Error(noSuchkey); + }; + + Dictionary.prototype.set = function (key, value) { + this._insert(key, value, false); + }; + + Dictionary.prototype.containskey = function (key) { + return this._findEntry(key) >= 0; + }; + + /** + * 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(), + leftDone = false, + leftId = 0, + leftMap = new Dictionary(), + rightDone = false, + rightId = 0, + rightMap = new Dictionary(); + group.add(left.subscribe(function (value) { + var duration, + expire, + id = leftId++, + md = new SingleAssignmentDisposable(), + result, + values; + leftMap.add(id, value); + group.add(md); + expire = function () { + if (leftMap.remove(id) && leftMap.count() === 0 && leftDone) { + observer.onCompleted(); + } + return group.remove(md); + }; + try { + duration = leftDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + md.disposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); })); + values = rightMap.getValues(); + for (var i = 0; i < values.length; i++) { + try { + result = resultSelector(value, values[i]); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + } + }, observer.onError.bind(observer), function () { + leftDone = true; + if (rightDone || leftMap.count() === 0) { + observer.onCompleted(); + } + })); + group.add(right.subscribe(function (value) { + var duration, + expire, + id = rightId++, + md = new SingleAssignmentDisposable(), + result, + values; + rightMap.add(id, value); + group.add(md); + expire = function () { + if (rightMap.remove(id) && rightMap.count() === 0 && rightDone) { + observer.onCompleted(); + } + return group.remove(md); + }; + try { + duration = rightDurationSelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + md.disposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); })); + values = leftMap.getValues(); + for (var i = 0; i < values.length; i++) { + try { + result = resultSelector(values[i], value); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + } + }, observer.onError.bind(observer), function () { + rightDone = true; + if (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 nothing = function () {}; + var group = new CompositeDisposable(); + var r = new RefCountDisposable(group); + var leftMap = new Dictionary(); + var rightMap = new Dictionary(); + var leftID = 0; + var rightID = 0; + + group.add(left.subscribe( + function (value) { + var s = new Subject(); + var id = leftID++; + leftMap.add(id, s); + var i, len, leftValues, rightValues; + + var result; + try { + result = resultSelector(value, addRef(s, r)); + } catch (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + return; + } + observer.onNext(result); + + rightValues = rightMap.getValues(); + for (i = 0, len = rightValues.length; i < len; i++) { + s.onNext(rightValues[i]); + } + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + if (leftMap.remove(id)) { + s.onCompleted(); + } + + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftMap.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe( + nothing, + function (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + }, + expire) + ); + }, + function (e) { + var leftValues = leftMap.getValues(); + for (var i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + }, + observer.onCompleted.bind(observer))); + + group.add(right.subscribe( + function (value) { + var leftValues, i, len; + 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) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftMap.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + return; + } + md.setDisposable(duration.take(1).subscribe( + nothing, + function (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftMap.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + }, + expire) + ); + + leftValues = leftMap.getValues(); + for (i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onNext(value); + } + }, + function (e) { + var leftValues = leftMap.getValues(); + for (var i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(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.disposable(m1); + m1.disposable(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; + }); + } + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.1.18/rx.coincidence.min.js b/ajax/libs/rxjs/2.1.18/rx.coincidence.min.js new file mode 100644 index 000000000..979fb79a1 --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.coincidence.min.js @@ -0,0 +1 @@ +(function(t,e){var n="object"==typeof exports&&exports,r=("object"==typeof module&&module&&module.exports==n&&module,"object"==typeof global&&global);r.global===r&&(window=r),"function"==typeof define&&define.amd?define(["rx","exports"],function(n,r){return t.Rx=e(t,r,n),t.Rx}):"object"==typeof module&&module&&module.exports===n?module.exports=e(t,module.exports,require("./rx")):t.Rx=e(t,{},t.Rx)})(this,function(t,e,n,r){function i(){}function o(t,e){return t===e}function s(t){if(false&t)return 2===t;for(var e=Math.sqrt(t),n=3;e>=n;){if(0===t%n)return!1;n+=2}return!0}function u(t){var e,n,r;for(e=0;D.length>e;++e)if(n=D[e],n>=t)return n;for(r=1|t;D[D.length-1]>r;){if(s(r))return r;r+=2}return t}function c(t){var e=757602046;if(!t.length)return e;for(var n=0,r=t.length;r>n;n++){var i=t.charCodeAt(n);e=(e<<5)-e+i,e&=e}return e}function a(t){var e=668265261;return t=61^t^t>>>16,t+=t<<3,t^=t>>>4,t*=e,t^=t>>>15}function h(){return{key:null,value:null,next:0,hashCode:0}}function l(t,e){return t.groupJoin(this,e,function(){return E()},function(t,e){return e})}function f(t){var e=this;return new x(function(n){var r=new w,i=new b,o=new v(i);return n.onNext(C(r,o)),i.add(e.subscribe(function(t){r.onNext(t)},function(t){r.onError(t),n.onError(t)},function(){r.onCompleted(),n.onCompleted()})),i.add(t.subscribe(function(){r.onCompleted(),r=new w,n.onNext(C(r,o))},function(t){r.onError(t),n.onError(t)},function(){r.onCompleted(),n.onCompleted()})),o})}function p(t){var e=this;return new x(function(n){var o,s=new y,u=new b(s),c=new v(u),a=new w;return n.onNext(C(a,c)),u.add(e.subscribe(function(t){a.onNext(t)},function(t){a.onError(t),n.onError(t)},function(){a.onCompleted(),n.onCompleted()})),o=function(){var e,u;try{u=t()}catch(h){return n.onError(h),r}e=new m,s.disposable(e),e.disposable(u.take(1).subscribe(i,function(t){a.onError(t),n.onError(t)},function(){a.onCompleted(),a=new w,n.onNext(C(a,c)),o()}))},o(),c})}var d=n.Observable,b=n.CompositeDisposable,v=n.RefCountDisposable,m=n.SingleAssignmentDisposable,y=n.SerialDisposable,w=n.Subject,g=d.prototype,E=d.empty,x=n.Internals.AnonymousObservable,C=(n.Observer.create,n.Internals.addRef),D=[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],A="no such key",S="duplicate key",N=function(){var t=0;return function(e){if(null==e)throw Error(A);if("string"==typeof e)return c(e);if("number"==typeof e)return a(e);if("boolean"==typeof e)return e===!0?1:0;if(e instanceof Date)return e.getTime();if(e.getHashCode)return e.getHashCode();var n=17*t++;return e.getHashCode=function(){return n},n}}(),_=function(t,e){if(0>t)throw Error("out of range");t>0&&this._initialize(t),this.comparer=e||o,this.freeCount=0,this.size=0,this.freeList=-1};return _.prototype._initialize=function(t){var e,n=u(t);for(this.buckets=Array(n),this.entries=Array(n),e=0;n>e;e++)this.buckets[e]=-1,this.entries[e]=h();this.freeList=-1},_.prototype.count=function(){return this.size},_.prototype.add=function(t,e){return this._insert(t,e,!0)},_.prototype._insert=function(t,e,n){this.buckets||this._initialize(0);for(var i,o=2147483647&N(t),s=o%this.buckets.length,u=this.buckets[s];u>=0;u=this.entries[u].next)if(this.entries[u].hashCode===o&&this.comparer(this.entries[u].key,t)){if(n)throw Error(S);return this.entries[u].value=e,r}this.freeCount>0?(i=this.freeList,this.freeList=this.entries[i].next,--this.freeCount):(this.size===this.entries.length&&(this._resize(),s=o%this.buckets.length),i=this.size,++this.size),this.entries[i].hashCode=o,this.entries[i].next=this.buckets[s],this.entries[i].key=t,this.entries[i].value=e,this.buckets[s]=i},_.prototype._resize=function(){var t=u(2*this.size),e=Array(t);for(r=0;e.length>r;++r)e[r]=-1;var n=Array(t);for(r=0;this.size>r;++r)n[r]=this.entries[r];for(var r=this.size;t>r;++r)n[r]=h();for(var i=0;this.size>i;++i){var o=n[i].hashCode%t;n[i].next=e[o],e[o]=i}this.buckets=e,this.entries=n},_.prototype.remove=function(t){if(this.buckets)for(var e=2147483647&N(t),n=e%this.buckets.length,r=-1,i=this.buckets[n];i>=0;i=this.entries[i].next){if(this.entries[i].hashCode===e&&this.comparer(this.entries[i].key,t))return 0>r?this.buckets[n]=this.entries[i].next:this.entries[r].next=this.entries[i].next,this.entries[i].hashCode=-1,this.entries[i].next=this.freeList,this.entries[i].key=null,this.entries[i].value=null,this.freeList=i,++this.freeCount,!0;r=i}return!1},_.prototype.clear=function(){var t,e;if(!(0>=this.size)){for(t=0,e=this.buckets.length;e>t;++t)this.buckets[t]=-1;for(t=0;this.size>t;++t)this.entries[t]=h();this.freeList=-1,this.size=0}},_.prototype._findEntry=function(t){if(this.buckets)for(var e=2147483647&N(t),n=this.buckets[e%this.buckets.length];n>=0;n=this.entries[n].next)if(this.entries[n].hashCode===e&&this.comparer(this.entries[n].key,t))return n;return-1},_.prototype.count=function(){return this.size-this.freeCount},_.prototype.tryGetValue=function(t){var e=this._findEntry(t);return e>=0?this.entries[e].value:r},_.prototype.getValues=function(){var t=0,e=[];if(this.entries)for(var n=0;this.size>n;n++)this.entries[n].hashCode>=0&&(e[t++]=this.entries[n].value);return e},_.prototype.get=function(t){var e=this._findEntry(t);if(e>=0)return this.entries[e].value;throw Error(A)},_.prototype.set=function(t,e){this._insert(t,e,!1)},_.prototype.containskey=function(t){return this._findEntry(t)>=0},g.join=function(t,e,n,o){var s=this;return new x(function(u){var c=new b,a=!1,h=0,l=new _,f=!1,p=0,d=new _;return c.add(s.subscribe(function(t){var n,s,f,p,b=h++,v=new m;l.add(b,t),c.add(v),s=function(){return l.remove(b)&&0===l.count()&&a&&u.onCompleted(),c.remove(v)};try{n=e(t)}catch(y){return u.onError(y),r}v.disposable(n.take(1).subscribe(i,u.onError.bind(u),function(){s()})),p=d.getValues();for(var w=0;p.length>w;w++){try{f=o(t,p[w])}catch(g){return u.onError(g),r}u.onNext(f)}},u.onError.bind(u),function(){a=!0,(f||0===l.count())&&u.onCompleted()})),c.add(t.subscribe(function(t){var e,s,a,h,b=p++,v=new m;d.add(b,t),c.add(v),s=function(){return d.remove(b)&&0===d.count()&&f&&u.onCompleted(),c.remove(v)};try{e=n(t)}catch(y){return u.onError(y),r}v.disposable(e.take(1).subscribe(i,u.onError.bind(u),function(){s()})),h=l.getValues();for(var w=0;h.length>w;w++){try{a=o(h[w],t)}catch(y){return u.onError(y),r}u.onNext(a)}},u.onError.bind(u),function(){f=!0,(a||0===d.count())&&u.onCompleted()})),c})},g.groupJoin=function(t,e,n,i){var o=this;return new x(function(s){var u=function(){},c=new b,a=new v(c),h=new _,l=new _,f=0,p=0;return c.add(o.subscribe(function(t){var n=new w,o=f++;h.add(o,n);var p,d,b,v,y;try{y=i(t,C(n,a))}catch(g){for(b=h.getValues(),p=0,d=b.length;d>p;p++)b[p].onError(g);return s.onError(g),r}for(s.onNext(y),v=l.getValues(),p=0,d=v.length;d>p;p++)n.onNext(v[p]);var E=new m;c.add(E);var x,D=function(){h.remove(o)&&n.onCompleted(),c.remove(E)};try{x=e(t)}catch(g){for(b=h.getValues(),p=0,d=h.length;d>p;p++)b[p].onError(g);return s.onError(g),r}E.setDisposable(x.take(1).subscribe(u,function(t){for(b=h.getValues(),p=0,d=b.length;d>p;p++)b[p].onError(t);s.onError(t)},D))},function(t){for(var e=h.getValues(),n=0,r=e.length;r>n;n++)e[n].onError(t);s.onError(t)},s.onCompleted.bind(s))),c.add(t.subscribe(function(t){var e,i,o,a=p++;l.add(a,t);var f=new m;c.add(f);var d,b=function(){l.remove(a),c.remove(f)};try{d=n(t)}catch(v){for(e=h.getValues(),i=0,o=h.length;o>i;i++)e[i].onError(v);return s.onError(v),r}for(f.setDisposable(d.take(1).subscribe(u,function(t){for(e=h.getValues(),i=0,o=h.length;o>i;i++)e[i].onError(t);s.onError(t)},b)),e=h.getValues(),i=0,o=e.length;o>i;i++)e[i].onNext(t)},function(t){for(var e=h.getValues(),n=0,r=e.length;r>n;n++)e[n].onError(t);s.onError(t)})),a})},g.buffer=function(){return this.window.apply(this,arguments).selectMany(function(t){return t.toArray()})},g.window=function(t,e){return 1===arguments.length&&"function"!=typeof arguments[0]?f.call(this,t):"function"==typeof t?p.call(this,t):l.call(this,t,e)},n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.1.18/rx.experimental.js b/ajax/libs/rxjs/2.1.18/rx.experimental.js new file mode 100644 index 000000000..bc6eee05c --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.experimental.js @@ -0,0 +1,454 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +(function (root, factory) { + var freeExports = typeof exports == 'object' && exports, + freeModule = typeof module == 'object' && module && module.exports == freeExports && module, + freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal) { + window = 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); + } +}(this, function (global, exp, Rx, undefined) { + + // Aliases + var Observable = Rx.Observable, + observableProto = Observable.prototype, + observableCreateWithDisposable = Observable.createWithDisposable, + observableConcat = Observable.concat, + observableDefer = Observable.defer, + observableEmpty = Observable.empty, + disposableEmpty = Rx.Disposable.empty, + BinaryObserver = Rx.Internals.BinaryObserver, + CompositeDisposable = Rx.CompositeDisposable, + SerialDisposable = Rx.SerialDisposable, + SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, + enumeratorCreate = Rx.Internals.Enumerator.create, + Enumerable = Rx.Internals.Enumerable, + enumerableForEach = 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; + + // Utilities + function nothing () { } + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + + function enumerableWhile(condition, source) { + return new Enumerable(function () { + var current; + return enumeratorCreate(function () { + if (condition()) { + current = source; + return true; + } + return false; + }, function () { return current; }); + }); + } + + /** + * 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. + * + * @memberOf Observable# + * @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 = 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, ...); + * @static + * @memberOf Observable + * @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 observableCreateWithDisposable(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]; + 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. + * + * @memberOf Observable# + * @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 observableCreateWithDisposable(function (observer) { + var leftStopped = false, rightStopped = false, + hasLeft = false, hasRight = false, + lastLeft, lastRight, + leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); + + 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) { + scheduler || (scheduler = immediateScheduler); + var source = this; + return Observable.defer(function () { + var chain; + + return source + .select( + function (x) { + var curr = new ChainObservable(x); + if (chain) { + chain.onNext(x); + } + chain = curr; + + return curr; + }) + .doAction( + nothing, + function (e) { + if (chain) { + chain.onError(e); + } + }, + function () { + if (chain) { + chain.onCompleted(); + } + }) + .observeOn(scheduler) + .select(function (x, i, o) { return selector(x, i, o); }); + }); + }; + + 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.1.18/rx.experimental.min.js b/ajax/libs/rxjs/2.1.18/rx.experimental.min.js new file mode 100644 index 000000000..722f860da --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.experimental.min.js @@ -0,0 +1 @@ +(function(t,e){var n="object"==typeof exports&&exports,r=("object"==typeof module&&module&&module.exports==n&&module,"object"==typeof global&&global);r.global===r&&(window=r),"function"==typeof define&&define.amd?define(["rx","exports"],function(n,r){return t.Rx=e(t,r,n),t.Rx}):"object"==typeof module&&module&&module.exports===n?module.exports=e(t,module.exports,require("./rx")):t.Rx=e(t,{},t.Rx)})(this,function(t,e,n,r){function i(){}function o(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:x.call(t)}function s(t,e){return new y(function(){var n;return m(function(){return t()?(n=e,!0):!1},function(){return n})})}var u=n.Observable,c=u.prototype,a=u.createWithDisposable,h=u.concat,l=u.defer,f=u.empty,p=n.Disposable.empty,d=(n.Internals.BinaryObserver,n.CompositeDisposable),b=n.SerialDisposable,v=n.SingleAssignmentDisposable,m=n.Internals.Enumerator.create,y=n.Internals.Enumerable,w=y.forEach,g=n.Scheduler.immediate,E=n.Scheduler.currentThread,x=Array.prototype.slice,C=n.AsyncSubject,D=n.Observer,A=n.Internals.inherits,S=n.Internals.addProperties;c.letBind=function(t){return t(this)},u["if"]=u.ifThen=function(t,e,n){return l(function(){if(n||(n=f()),n.now){var r=n;n=f(r)}return t()?e:n})},u["for"]=u.forIn=function(t,e){return w(t,e).concat()};var N=u["while"]=u.whileDo=function(t,e){return s(t,e).concat()};c.doWhile=function(t){return h([this,N(t,this)])},u["case"]=u.switchCase=function(t,e,n){return l(function(){if(n||(n=f()),n.now){var i=n;n=f(i)}var o=e[t()];return o!==r?o:n})},c.expand=function(t,e){e||(e=g);var n=this;return a(function(i){var o=[],s=new b,u=new d(s),c=0,a=!1,h=function(){var n=!1;o.length>0&&(n=!a,a=!0),n&&s.setDisposable(e.scheduleRecursive(function(e){var n;if(!(o.length>0))return a=!1,r;n=o.shift();var s=new v;u.add(s),s.setDisposable(n.subscribe(function(e){i.onNext(e);var n=null;try{n=t(e)}catch(r){i.onError(r)}o.push(n),c++,h()},i.onError.bind(i),function(){u.remove(s),c--,0===c&&i.onCompleted()})),e()}))};return o.push(n),c++,h(),u})},u.forkJoin=function(){var t=o(arguments,0);return a(function(e){var n=t.length;if(0===n)return e.onCompleted(),p;for(var i=new d,o=!1,s=Array(n),u=Array(n),c=Array(n),a=0;n>a;a++)(function(a){var h=t[a];i.add(h.subscribe(function(t){o||(s[a]=!0,c[a]=t)},function(t){o=!0,e.onError(t),i.dispose()},function(){if(!o){if(!s[a])return e.onCompleted(),r;u[a]=!0;for(var t=0;n>t;t++)if(!u[t])return;o=!0,e.onNext(c),e.onCompleted()}}))})(a);return i})},c.forkJoin=function(t,e){var n=this;return a(function(i){var o,s,u=!1,c=!1,a=!1,h=!1,l=new v,f=new v;return l.setDisposable(n.subscribe(function(t){a=!0,o=t},function(t){f.dispose(),i.onError(t)},function(){if(u=!0,c)if(a)if(h){var t;try{t=e(o,s)}catch(n){return i.onError(n),r}i.onNext(t),i.onCompleted()}else i.onCompleted();else i.onCompleted()})),f.setDisposable(t.subscribe(function(t){h=!0,s=t},function(t){l.dispose(),i.onError(t)},function(){if(c=!0,u)if(a)if(h){var t;try{t=e(o,s)}catch(n){return i.onError(n),r}i.onNext(t),i.onCompleted()}else i.onCompleted();else i.onCompleted()})),new d(l,f)})},c.manySelect=function(t,e){e||(e=g);var n=this;return u.defer(function(){var r;return n.select(function(t){var e=new _(t);return r&&r.onNext(t),r=e,e}).doAction(i,function(t){r&&r.onError(t)},function(){r&&r.onCompleted()}).observeOn(e).select(function(e,n,r){return t(e,n,r)})})};var _=function(t){function e(t){var e=this,n=new d;return n.add(E.schedule(function(){t.onNext(e.head),n.add(e.tail.mergeObservable().subscribe(t))})),n}function n(n){t.call(this,e),this.head=n,this.tail=new C}return A(n,t),S(n.prototype,D,{onCompleted:function(){this.onNext(u.empty())},onError:function(t){this.onNext(u.throwException(t))},onNext:function(t){this.tail.onNext(t),this.tail.onCompleted()}}),n}(u);return n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.1.18/rx.joinpatterns.js b/ajax/libs/rxjs/2.1.18/rx.joinpatterns.js new file mode 100644 index 000000000..f6908f1d8 --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.joinpatterns.js @@ -0,0 +1,408 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +(function (root, factory) { + var freeExports = typeof exports == 'object' && exports, + freeModule = typeof module == 'object' && module && module.exports == freeExports && module, + freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal) { + window = 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); + } +}(this, function (global, exp, Rx, undefined) { + + // Aliases + var Observable = Rx.Observable, + observableProto = Observable.prototype, + AnonymousObservable = Rx.Internals.AnonymousObservable, + observableThrow = Observable.throwException, + observerCreate = Rx.Observer.create, + SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, + CompositeDisposable = Rx.CompositeDisposable, + AbstractObserver = Rx.Internals.AbstractObserver, + isEqual = Rx.Internals.isEqual; + + // Defaults + function defaultComparer(x, y) { return isEqual(x, y); } + function noop() { } + + // Utilities + var inherits = Rx.Internals.inherits; + var slice = Array.prototype.slice; + 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.then = function (selector) { + return new Plan(this, selector); + }; + + // Plan + 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.disposable(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)); + + // Observable extensions + + /** + * 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.then = function (selector) { + return new Pattern([this]).then(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.1.18/rx.joinpatterns.min.js b/ajax/libs/rxjs/2.1.18/rx.joinpatterns.min.js new file mode 100644 index 000000000..c901d1ce2 --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.joinpatterns.min.js @@ -0,0 +1 @@ +(function(t,e){var n="object"==typeof exports&&exports,r=("object"==typeof module&&module&&module.exports==n&&module,"object"==typeof global&&global);r.global===r&&(window=r),"function"==typeof define&&define.amd?define(["rx","exports"],function(n,r){return t.Rx=e(t,r,n),t.Rx}):"object"==typeof module&&module&&module.exports===n?module.exports=e(t,module.exports,require("./rx")):t.Rx=e(t,{},t.Rx)})(this,function(t,e,n){function r(){}function i(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:y.call(t)}function o(t){this.patterns=t}function s(t,e){this.expression=t,this.selector=e}function u(t,e,n){var r=t.get(e);if(!r){var i=new g(e,n);return t.set(e,i),i}return r}function c(t,e,n){var r,i;for(this.joinObserverArray=t,this.onNext=e,this.onCompleted=n,this.joinObservers=new w,r=0;this.joinObserverArray.length>r;r++)i=this.joinObserverArray[r],this.joinObservers.set(i,i)}var a=n.Observable,h=a.prototype,l=n.Internals.AnonymousObservable,f=a.throwException,p=n.Observer.create,d=n.SingleAssignmentDisposable,b=n.CompositeDisposable,v=n.Internals.AbstractObserver;n.Internals.isEqual;var m=n.Internals.inherits,y=Array.prototype.slice,w=function(){function t(){this.keys=[],this.values=[]}return t.prototype["delete"]=function(t){var e=this.keys.indexOf(t);return-1!==e&&(this.keys.splice(e,1),this.values.splice(e,1)),-1!==e},t.prototype.get=function(t,e){var n=this.keys.indexOf(t);return-1!==n?this.values[n]:e},t.prototype.set=function(t,e){var n=this.keys.indexOf(t);-1!==n&&(this.values[n]=e),this.values[this.keys.push(t)-1]=e},t.prototype.size=function(){return this.keys.length},t.prototype.has=function(t){return-1!==this.keys.indexOf(t)},t.prototype.getKeys=function(){return this.keys.slice(0)},t.prototype.getValues=function(){return this.values.slice(0)},t}();o.prototype.and=function(t){var e=this.patterns.slice(0);return e.push(t),new o(e)},o.prototype.then=function(t){return new s(this,t)},s.prototype.activate=function(t,e,n){for(var r=this,i=[],o=0,s=this.expression.patterns.length;s>o;o++)i.push(u(t,this.expression.patterns[o],e.onError.bind(e)));var a=new c(i,function(){var t;try{t=r.selector.apply(r,arguments)}catch(n){return e.onError(n),undefined}e.onNext(t)},function(){for(var t=0,e=i.length;e>t;t++)i[t].removeActivePlan(a);n(a)});for(o=0,s=i.length;s>o;o++)i[o].addActivePlan(a);return a},c.prototype.dequeue=function(){for(var t=this.joinObservers.getValues(),e=0,n=t.length;n>e;e++)t[e].queue.shift()},c.prototype.match=function(){var t,e,n,r,i,o=!0;for(e=0,n=this.joinObserverArray.length;n>e;e++)if(0===this.joinObserverArray[e].queue.length){o=!1;break}if(o){for(t=[],r=!1,e=0,n=this.joinObserverArray.length;n>e;e++)t.push(this.joinObserverArray[e].queue[0]),"C"===this.joinObserverArray[e].queue[0].kind&&(r=!0);if(r)this.onCompleted();else{for(this.dequeue(),i=[],e=0;t.length>e;e++)i.push(t[e].value);this.onNext.apply(this,i)}}};var g=function(t){function e(e,n){t.call(this),this.source=e,this.onError=n,this.queue=[],this.activePlans=[],this.subscription=new d,this.isDisposed=!1}m(e,t);var n=e.prototype;return n.next=function(t){if(!this.isDisposed){if("E"===t.kind)return this.onError(t.exception),undefined;this.queue.push(t);for(var e=this.activePlans.slice(0),n=0,r=e.length;r>n;n++)e[n].match()}},n.error=r,n.completed=r,n.addActivePlan=function(t){this.activePlans.push(t)},n.subscribe=function(){this.subscription.disposable(this.source.materialize().subscribe(this))},n.removeActivePlan=function(t){var e=this.activePlans.indexOf(t);this.activePlans.splice(e,1),0===this.activePlans.length&&this.dispose()},n.dispose=function(){t.prototype.dispose.call(this),this.isDisposed||(this.isDisposed=!0,this.subscription.dispose())},e}(v);return h.and=function(t){return new o([this,t])},h.then=function(t){return new o([this]).then(t)},a.when=function(){var t=i(arguments,0);return new l(function(e){var n,r,i,o,s,u,c=[],a=new w;u=p(e.onNext.bind(e),function(t){for(var n=a.getValues(),r=0,i=n.length;i>r;r++)n[r].onError(t);e.onError(t)},e.onCompleted.bind(e));try{for(r=0,i=t.length;i>r;r++)c.push(t[r].activate(a,u,function(t){var e=c.indexOf(t);c.splice(e,1),0===c.length&&u.onCompleted()}))}catch(h){f(h).subscribe(e)}for(n=new b,s=a.getValues(),r=0,i=s.length;i>r;r++)o=s[r],o.subscribe(),n.add(o);return n})},n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.1.18/rx.js b/ajax/libs/rxjs/2.1.18/rx.js new file mode 100644 index 000000000..62cf3b0ce --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.js @@ -0,0 +1,5054 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +(function (window, undefined) { + + var freeExports = typeof exports == 'object' && exports, + freeModule = typeof module == 'object' && module && module.exports == freeExports && module, + freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal) { + window = freeGlobal; + } + + /** + * @name Rx + * @type Object + */ + var Rx = { Internals: {} }; + + // Defaults + function noop() { } + function identity(x) { return x; } + function defaultNow() { return new Date().getTime(); } + function defaultComparer(x, y) { return isEqual(x, y); } + function defaultSubComparer(x, y) { return x - y; } + function defaultKeySerializer(x) { return x.toString(); } + function defaultError(err) { throw err; } + + // 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); + } + } + + /** Used to determine if values are of the language type Object */ + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + /** `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) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + + if ({}.toString.call(fun) != "[object Function]") { + 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) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0, + result = Array(length), + thisp = arguments[1]; + + if ({}.toString.call(fun) != "[object Function]") { + 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) == '[object Array]'; + }; + } + + 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 = 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. + * + * @memberOf 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. + * + * @memberOf CompositeDisposable# + */ + 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. + * + * @memberOf 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. + * + * @memberOf CompositeDisposable# + * @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 + * + * @memberOf CompositeDisposable# + * @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. + * + * @memberOf Disposable# + */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * + * @static + * @memberOf Disposable + * @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. + * + * @static + * @memberOf Disposable + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + /** + * 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. + * + * @constructor + */ + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () { + this.isDisposed = false; + this.current = null; + }; + + var SingleAssignmentDisposablePrototype = SingleAssignmentDisposable.prototype; + + /** + * Gets or sets the underlying disposable. After disposal, the result of getting this method is undefined. + * + * @memberOf SingleAssignmentDisposable# + * @param {Disposable} [value] The new underlying disposable. + * @returns {Disposable} The underlying disposable. + */ + SingleAssignmentDisposablePrototype.disposable = function (value) { + return !value ? this.getDisposable() : this.setDisposable(value); + }; + + /** + * Gets the underlying disposable. After disposal, the result of getting this method is undefined. + * + * @memberOf SingleAssignmentDisposable# + * @returns {Disposable} The underlying disposable. + */ + SingleAssignmentDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * + * @memberOf SingleAssignmentDisposable# + * @param {Disposable} value The new underlying disposable. + */ + SingleAssignmentDisposablePrototype.setDisposable = function (value) { + if (this.current) { + throw new Error('Disposable has already been assigned'); + } + var shouldDispose = this.isDisposed; + if (!shouldDispose) { + this.current = value; + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable. + * + * @memberOf SingleAssignmentDisposable# + */ + SingleAssignmentDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + /** + * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. + * + * @constructor + */ + var SerialDisposable = Rx.SerialDisposable = function () { + this.isDisposed = false; + this.current = null; + }; + + /** + * Gets the underlying disposable. + * @return The underlying disposable + */ + SerialDisposable.prototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * + * @memberOf SerialDisposable# + * @param {Disposable} value The new underlying disposable. + */ + SerialDisposable.prototype.setDisposable = function (value) { + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + if (old) { + old.dispose(); + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Gets or sets the underlying disposable. + * If the SerialDisposable has already been disposed, assignment to this property causes immediate disposal of the given disposable object. Assigning this property disposes the previous disposable object. + * + * @memberOf SerialDisposable# + * @param {Disposable} [value] The new underlying disposable. + * @returns {Disposable} The underlying disposable. + */ + SerialDisposable.prototype.disposable = function (value) { + if (!value) { + return this.getDisposable(); + } else { + this.setDisposable(value); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + * + * @memberOf SerialDisposable# + */ + SerialDisposable.prototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + /** + * @constructor + * @private + */ + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + /** @private */ + 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 + * + * @memberOf RefCountDisposable# + */ + 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. + * + * @memberOf RefCountDisposable# + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.H + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + /** + * @constructor + * @private + */ + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler, this.disposable = disposable, this.isDisposed = false; + } + + /** + * @private + * @memberOf ScheduledDisposable# + */ + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + /** + * @private + * @constructor + */ + function ScheduledItem(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(); + } + + /** + * @private + * @memberOf ScheduledItem# + */ + ScheduledItem.prototype.invoke = function () { + this.disposable.disposable(this.invokeCore()); + }; + + /** + * @private + * @memberOf ScheduledItem# + */ + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + /** + * @private + * @memberOf ScheduledItem# + */ + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + /** + * @private + * @memberOf ScheduledItem# + */ + 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. + * + * @memberOf Scheduler# + * @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 = 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. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler# + * @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 = window.setInterval(function () { + s = action(s); + }, period); + return disposableCreate(function () { + window.clearInterval(id); + }); + }; + + /** + * Schedules an action to be executed. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler + * @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. + * + * @memberOf Scheduler + * @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. + * + * @memberOf Scheduler + * @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. + * + * @memberOf Scheduler + * @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. + * + * @static + * @memberOf Scheduler + * @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 schedulerNoBlockError = 'Scheduler is not allowed to block the thread'; + + /** + * Gets a scheduler that schedules work immediately on the current thread. + * + * @memberOf Scheduler + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { + return action(this, state); + } + + function scheduleRelative(state, dueTime, action) { + if (dueTime > 0) throw new Error(schedulerNoBlockError); + 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; + + /** + * @private + * @constructor + */ + function Trampoline() { + queue = new PriorityQueue(4); + } + + /** + * @private + * @memberOf Trampoline + */ + Trampoline.prototype.dispose = function () { + queue = null; + }; + + /** + * @private + * @memberOf Trampoline + */ + Trampoline.prototype.run = function () { + var item; + while (queue.length > 0) { + item = queue.dequeue(); + if (!item.isCancelled()) { + 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), + t; + if (!queue) { + t = new Trampoline(); + try { + queue.enqueue(si); + t.run(); + } catch (e) { + throw e; + } finally { + t.dispose(); + } + } 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 === null; }; + currentScheduler.ensureTrampoline = function (action) { + if (queue === null) { + return this.schedule(action); + } else { + return action(); + } + }; + + return currentScheduler; + }()); + + /** + * @private + */ + var SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + /** + * @constructor + * @private + */ + 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; + }()); + + /** Provides a set of extension methods for virtual time scheduling. */ + Rx.VirtualTimeScheduler = (function (_super) { + + 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; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. + * + * @memberOf VirtualTimeScheduler# + * @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. + * + * @memberOf VirtualTimeScheduler# + * @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. + * + * @memberOf VirtualTimeScheduler# + * @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. + * + * @memberOf VirtualTimeScheduler# + */ + VirtualTimeSchedulerPrototype.start = function () { + var next; + if (!this.isEnabled) { + this.isEnabled = true; + do { + next = this.getNext(); + if (next !== null) { + if (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. + * + * @memberOf VirtualTimeScheduler# + */ + 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 next; + 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 { + next = this.getNext(); + if (next !== null && this.comparer(next.dueTime, time) <= 0) { + if (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. + * + * @memberOf VirtualTimeScheduler# + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.advanceBy = function (time) { + var dt = this.add(this.clock, time); + var dueToClock = this.comparer(this.clock, dt); + if (dueToClock > 0) { + throw new Error(argumentOutOfRange); + } + if (dueToClock === 0) { + return; + } + return this.advanceTo(dt); + }; + + /** + * Advances the scheduler's clock by the specified relative time. + * + * @memberOf VirtualTimeScheduler# + * @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. + * + * @memberOf VirtualTimeScheduler# + * @returns {ScheduledItem} The next scheduled item. + */ + VirtualTimeSchedulerPrototype.getNext = function () { + var next; + while (this.queue.length > 0) { + next = this.queue.peek(); + if (next.isCancelled()) { + this.queue.dequeue(); + } else { + return next; + } + } + return null; + }; + + /** + * Schedules an action to be executed at dueTime. + * + * @memberOf VirtualTimeScheduler# + * @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. + * + * @memberOf VirtualTimeScheduler# + * @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, + run = function (scheduler, state1) { + self.queue.remove(si); + return action(scheduler, state1); + }, + si = new ScheduledItem(self, state, run, dueTime, self.comparer); + self.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. + * + * @memberOf HistoricalScheduler + * @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; + }; + + /** + * @private + * @memberOf HistoricalScheduler + */ + 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 scheduleMethod, clearMethod = noop; + (function () { + function postMessageSupported () { + // Ensure not in a worker + if (!window.postMessage || window.importScripts) { return false; } + var isAsync = false, + oldHandler = window.onmessage; + // Test for async + window.onmessage = function () { isAsync = true; }; + window.postMessage('','*'); + window.onmessage = oldHandler; + + return isAsync; + } + + // Check for setImmediate first for Node v0.11+ + if (typeof window.setImmediate === 'function') { + scheduleMethod = window.setImmediate; + clearMethod = clearImmediate; + } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } 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 (window.addEventListener) { + window.addEventListener('message', onGlobalPostMessage, false); + } else { + window.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + window.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!window.MessageChannel) { + var channel = new window.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 window && 'onreadystatechange' in window.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = window.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + window.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return window.setTimeout(action, 0); }; + clearMethod = window.clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + * + * @memberOf Scheduler + */ + 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 = window.setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + window.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; + } + + var NotificationPrototype = Notification.prototype; + + /** + * 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. + */ + NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { + if (arguments.length === 1 && typeof observerOrOnNext === 'object') { + return this._acceptObservable(observerOrOnNext); + } + return this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notification + * @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. + */ + NotificationPrototype.toObservable = function (scheduler) { + var notification = this; + scheduler = scheduler || immediateScheduler; + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + if (notification.kind === 'N') { + observer.onCompleted(); + } + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * + * @static + * @memberOf Notification + * @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.bind(notification); + notification._acceptObservable = _acceptObservable.bind(notification); + notification.toString = toString.bind(notification); + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * + * @static s + * @memberOf Notification + * @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.bind(notification); + notification._acceptObservable = _acceptObservable.bind(notification); + notification.toString = toString.bind(notification); + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * + * @static + * @memberOf Notification + * @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.bind(notification); + notification._acceptObservable = _acceptObservable.bind(notification); + notification.toString = toString.bind(notification); + return notification; + }; + }()); + + /** + * @constructor + * @private + */ + var Enumerator = Rx.Internals.Enumerator = function (moveNext, getCurrent, dispose) { + this.moveNext = moveNext; + this.getCurrent = getCurrent; + this.dispose = dispose; + }; + + /** + * @static + * @memberOf Enumerator + * @private + */ + var enumeratorCreate = Enumerator.create = function (moveNext, getCurrent, dispose) { + var done = false; + dispose || (dispose = noop); + return new Enumerator(function () { + if (done) { + return false; + } + var result = moveNext(); + if (!result) { + done = true; + dispose(); + } + return result; + }, function () { return getCurrent(); }, function () { + if (!done) { + dispose(); + done = true; + } + }); + }; + + /** @private */ + var Enumerable = Rx.Internals.Enumerable = (function () { + + /** + * @constructor + * @private + */ + function Enumerable(getEnumerator) { + this.getEnumerator = getEnumerator; + } + + /** + * @private + * @memberOf Enumerable# + */ + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e = sources.getEnumerator(), isDisposed = false, subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, ex, hasNext = false; + if (!isDisposed) { + try { + hasNext = e.moveNext(); + if (hasNext) { + current = e.getCurrent(); + } else { + e.dispose(); + } + } catch (exception) { + ex = exception; + e.dispose(); + } + } else { + return; + } + if (ex) { + observer.onError(ex); + return; + } + if (!hasNext) { + observer.onCompleted(); + return; + } + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + e.dispose(); + })); + }); + }; + + /** + * @private + * @memberOf Enumerable# + */ + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e = sources.getEnumerator(), isDisposed = false, lastException; + var subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, ex, hasNext; + hasNext = false; + if (!isDisposed) { + try { + hasNext = e.moveNext(); + if (hasNext) { + current = e.getCurrent(); + } + } catch (exception) { + ex = exception; + } + } else { + return; + } + if (ex) { + observer.onError(ex); + return; + } + if (!hasNext) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + return Enumerable; + }()); + + /** + * @static + * @private + * @memberOf Enumerable + */ + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount === undefined) { + repeatCount = -1; + } + return new Enumerable(function () { + var current, left = repeatCount; + return enumeratorCreate(function () { + if (left === 0) { + return false; + } + if (left > 0) { + left--; + } + current = value; + return true; + }, function () { return current; }); + }); + }; + + /** + * @static + * @private + * @memberOf Enumerable + */ + var enumerableFor = Enumerable.forEach = function (source, selector) { + selector || (selector = identity); + return new Enumerable(function () { + var current, index = -1; + return enumeratorCreate( + function () { + if (++index < source.length) { + current = selector(source[index], index); + return true; + } + return false; + }, + function () { return current; } + ); + }); + }; + + /** + * 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. + * + * @constructor + * @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. + * + * @memberOf AnonymousObserver + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * + * @memberOf AnonymousObserver + * @param {Any{ error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + * + * @memberOf AnonymousObserver + */ + 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)); + + /** @private */ + 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(); + } + + /** @private */ + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + /** @private */ + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + /** @private */ + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + /** @private */ + 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(); + })); + } + }; + + /** @private */ + 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 () { + + /** + * @constructor + * @private + */ + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + 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(); + } + }); + }); + }; + + /** + * 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; + if (typeof observerOrOnNext === 'object') { + subscriber = observerOrOnNext; + } else { + subscriber = observerCreate(observerOrOnNext, onError, onCompleted); + } + + return this._subscribe(subscriber); + }; + + /** + * Creates a list from an observable sequence. + * + * @memberOf Observable + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + function accumulator(list, i) { + var newList = list.slice(0); + newList.push(i); + return newList; + } + return this.scan([], accumulator).startWith([]).finalValue(); + }; + + return Observable; + })(); + + /** + * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. + * + * @example + * 1 - res = Rx.Observable.start(function () { console.log('hello'); }); + * 2 - res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); + * 2 - 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, scheduler, context) { + return observableToAsync(func, scheduler, context)(); + }; + + /** + * 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 + * 1 - res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); + * 2 - res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); + * 2 - 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, scheduler, context) { + 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(); + }; + }; + /** + * 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; + }); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * 1 - res = Rx.Observable.create(function (observer) { return function () { } ); + * + * @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 = function (subscribe) { + return new AnonymousObservable(function (o) { + return disposableCreate(subscribe(o)); + }); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * 1 - res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * @static + * @memberOf Observable + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.createWithDisposable = function (subscribe) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * 1 - res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @static + * @memberOf Observable + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence. + * @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); + } + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * 1 - res = Rx.Observable.empty(); + * 2 - res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @static + * @memberOf Observable + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * 1 - res = Rx.Observable.fromArray([1,2,3]); + * 2 - res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @static + * @memberOf Observable + * @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) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0; + return scheduler.scheduleRecursive(function (self) { + if (count < array.length) { + 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 + * 1 - res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); + * 2 - res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); + * @static + * @memberOf Observable + * @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) { + 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). + * + * @static + * @memberOf Observable + * @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 + * 1 - res = Rx.Observable.range(0, 10); + * 2 - res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @static + * @memberOf Observable + * @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) { + 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 + * 1 - res = Rx.Observable.repeat(42); + * 2 - 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); + * @static + * @memberOf Observable + * @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) { + scheduler || (scheduler = currentThreadScheduler); + if (repeatCount == null) { + repeatCount = -1; + } + return observableReturn(value, scheduler).repeat(repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'returnValue' for browsers 0) { + s = q.shift(); + subscribe(s); + } else { + activeCount--; + if (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; + if (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]); + * + * @static + * @memberOf Observable + * @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. + * + * @memberOf Observable# + * @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); + 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. + * + * @memberOf Observable + * @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]); + * @static + * @memberOf Observable + * @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++]; + 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. + * + * @memberOf Observable# + * @param {Observable} other The observable sequence 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) { + if (isOpen) { + observer.onNext(left); + } + }, observer.onError.bind(observer), function () { + if (isOpen) { + observer.onCompleted(); + } + })); + + 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. + * + * @memberOf Observable# + * @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); + 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. + * + * @memberOf Observable# + * @param {Observable} other Observable sequence 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) { + 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); + * @memberOf Observable# + * @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; }); + + var next = function (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) { + 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); + } + + 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. + * + * @static + * @memberOf Observable + * @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. + * + * @static + * @memberOf Observable + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = slice.call(arguments); + 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 + * 1 - xs.bufferWithCount(10); + * 2 - xs.bufferWithCount(10, 1); + * + * @memberOf Observable# + * @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 (skip === undefined) { + 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. + * + * @memberOf Observable# + * @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. + * + * 1 - var obs = observable.distinctUntilChanged(); + * 2 - var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * 3 - var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @memberOf Observable# + * @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 + * 1 - observable.doAction(observer); + * 2 - observable.doAction(onNext); + * 3 - observable.doAction(onNext, onError); + * 4 - observable.doAction(onNext, onError, onCompleted); + * + * @memberOf Observable# + * @param {Mixed} 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 = 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 (exception) { + if (!onError) { + observer.onError(exception); + } else { + try { + onError(exception); + } catch (e) { + observer.onError(e); + } + observer.onError(exception); + } + }, 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 + * 1 - obs = observable.finallyAction(function () { console.log('sequence ended'; }); + * + * @memberOf Observable# + * @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 = source.subscribe(observer); + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * + * @memberOf Observable# + * @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. + * + * @memberOf Observable# + * @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 (exception) { + observer.onNext(notificationCreateOnError(exception)); + 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 + * 1 - repeated = source.repeat(); + * 2 - repeated = source.repeat(42); + * + * @memberOf Observable# + * @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. + * + * @example + * 1 - retried = retry.repeat(); + * 2 - retried = retry.repeat(42); + * + * @memberOf Observable# + * @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. + * + * 1 - scanned = source.scan(function (acc, x) { return acc + x; }); + * 2 - scanned = source.scan(0, function (acc, x) { return acc + x; }); + * + * @memberOf Observable# + * @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 seed, hasSeed = false, accumulator; + if (arguments.length === 2) { + seed = arguments[0]; + accumulator = arguments[1]; + hasSeed = true; + } else { + accumulator = arguments[0]; + } + var source = this; + return observableDefer(function () { + var hasAccumulation = false, accumulation; + return source.select(function (x) { + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + return accumulation; + }); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * + * @memberOf Observable# + * @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. + * + * 1 - source.startWith(1, 2, 3); + * 2 - 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, using an optional scheduler to drain the queue. + * + * @example + * 1 - obs = source.takeLast(5); + * 2 - obs = source.takeLast(5, Rx.Scheduler.timeout); + * + * @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. + * + * @memberOf Observable# + * @param {Number} count Number of elements to take from the end of the source sequence. + * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion 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, scheduler) { + return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); + }; + + /** + * 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. + * + * @memberOf Observable# + * @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); + if (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. + * + * 1 - xs.windowWithCount(10); + * 2 - xs.windowWithCount(10, 1); + * + * @memberOf Observable# + * @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 (skip == null) { + 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 the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * 1 - 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(); + }); + }); + }; + + /** + * 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 + * 1 - obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); + * + * @memberOf Observable# + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, keySerializer) { + var source = this; + keySelector || (keySelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var hashSet = {}; + return source.subscribe(function (x) { + var key, serializedKey, otherKey, hasMatch = false; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (exception) { + observer.onError(exception); + return; + } + for (otherKey in hashSet) { + if (serializedKey === otherKey) { + hasMatch = true; + break; + } + } + if (!hasMatch) { + hashSet[serializedKey] = null; + 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 + * 1 - 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(); }); + * + * @memberOf Observable# + * @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} [keySerializer] Used to serialize the given object into a string for object comparison. + * @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, keySerializer) { + return this.groupByUntil(keySelector, elementSelector, function () { + return observableNever(); + }, keySerializer); + }; + + /** + * 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 + * 1 - 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(); }); + * + * @memberOf Observable# + * @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} [keySerializer] Used to serialize the given object into a string for object comparison. + * @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, keySerializer) { + var source = this; + elementSelector || (elementSelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var map = {}, + groupDisposable = new CompositeDisposable(), + refCountDisposable = new RefCountDisposable(groupDisposable); + groupDisposable.add(source.subscribe(function (x) { + var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + fireNewMapEntry = false; + try { + writer = map[serializedKey]; + if (!writer) { + writer = new Subject(); + map[serializedKey] = writer; + fireNewMapEntry = true; + } + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + if (fireNewMapEntry) { + group = new GroupedObservable(key, writer, refCountDisposable); + durationGroup = new GroupedObservable(key, writer); + try { + duration = durationSelector(durationGroup); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + observer.onNext(group); + md = new SingleAssignmentDisposable(); + groupDisposable.add(md); + var expire = function () { + if (serializedKey in map) { + delete map[serializedKey]; + writer.onCompleted(); + } + groupDisposable.remove(md); + }; + md.setDisposable(duration.take(1).subscribe(noop, function (exn) { + for (w in map) { + map[w].onError(exn); + } + observer.onError(exn); + }, function () { + expire(); + })); + } + try { + element = elementSelector(x); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + writer.onNext(element); + }, function (ex) { + for (var w in map) { + map[w].onError(ex); + } + observer.onError(ex); + }, function () { + for (var w in map) { + map[w].onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * + * @memberOf Observable# + * @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. + * + * @memberOf Observable# + * @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 selectMany(selector) { + return this.select(selector).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 + * 1 - 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. + * + * 1 - 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. + * + * 1 - source.selectMany(Rx.Observable.fromArray([1,2,3])); + * + * @memberOf Observable# + * @param selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto. + * @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.selectMany = observableProto.flatMap = function (selector, resultSelector) { + if (resultSelector) { + return this.selectMany(function (x) { + return selector(x).select(function (y) { + return resultSelector(x, y); + }); + }); + } + if (typeof selector === 'function') { + return selectMany.call(this, selector); + } + return selectMany.call(this, function () { + return selector; + }); + }; + + /** + * 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 and + * then transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * + * @example + * 1 - 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 + * and then transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * + * 1 - 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. + * and then transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * + * 1 - 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. + * @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 that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectManyLatest = observableProto.flatMapLatest = function (selector, resultSelector) { + return this.selectMany(selector, resultSelector).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * + * @memberOf Observable# + * @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. + * + * 1 - source.skipWhile(function (value) { return value < 10; }); + * 1 - source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * + * @memberOf Observable# + * @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). + * + * 1 - source.take(5); + * 2 - source.take(0, Rx.Scheduler.timeout); + * + * @memberOf Observable# + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case -1;return n.pop(),r.pop(),i}function d(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:B.call(t)}function b(t,e){for(var n=Array(t),r=0;t>r;r++)n[r]=e();return n}function v(t,e){this.scheduler=t,this.disposable=e,this.isDisposed=!1}function m(t,e,n,r,i){this.scheduler=t,this.state=e,this.action=n,this.dueTime=r,this.comparer=i||s,this.disposable=new re}function y(t,n){return new Ge(function(r){var i=new re,o=new oe;return o.setDisposable(i),i.setDisposable(t.subscribe(r.onNext.bind(r),function(t){var i,s;try{s=n(t)}catch(u){return r.onError(u),e}i=new re,o.setDisposable(i),i.setDisposable(s.subscribe(r))},r.onCompleted.bind(r))),o})}function w(t,n){var r=this;return new Ge(function(i){var o=0,s=t.length;return r.subscribe(function(r){if(s>o){var u,c=t[o++];try{u=n(r,c)}catch(a){return i.onError(a),e}i.onNext(u)}else i.onCompleted()},i.onError.bind(i),i.onCompleted.bind(i))})}function g(t){return this.select(t).mergeObservable()}var E="object"==typeof exports&&exports,x=("object"==typeof module&&module&&module.exports==E&&module,"object"==typeof global&&global);x.global===x&&(t=x);var C,D={Internals:{}},A="Sequence contains no elements.",S="Argument out of range",_="Object has been disposed",N={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},O="[object Arguments]",R="[object Array]",W="[object Boolean]",k="[object Date]",j="[object Function]",q="[object Number]",T="[object Object]",I="[object RegExp]",M="[object String]",P=Object.prototype.toString,L=Object.prototype.hasOwnProperty,V=P.call(arguments)==O;try{C=!(P.call(document)==T&&!({toString:0}+""))}catch(z){C=!0}V||(l=function(t){return t&&"object"==typeof t?L.call(t,"callee"):!1}),f(/x/)&&(f=function(t){return"function"==typeof t&&P.call(t)==j});var F=D.Internals.isEqual=function(t,e){return p(t,e,[],[])},B=Array.prototype.slice;({}).hasOwnProperty;var H=this.inherits=D.Internals.inherits=function(t,e){function n(){this.constructor=t}n.prototype=e.prototype,t.prototype=new n},U=D.Internals.addProperties=function(t){for(var e=B.call(arguments,1),n=0,r=e.length;r>n;n++){var i=e[n];for(var o in i)t[o]=i[o]}},G=D.Internals.addRef=function(t,e){return new Ge(function(n){return new Z(e.getDisposable(),t.subscribe(n))})};Function.prototype.bind||(Function.prototype.bind=function(t){var e=this,n=B.call(arguments,1),r=function(){function i(){}if(this instanceof r){i.prototype=e.prototype;var o=new i,s=e.apply(o,n.concat(B.call(arguments)));return Object(s)===s?s:o}return e.apply(t,n.concat(B.call(arguments)))};return r});var J=Object("a"),K="a"!=J[0]||!(0 in J);Array.prototype.every||(Array.prototype.every=function(t){var e=Object(this),n=K&&"[object String]"=={}.toString.call(this)?this.split(""):e,r=n.length>>>0,i=arguments[1];if("[object Function]"!={}.toString.call(t))throw new TypeError(t+" is not a function");for(var o=0;r>o;o++)if(o in n&&!t.call(i,n[o],o,e))return!1;return!0}),Array.prototype.map||(Array.prototype.map=function(t){var e=Object(this),n=K&&"[object String]"=={}.toString.call(this)?this.split(""):e,r=n.length>>>0,i=Array(r),o=arguments[1];if("[object Function]"!={}.toString.call(t))throw new TypeError(t+" is not a function");for(var s=0;r>s;s++)s in n&&(i[s]=t.call(o,n[s],s,e));return i}),Array.prototype.filter||(Array.prototype.filter=function(t){for(var e,n=[],r=Object(this),i=0,o=r.length>>>0;o>i;i++)e=r[i],i in r&&t.call(arguments[1],e,i,r)&&n.push(e);return n}),Array.isArray||(Array.isArray=function(t){return"[object Array]"==Object.prototype.toString.call(t)}),Array.prototype.indexOf||(Array.prototype.indexOf=function(t){var e=Object(this),n=e.length>>>0;if(0===n)return-1;var r=0;if(arguments.length>1&&(r=Number(arguments[1]),r!==r?r=0:0!==r&&1/0!=r&&r!==-1/0&&(r=(r>0||-1)*Math.floor(Math.abs(r)))),r>=n)return-1;for(var i=r>=0?r:Math.max(n-Math.abs(r),0);n>i;i++)if(i in e&&e[i]===t)return i;return-1});var Q=function(t,e){this.id=t,this.value=e};Q.prototype.compareTo=function(t){var e=this.value.compareTo(t.value);return 0===e&&(e=this.id-t.id),e};var X=function(t){this.items=Array(t),this.length=0},Y=X.prototype;Y.isHigherPriority=function(t,e){return 0>this.items[t].compareTo(this.items[e])},Y.percolate=function(t){if(!(t>=this.length||0>t)){var e=t-1>>1;if(!(0>e||e===t)&&this.isHigherPriority(t,e)){var n=this.items[t];this.items[t]=this.items[e],this.items[e]=n,this.percolate(e)}}},Y.heapify=function(t){if(t===e&&(t=0),!(t>=this.length||0>t)){var n=2*t+1,r=2*t+2,i=t;if(this.length>n&&this.isHigherPriority(n,i)&&(i=n),this.length>r&&this.isHigherPriority(r,i)&&(i=r),i!==t){var o=this.items[t];this.items[t]=this.items[i],this.items[i]=o,this.heapify(i)}}},Y.peek=function(){return this.items[0].value},Y.removeAt=function(t){this.items[t]=this.items[--this.length],delete this.items[this.length],this.heapify()},Y.dequeue=function(){var t=this.peek();return this.removeAt(0),t},Y.enqueue=function(t){var e=this.length++;this.items[e]=new Q(X.count++,t),this.percolate(e)},Y.remove=function(t){for(var e=0;this.length>e;e++)if(this.items[e].value===t)return this.removeAt(e),!0;return!1},X.count=0;var Z=D.CompositeDisposable=function(){this.disposables=d(arguments,0),this.isDisposed=!1,this.length=this.disposables.length},$=Z.prototype;$.add=function(t){this.isDisposed?t.dispose():(this.disposables.push(t),this.length++)},$.remove=function(t){var e=!1;if(!this.isDisposed){var n=this.disposables.indexOf(t);-1!==n&&(e=!0,this.disposables.splice(n,1),this.length--,t.dispose())}return e},$.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()}},$.clear=function(){var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()},$.contains=function(t){return-1!==this.disposables.indexOf(t)},$.toArray=function(){return this.disposables.slice(0)};var te=D.Disposable=function(t){this.isDisposed=!1,this.action=t||n};te.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var ee=te.create=function(t){return new te(t)},ne=te.empty={dispose:n},re=D.SingleAssignmentDisposable=function(){this.isDisposed=!1,this.current=null},ie=re.prototype;ie.disposable=function(t){return t?this.setDisposable(t):this.getDisposable()},ie.getDisposable=function(){return this.current},ie.setDisposable=function(t){if(this.current)throw Error("Disposable has already been assigned");var e=this.isDisposed;e||(this.current=t),e&&t&&t.dispose()},ie.dispose=function(){var t;this.isDisposed||(this.isDisposed=!0,t=this.current,this.current=null),t&&t.dispose()};var oe=D.SerialDisposable=function(){this.isDisposed=!1,this.current=null};oe.prototype.getDisposable=function(){return this.current},oe.prototype.setDisposable=function(t){var e,n=this.isDisposed;n||(e=this.current,this.current=t),e&&e.dispose(),n&&t&&t.dispose()},oe.prototype.disposable=function(t){return t?(this.setDisposable(t),e):this.getDisposable()},oe.prototype.dispose=function(){var t;this.isDisposed||(this.isDisposed=!0,t=this.current,this.current=null),t&&t.dispose()};var se=D.RefCountDisposable=function(){function t(t){this.disposable=t,this.disposable.count++,this.isInnerDisposed=!1}function e(t){this.underlyingDisposable=t,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return t.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()))},e.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},e.prototype.getDisposable=function(){return this.isDisposed?ne:new t(this)},e}();v.prototype.dispose=function(){var t=this;this.scheduler.schedule(function(){t.isDisposed||(t.isDisposed=!0,t.disposable.dispose())})},m.prototype.invoke=function(){this.disposable.disposable(this.invokeCore())},m.prototype.compareTo=function(t){return this.comparer(this.dueTime,t.dueTime)},m.prototype.isCancelled=function(){return this.disposable.isDisposed},m.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var ue=D.Scheduler=function(){function e(t,e,n,r){this.now=t,this._schedule=e,this._scheduleRelative=n,this._scheduleAbsolute=r}function n(t,e){var n=e.first,r=e.second,i=new Z,o=function(e){r(e,function(e){var n=!1,r=!1,s=t.scheduleWithState(e,function(t,e){return n?i.remove(s):r=!0,o(e),ne});r||(i.add(s),n=!0)})};return o(n),i}function r(t,e,n){var r=e.first,i=e.second,o=new Z,s=function(e){i(e,function(e,r){var i=!1,u=!1,c=t[n].call(t,e,r,function(t,e){return i?o.remove(c):u=!0,s(e),ne});u||(o.add(c),i=!0)})};return s(r),o}function o(t,e){return e(),ne}var s=e.prototype;return s.catchException=function(t){return new be(this,t)},s.schedulePeriodic=function(t,e){return this.schedulePeriodicWithState(null,t,function(){e()})},s.schedulePeriodicWithState=function(e,n,r){var i=e,o=t.setInterval(function(){i=r(i)},n);return ee(function(){t.clearInterval(o)})},s.schedule=function(t){return this._schedule(t,o)},s.scheduleWithState=function(t,e){return this._schedule(t,e)},s.scheduleWithRelative=function(t,e){return this._scheduleRelative(e,t,o)},s.scheduleWithRelativeAndState=function(t,e,n){return this._scheduleRelative(t,e,n)},s.scheduleWithAbsolute=function(t,e){return this._scheduleAbsolute(e,t,o)},s.scheduleWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute(t,e,n)},s.scheduleRecursive=function(t){return this.scheduleRecursiveWithState(t,function(t,e){t(function(){e(t)})})},s.scheduleRecursiveWithState=function(t,e){return this.scheduleWithState({first:t,second:e},function(t,e){return n(t,e)})},s.scheduleRecursiveWithRelative=function(t,e){return this.scheduleRecursiveWithRelativeAndState(e,t,function(t,e){t(function(n){e(t,n)})})},s.scheduleRecursiveWithRelativeAndState=function(t,e,n){return this._scheduleRelative({first:t,second:n},e,function(t,e){return r(t,e,"scheduleWithRelativeAndState")})},s.scheduleRecursiveWithAbsolute=function(t,e){return this.scheduleRecursiveWithAbsoluteAndState(e,t,function(t,e){t(function(n){e(t,n)})})},s.scheduleRecursiveWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute({first:t,second:n},e,function(t,e){return r(t,e,"scheduleWithAbsoluteAndState")})},e.now=i,e.normalize=function(t){return 0>t&&(t=0),t},e}(),ce="Scheduler is not allowed to block the thread",ae=ue.immediate=function(){function t(t,e){return e(this,t)}function e(t,e,n){if(e>0)throw Error(ce);return n(this,t)}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new ue(i,t,e,n)}(),he=ue.currentThread=function(){function t(){o=new X(4)}function e(t,e){return this.scheduleWithRelativeAndState(t,0,e)}function n(e,n,r){var i,s=this.now()+ue.normalize(n),u=new m(this,e,r,s);if(o)o.enqueue(u);else{i=new t;try{o.enqueue(u),i.run()}catch(c){throw c}finally{i.dispose()}}return u.disposable}function r(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}var o;t.prototype.dispose=function(){o=null},t.prototype.run=function(){for(var t;o.length>0;)if(t=o.dequeue(),!t.isCancelled()){for(;t.dueTime-ue.now()>0;);t.isCancelled()||t.invoke()}};var s=new ue(i,e,n,r);return s.scheduleRequired=function(){return null===o},s.ensureTrampoline=function(t){return null===o?this.schedule(t):t()},s}(),le=function(){function t(t,e){e(0,this._period);try{this._state=this._action(this._state)}catch(n){throw this._cancel.dispose(),n}}function e(t,e,n,r){this._scheduler=t,this._state=e,this._period=n,this._action=r}return e.prototype.start=function(){var e=new re;return this._cancel=e,e.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,t.bind(this))),e},e}();D.VirtualTimeScheduler=function(t){function n(){return this.toDateTimeOffset(this.clock)}function r(t,e){return this.scheduleAbsoluteWithState(t,this.clock,e)}function i(t,e,n){return this.scheduleRelativeWithState(t,this.toRelative(e),n)}function o(t,e,n){return this.scheduleRelativeWithState(t,this.toRelative(e-this.now()),n)}function s(t,e){return e(),ne}function u(e,s){this.clock=e,this.comparer=s,this.isEnabled=!1,this.queue=new X(1024),t.call(this,n,r,i,o)}H(u,t);var c=u.prototype;return c.schedulePeriodicWithState=function(t,e,n){var r=new le(this,t,e,n);return r.start()},c.scheduleRelativeWithState=function(t,e,n){var r=this.add(this.clock,e);return this.scheduleAbsoluteWithState(t,r,n)},c.scheduleRelative=function(t,e){return this.scheduleRelativeWithState(e,t,s)},c.start=function(){var t;if(!this.isEnabled){this.isEnabled=!0;do t=this.getNext(),null!==t?(this.comparer(t.dueTime,this.clock)>0&&(this.clock=t.dueTime),t.invoke()):this.isEnabled=!1;while(this.isEnabled)}},c.stop=function(){this.isEnabled=!1},c.advanceTo=function(t){var e,n=this.comparer(this.clock,t);if(this.comparer(this.clock,t)>0)throw Error(S);if(0!==n&&!this.isEnabled){this.isEnabled=!0;do e=this.getNext(),null!==e&&0>=this.comparer(e.dueTime,t)?(this.comparer(e.dueTime,this.clock)>0&&(this.clock=e.dueTime),e.invoke()):this.isEnabled=!1;while(this.isEnabled);this.clock=t}},c.advanceBy=function(t){var n=this.add(this.clock,t),r=this.comparer(this.clock,n);if(r>0)throw Error(S);return 0!==r?this.advanceTo(n):e},c.sleep=function(t){var e=this.add(this.clock,t);if(this.comparer(this.clock,e)>=0)throw Error(S);this.clock=e},c.getNext=function(){for(var t;this.queue.length>0;){if(t=this.queue.peek(),!t.isCancelled())return t;this.queue.dequeue()}return null},c.scheduleAbsolute=function(t,e){return this.scheduleAbsoluteWithState(e,t,s)},c.scheduleAbsoluteWithState=function(t,e,n){var r=this,i=function(t,e){return r.queue.remove(o),n(t,e)},o=new m(r,t,i,e,r.comparer);return r.queue.enqueue(o),o.disposable},u}(ue),D.HistoricalScheduler=function(t){function e(e,n){var r=null==e?0:e,i=n||s;t.call(this,r,i)}H(e,t);var n=e.prototype;return n.add=function(t,e){return t+e},n.toDateTimeOffset=function(t){return new Date(t).getTime()},n.toRelative=function(t){return t},e}(D.VirtualTimeScheduler);var fe,pe=n;(function(){function e(){if(!t.postMessage||t.importScripts)return!1;var e=!1,n=t.onmessage;return t.onmessage=function(){e=!0},t.postMessage("","*"),t.onmessage=n,e}function n(t){if("string"==typeof t.data&&t.data.substring(0,r.length)===r){var e=t.data.substring(r.length),n=i[e];n(),delete i[e]}}if("function"==typeof t.setImmediate)fe=t.setImmediate,pe=clearImmediate;else if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))fe=process.nextTick;else if(e()){var r="ms.rx.schedule"+Math.random(),i={},o=0;t.addEventListener?t.addEventListener("message",n,!1):t.attachEvent("onmessage",n,!1),fe=function(e){var n=o++;i[n]=e,t.postMessage(r+n,"*")}}else if(t.MessageChannel){var s=new t.MessageChannel,u={},c=0;s.port1.onmessage=function(t){var e=t.data,n=u[e];n(),delete u[e]},fe=function(t){var e=c++;u[e]=t,s.port2.postMessage(e)}}else"document"in t&&"onreadystatechange"in t.document.createElement("script")?fe=function(e){var n=t.document.createElement("script");n.onreadystatechange=function(){e(),n.onreadystatechange=null,n.parentNode.removeChild(n),n=null},t.document.documentElement.appendChild(n)}:(fe=function(e){return t.setTimeout(e,0)},pe=t.clearTimeout)})();var de=ue.timeout=function(){function e(t,e){var n=this,r=new re,i=fe(function(){r.isDisposed||r.setDisposable(e(n,t))});return new Z(r,ee(function(){pe(i)}))}function n(e,n,r){var i=this,o=ue.normalize(n);if(0===o)return i.scheduleWithState(e,r);var s=new re,u=t.setTimeout(function(){s.isDisposed||s.setDisposable(r(i,e))},o);return new Z(s,ee(function(){t.clearTimeout(u)}))}function r(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new ue(i,e,n,r)}(),be=function(t){function e(){return this._scheduler.now()}function n(t,e){return this._scheduler.scheduleWithState(t,this._wrap(e))}function r(t,e,n){return this._scheduler.scheduleWithRelativeAndState(t,e,this._wrap(n))}function i(t,e,n){return this._scheduler.scheduleWithAbsoluteAndState(t,e,this._wrap(n))}function o(o,s){this._scheduler=o,this._handler=s,this._recursiveOriginal=null,this._recursiveWrapper=null,t.call(this,e,n,r,i)}return H(o,t),o.prototype._clone=function(t){return new o(t,this._handler)},o.prototype._wrap=function(t){var e=this;return function(n,r){try{return t(e._getRecursiveWrapper(n),r)}catch(i){if(!e._handler(i))throw i;return ne}}},o.prototype._getRecursiveWrapper=function(t){if(this._recursiveOriginal!==t){this._recursiveOriginal=t;var e=this._clone(t);e._recursiveOriginal=t,e._recursiveWrapper=e,this._recursiveWrapper=e}return this._recursiveWrapper},o.prototype.schedulePeriodicWithState=function(t,e,n){var r=this,i=!1,o=new re;return o.setDisposable(this._scheduler.schedulePeriodicWithState(t,e,function(t){if(i)return null;try{return n(t)}catch(e){if(i=!0,!r._handler(e))throw e;return o.dispose(),null}})),o},o}(ue),ve=D.Notification=function(){function t(t,e){this.hasValue=null==e?!1:e,this.kind=t}var e=t.prototype;return e.accept=function(t,e,n){return 1===arguments.length&&"object"==typeof t?this._acceptObservable(t):this._accept(t,e,n)},e.toObservable=function(t){var e=this;return t=t||ae,new Ge(function(n){return t.schedule(function(){e._acceptObservable(n),"N"===e.kind&&n.onCompleted()})})},t}(),me=ve.createOnNext=function(){function t(t){return t(this.value)}function e(t){return t.onNext(this.value)}function n(){return"OnNext("+this.value+")"}return function(r){var i=new ve("N",!0);return i.value=r,i._accept=t.bind(i),i._acceptObservable=e.bind(i),i.toString=n.bind(i),i}}(),ye=ve.createOnError=function(){function t(t,e){return e(this.exception)}function e(t){return t.onError(this.exception)}function n(){return"OnError("+this.exception+")"}return function(r){var i=new ve("E");return i.exception=r,i._accept=t.bind(i),i._acceptObservable=e.bind(i),i.toString=n.bind(i),i}}(),we=ve.createOnCompleted=function(){function t(t,e,n){return n()}function e(t){return t.onCompleted()}function n(){return"OnCompleted()"}return function(){var r=new ve("C");return r._accept=t.bind(r),r._acceptObservable=e.bind(r),r.toString=n.bind(r),r}}(),ge=D.Internals.Enumerator=function(t,e,n){this.moveNext=t,this.getCurrent=e,this.dispose=n},Ee=ge.create=function(t,e,r){var i=!1;return r||(r=n),new ge(function(){if(i)return!1;var e=t();return e||(i=!0,r()),e},function(){return e()},function(){i||(r(),i=!0)})},xe=D.Internals.Enumerable=function(){function t(t){this.getEnumerator=t}return t.prototype.concat=function(){var t=this;return new Ge(function(n){var r=t.getEnumerator(),i=!1,o=new oe,s=ae.scheduleRecursive(function(t){var s,u,c=!1;if(!i){try{c=r.moveNext(),c?s=r.getCurrent():r.dispose()}catch(a){u=a,r.dispose()}if(u)return n.onError(u),e;if(!c)return n.onCompleted(),e;var h=new re;o.setDisposable(h),h.setDisposable(s.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){t()}))}});return new Z(o,s,ee(function(){i=!0,r.dispose()}))})},t.prototype.catchException=function(){var t=this;return new Ge(function(n){var r,i=t.getEnumerator(),o=!1,s=new oe,u=ae.scheduleRecursive(function(t){var u,c,a;if(a=!1,!o){try{a=i.moveNext(),a&&(u=i.getCurrent())}catch(h){c=h}if(c)return n.onError(c),e;if(!a)return r?n.onError(r):n.onCompleted(),e;var l=new re;s.setDisposable(l),l.setDisposable(u.subscribe(n.onNext.bind(n),function(e){r=e,t()},n.onCompleted.bind(n)))}});return new Z(s,u,ee(function(){o=!0}))})},t}(),Ce=xe.repeat=function(t,n){return n===e&&(n=-1),new xe(function(){var e,r=n;return Ee(function(){return 0===r?!1:(r>0&&r--,e=t,!0)},function(){return e})})},De=xe.forEach=function(t,e){return e||(e=r),new xe(function(){var n,r=-1;return Ee(function(){return++r0&&(t=!this.isAcquired,this.isAcquired=!0),t&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(t){var r;if(!(n.queue.length>0))return n.isAcquired=!1,e;r=n.queue.shift();try{r()}catch(i){throw n.queue=[],n.hasFaulted=!0,i}t()}))},n.prototype.dispose=function(){t.prototype.dispose.call(this),this.disposable.dispose()},n}(Ne),ke=function(t){function e(){t.apply(this,arguments)}return H(e,t),e.prototype.next=function(e){t.prototype.next.call(this,e),this.ensureActive()},e.prototype.error=function(e){t.prototype.error.call(this,e),this.ensureActive()},e.prototype.completed=function(){t.prototype.completed.call(this),this.ensureActive()},e}(We),je=D.Observable=function(){function t(t){this._subscribe=t}return _e=t.prototype,_e.finalValue=function(){var t=this;return new Ge(function(e){var n,r=!1;return t.subscribe(function(t){r=!0,n=t},e.onError.bind(e),function(){r?(e.onNext(n),e.onCompleted()):e.onError(Error(A))})})},_e.subscribe=_e.forEach=function(t,e,n){var r;return r="object"==typeof t?t:Se(t,e,n),this._subscribe(r)},_e.toArray=function(){function t(t,e){var n=t.slice(0);return n.push(e),n}return this.scan([],t).startWith([]).finalValue()},t}();je.start=function(t,e,n){return qe(t,e,n)()};var qe=je.toAsync=function(t,n,r){return n||(n=de),function(){var i=arguments,o=new Ye;return n.schedule(function(){var n;try{n=t.apply(r,i)}catch(s){return o.onError(s),e}o.onNext(n),o.onCompleted()}),o.asObservable()}};_e.observeOn=function(t){var e=this;return new Ge(function(n){return e.subscribe(new ke(t,n))})},_e.subscribeOn=function(t){var e=this;return new Ge(function(n){var r=new re,i=new oe;return i.setDisposable(r),r.setDisposable(t.schedule(function(){i.setDisposable(new v(t,e.subscribe(n)))})),i})},je.create=function(t){return new Ge(function(e){return ee(t(e))})},je.createWithDisposable=function(t){return new Ge(t)};var Te=je.defer=function(t){return new Ge(function(e){var n;try{n=t()}catch(r){return Ve(r).subscribe(e)}return n.subscribe(e)})},Ie=je.empty=function(t){return t||(t=ae),new Ge(function(e){return t.schedule(function(){e.onCompleted()})})},Me=je.fromArray=function(t,e){return e||(e=he),new Ge(function(n){var r=0;return e.scheduleRecursive(function(e){t.length>r?(n.onNext(t[r++]),e()):n.onCompleted()})})};je.generate=function(t,n,r,i,o){return o||(o=he),new Ge(function(s){var u=!0,c=t;return o.scheduleRecursive(function(t){var o,a;try{u?u=!1:c=r(c),o=n(c),o&&(a=i(c))}catch(h){return s.onError(h),e}o?(s.onNext(a),t()):s.onCompleted()})})};var Pe=je.never=function(){return new Ge(function(){return ne})};je.range=function(t,e,n){return n||(n=he),new Ge(function(r){return n.scheduleRecursiveWithState(0,function(n,i){e>n?(r.onNext(t+n),i(n+1)):r.onCompleted()})})},je.repeat=function(t,e,n){return n||(n=he),null==e&&(e=-1),Le(t,n).repeat(e)};var Le=je["return"]=je.returnValue=function(t,e){return e||(e=ae),new Ge(function(n){return e.schedule(function(){n.onNext(t),n.onCompleted()})})},Ve=je["throw"]=je.throwException=function(t,e){return e||(e=ae),new Ge(function(n){return e.schedule(function(){n.onError(t)})})};je.using=function(t,e){return new Ge(function(n){var r,i,o=ne;try{r=t(),r&&(o=r),i=e(r)}catch(s){return new Z(Ve(s).subscribe(n),o)}return new Z(i.subscribe(n),o)})},_e.amb=function(t){var e=this;return new Ge(function(n){function r(){o||(o=s,a.dispose())}function i(){o||(o=u,c.dispose())}var o,s="L",u="R",c=new re,a=new re;return c.setDisposable(e.subscribe(function(t){r(),o===s&&n.onNext(t)},function(t){r(),o===s&&n.onError(t)},function(){r(),o===s&&n.onCompleted()})),a.setDisposable(t.subscribe(function(t){i(),o===u&&n.onNext(t)},function(t){i(),o===u&&n.onError(t)},function(){i(),o===u&&n.onCompleted()})),new Z(c,a)})},je.amb=function(){function t(t,e){return t.amb(e)}for(var e=Pe(),n=d(arguments,0),r=0,i=n.length;i>r;r++)e=t(e,n[r]);return e},_e["catch"]=_e.catchException=function(t){return"function"==typeof t?y(this,t):ze([this,t])};var ze=je.catchException=je["catch"]=function(){var t=d(arguments,0);return De(t).catchException()};_e.combineLatest=function(){var t=B.call(arguments);return Array.isArray(t[0])?t[0].unshift(this):t.unshift(this),Fe.apply(this,t)};var Fe=je.combineLatest=function(){var t=B.call(arguments),n=t.pop();return Array.isArray(t[0])&&(t=t[0]),new Ge(function(r){function i(t){var i;if(c[t]=!0,a||(a=c.every(function(t){return t}))){try{i=n.apply(null,l)}catch(o){return r.onError(o),e}r.onNext(i)}else h.filter(function(e,n){return n!==t}).every(function(t){return t})&&r.onCompleted()}function o(t){h[t]=!0,h.every(function(t){return t})&&r.onCompleted()}for(var s=function(){return!1},u=t.length,c=b(u,s),a=!1,h=b(u,s),l=Array(u),f=Array(u),p=0;u>p;p++)(function(e){f[e]=new re,f[e].setDisposable(t[e].subscribe(function(t){l[e]=t,i(e)},r.onError.bind(r),function(){o(e)}))})(p);return new Z(f)})};_e.concat=function(){var t=B.call(arguments,0);return t.unshift(this),Be.apply(this,t)};var Be=je.concat=function(){var t=d(arguments,0);return De(t).concat()};_e.concatObservable=_e.concatAll=function(){return this.merge(1)},_e.merge=function(t){if("number"!=typeof t)return He(this,t);var e=this;return new Ge(function(n){var r=0,i=new Z,o=!1,s=[],u=function(t){var e=new re;i.add(e),e.setDisposable(t.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){var t;i.remove(e),s.length>0?(t=s.shift(),u(t)):(r--,o&&0===r&&n.onCompleted())}))};return i.add(e.subscribe(function(e){t>r?(r++,u(e)):s.push(e)},n.onError.bind(n),function(){o=!0,0===r&&n.onCompleted()})),i})};var He=je.merge=function(){var t,e;return arguments[0]?arguments[0].now?(t=arguments[0],e=B.call(arguments,1)):(t=ae,e=B.call(arguments,0)):(t=ae,e=B.call(arguments,1)),Array.isArray(e[0])&&(e=e[0]),Me(e,t).mergeObservable()};_e.mergeObservable=_e.mergeAll=function(){var t=this;return new Ge(function(e){var n=new Z,r=!1,i=new re;return n.add(i),i.setDisposable(t.subscribe(function(t){var i=new re;n.add(i),i.setDisposable(t.subscribe(function(t){e.onNext(t)},e.onError.bind(e),function(){n.remove(i),r&&1===n.length&&e.onCompleted()}))},e.onError.bind(e),function(){r=!0,1===n.length&&e.onCompleted()})),n})},_e.onErrorResumeNext=function(t){if(!t)throw Error("Second observable is required");return Ue([this,t])};var Ue=je.onErrorResumeNext=function(){var t=d(arguments,0);return new Ge(function(e){var n=0,r=new oe,i=ae.scheduleRecursive(function(i){var o,s;t.length>n?(o=t[n++],s=new re,r.setDisposable(s),s.setDisposable(o.subscribe(e.onNext.bind(e),function(){i()},function(){i()}))):e.onCompleted()});return new Z(r,i)})};_e.skipUntil=function(t){var e=this;return new Ge(function(n){var r=!1,i=new Z(e.subscribe(function(t){r&&n.onNext(t)},n.onError.bind(n),function(){r&&n.onCompleted()})),o=new re;return i.add(o),o.setDisposable(t.subscribe(function(){r=!0,o.dispose()},n.onError.bind(n),function(){o.dispose()})),i})},_e["switch"]=_e.switchLatest=function(){var t=this;return new Ge(function(e){var n=!1,r=new oe,i=!1,o=0,s=t.subscribe(function(t){var s=new re,u=++o;n=!0,r.setDisposable(s),s.setDisposable(t.subscribe(function(t){o===u&&e.onNext(t)},function(t){o===u&&e.onError(t)},function(){o===u&&(n=!1,i&&e.onCompleted())}))},e.onError.bind(e),function(){i=!0,n||e.onCompleted()});return new Z(s,r)})},_e.takeUntil=function(t){var e=this;return new Ge(function(r){return new Z(e.subscribe(r),t.subscribe(r.onCompleted.bind(r),r.onError.bind(r),n))})},_e.zip=function(){if(Array.isArray(arguments[0]))return w.apply(this,arguments);var t=this,n=B.call(arguments),i=n.pop();return n.unshift(t),new Ge(function(o){function s(t){a[t]=!0,a.every(function(t){return t})&&o.onCompleted()}for(var u=n.length,c=b(u,function(){return[]}),a=b(u,function(){return!1}),h=function(n){var s,u;if(c.every(function(t){return t.length>0})){try{u=c.map(function(t){return t.shift()}),s=i.apply(t,u)}catch(h){return o.onError(h),e}o.onNext(s)}else a.filter(function(t,e){return e!==n}).every(r)&&o.onCompleted()},l=Array(u),f=0;u>f;f++)(function(t){l[t]=new re,l[t].setDisposable(n[t].subscribe(function(e){c[t].push(e),h(t)},o.onError.bind(o),function(){s(t)}))})(f);return new Z(l)})},je.zip=function(){var t=B.call(arguments,0),e=t.shift();return e.zip.apply(e,t)},je.zipArray=function(){var t=B.call(arguments);return new Ge(function(n){function i(t){if(u.every(function(t){return t.length>0})){var i=u.map(function(t){return t.shift()});n.onNext(i) +}else if(c.filter(function(e,n){return n!==t}).every(r))return n.onCompleted(),e}function o(t){return c[t]=!0,c.every(r)?(n.onCompleted(),e):e}for(var s=t.length,u=b(s,function(){return[]}),c=b(s,function(){return!1}),a=Array(s),h=0;s>h;h++)(function(e){a[e]=new re,a[e].setDisposable(t[e].subscribe(function(t){u[e].push(t),i(e)},n.onError.bind(n),function(){o(e)}))})(h);var l=new Z(a);return l.add(ee(function(){for(var t=0,e=u.length;e>t;t++)u[t]=[]})),l})},_e.asObservable=function(){var t=this;return new Ge(function(e){return t.subscribe(e)})},_e.bufferWithCount=function(t,n){return n===e&&(n=t),this.windowWithCount(t,n).selectMany(function(t){return t.toArray()}).where(function(t){return t.length>0})},_e.dematerialize=function(){var t=this;return new Ge(function(e){return t.subscribe(function(t){return t.accept(e)},e.onError.bind(e),e.onCompleted.bind(e))})},_e.distinctUntilChanged=function(t,n){var i=this;return t||(t=r),n||(n=o),new Ge(function(r){var o,s=!1;return i.subscribe(function(i){var u,c=!1;try{u=t(i)}catch(a){return r.onError(a),e}if(s)try{c=n(o,u)}catch(a){return r.onError(a),e}s&&c||(s=!0,o=u,r.onNext(i))},r.onError.bind(r),r.onCompleted.bind(r))})},_e["do"]=_e.doAction=function(t,e,n){var r,i=this;return"function"==typeof t?r=t:(r=t.onNext.bind(t),e=t.onError.bind(t),n=t.onCompleted.bind(t)),new Ge(function(t){return i.subscribe(function(e){try{r(e)}catch(n){t.onError(n)}t.onNext(e)},function(n){if(e){try{e(n)}catch(r){t.onError(r)}t.onError(n)}else t.onError(n)},function(){if(n){try{n()}catch(e){t.onError(e)}t.onCompleted()}else t.onCompleted()})})},_e["finally"]=_e.finallyAction=function(t){var e=this;return new Ge(function(n){var r=e.subscribe(n);return ee(function(){try{r.dispose()}catch(e){throw e}finally{t()}})})},_e.ignoreElements=function(){var t=this;return new Ge(function(e){return t.subscribe(n,e.onError.bind(e),e.onCompleted.bind(e))})},_e.materialize=function(){var t=this;return new Ge(function(e){return t.subscribe(function(t){e.onNext(me(t))},function(t){e.onNext(ye(t)),e.onCompleted()},function(){e.onNext(we()),e.onCompleted()})})},_e.repeat=function(t){return Ce(this,t).concat()},_e.retry=function(t){return Ce(this,t).catchException()},_e.scan=function(){var t,e,n=!1;2===arguments.length?(t=arguments[0],e=arguments[1],n=!0):e=arguments[0];var r=this;return Te(function(){var i,o=!1;return r.select(function(r){return o?i=e(i,r):(i=n?e(t,r):r,o=!0),i})})},_e.skipLast=function(t){var e=this;return new Ge(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&n.onNext(r.shift())},n.onError.bind(n),n.onCompleted.bind(n))})},_e.startWith=function(){var t,e,n=0;return arguments.length&&"now"in Object(arguments[0])?(e=arguments[0],n=1):e=ae,t=B.call(arguments,n),De([Me(t,e),this]).concat()},_e.takeLast=function(t,e){return this.takeLastBuffer(t).selectMany(function(t){return Me(t,e)})},_e.takeLastBuffer=function(t){var e=this;return new Ge(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},n.onError.bind(n),function(){n.onNext(r),n.onCompleted()})})},_e.windowWithCount=function(t,e){var n=this;if(0>=t)throw Error(S);if(null==e&&(e=t),0>=e)throw Error(S);return new Ge(function(r){var i=new re,o=new se(i),s=0,u=[],c=function(){var t=new Xe;u.push(t),r.onNext(G(t,o))};return c(),i.setDisposable(n.subscribe(function(n){for(var r,i=0,o=u.length;o>i;i++)u[i].onNext(n);var a=s-t+1;a>=0&&0===a%e&&(r=u.shift(),r.onCompleted()),s++,0===s%e&&c()},function(t){for(;u.length>0;)u.shift().onError(t);r.onError(t)},function(){for(;u.length>0;)u.shift().onCompleted();r.onCompleted()})),o})},_e.defaultIfEmpty=function(t){var n=this;return t===e&&(t=null),new Ge(function(e){var r=!1;return n.subscribe(function(t){r=!0,e.onNext(t)},e.onError.bind(e),function(){r||e.onNext(t),e.onCompleted()})})},_e.distinct=function(t,n){var i=this;return t||(t=r),n||(n=u),new Ge(function(r){var o={};return i.subscribe(function(i){var s,u,c,a=!1;try{s=t(i),u=n(s)}catch(h){return r.onError(h),e}for(c in o)if(u===c){a=!0;break}a||(o[u]=null,r.onNext(i))},r.onError.bind(r),r.onCompleted.bind(r))})},_e.groupBy=function(t,e,n){return this.groupByUntil(t,e,function(){return Pe()},n)},_e.groupByUntil=function(t,i,o,s){var c=this;return i||(i=r),s||(s=u),new Ge(function(r){var u={},a=new Z,h=new se(a);return a.add(c.subscribe(function(c){var l,f,p,d,b,v,m,y,w,g;try{v=t(c),m=s(v)}catch(E){for(g in u)u[g].onError(E);return r.onError(E),e}d=!1;try{w=u[m],w||(w=new Xe,u[m]=w,d=!0)}catch(E){for(g in u)u[g].onError(E);return r.onError(E),e}if(d){b=new Ke(v,w,h),f=new Ke(v,w);try{l=o(f)}catch(E){for(g in u)u[g].onError(E);return r.onError(E),e}r.onNext(b),y=new re,a.add(y);var x=function(){m in u&&(delete u[m],w.onCompleted()),a.remove(y)};y.setDisposable(l.take(1).subscribe(n,function(t){for(g in u)u[g].onError(t);r.onError(t)},function(){x()}))}try{p=i(c)}catch(E){for(g in u)u[g].onError(E);return r.onError(E),e}w.onNext(p)},function(t){for(var e in u)u[e].onError(t);r.onError(t)},function(){for(var t in u)u[t].onCompleted();r.onCompleted()})),h})},_e.select=_e.map=function(t,n){var r=this;return new Ge(function(i){var o=0;return r.subscribe(function(s){var u;try{u=t.call(n,s,o++,r)}catch(c){return i.onError(c),e}i.onNext(u)},i.onError.bind(i),i.onCompleted.bind(i))})},_e.pluck=function(t){return this.select(function(e){return e[t]})},_e.selectMany=_e.flatMap=function(t,e){return e?this.selectMany(function(n){return t(n).select(function(t){return e(n,t)})}):"function"==typeof t?g.call(this,t):g.call(this,function(){return t})},_e.selectManyLatest=_e.flatMapLatest=function(t,e){return this.selectMany(t,e).switchLatest()},_e.skip=function(t){if(0>t)throw Error(S);var e=this;return new Ge(function(n){var r=t;return e.subscribe(function(t){0>=r?n.onNext(t):r--},n.onError.bind(n),n.onCompleted.bind(n))})},_e.skipWhile=function(t,n){var r=this;return new Ge(function(i){var o=0,s=!1;return r.subscribe(function(u){if(!s)try{s=!t.call(n,u,o++,r)}catch(c){return i.onError(c),e}s&&i.onNext(u)},i.onError.bind(i),i.onCompleted.bind(i))})},_e.take=function(t,e){if(0>t)throw Error(S);if(0===t)return Ie(e);var n=this;return new Ge(function(e){var r=t;return n.subscribe(function(t){r>0&&(r--,e.onNext(t),0===r&&e.onCompleted())},e.onError.bind(e),e.onCompleted.bind(e))})},_e.takeWhile=function(t,n){var r=this;return new Ge(function(i){var o=0,s=!0;return r.subscribe(function(u){if(s){try{s=t.call(n,u,o++,r)}catch(c){return i.onError(c),e}s?i.onNext(u):i.onCompleted()}},i.onError.bind(i),i.onCompleted.bind(i))})},_e.where=_e.filter=function(t,n){var r=this;return new Ge(function(i){var o=0;return r.subscribe(function(s){var u;try{u=t.call(n,s,o++,r)}catch(c){return i.onError(c),e}u&&i.onNext(s)},i.onError.bind(i),i.onCompleted.bind(i))})};var Ge=D.Internals.AnonymousObservable=function(t){function n(r){function i(t){var e=new Je(t);if(he.scheduleRequired())he.schedule(function(){try{e.disposable(r(e))}catch(t){if(!e.fail(t))throw t}});else try{e.disposable(r(e))}catch(n){if(!e.fail(n))throw n}return e}return this instanceof n?(t.call(this,i),e):new n(r)}return H(n,t),n}(je),Je=function(t){function e(e){t.call(this),this.observer=e,this.m=new re}H(e,t);var n=e.prototype;return n.next=function(t){var e=!1;try{this.observer.onNext(t),e=!0}catch(n){throw n}finally{e||this.dispose()}},n.error=function(t){try{this.observer.onError(t)}catch(e){throw e}finally{this.dispose()}},n.completed=function(){try{this.observer.onCompleted()}catch(t){throw t}finally{this.dispose()}},n.disposable=function(t){return this.m.disposable(t)},n.dispose=function(){t.prototype.dispose.call(this),this.m.dispose()},e}(Ne),Ke=function(t){function e(t){return this.underlyingObservable.subscribe(t)}function n(n,r,i){t.call(this,e),this.key=n,this.underlyingObservable=i?new Ge(function(t){return new Z(i.getDisposable(),r.subscribe(t))}):r}return H(n,t),n}(je),Qe=function(t,e){this.subject=t,this.observer=e};Qe.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}};var Xe=D.Subject=function(t){function e(t){return a.call(this),this.isStopped?this.exception?(t.onError(this.exception),ne):(t.onCompleted(),ne):(this.observers.push(t),new Qe(this,t))}function n(){t.call(this,e),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return H(n,t),U(n.prototype,Ae,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(a.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var e=0,n=t.length;n>e;e++)t[e].onCompleted();this.observers=[]}},onError:function(t){if(a.call(this),!this.isStopped){var e=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var n=0,r=e.length;r>n;n++)e[n].onError(t);this.observers=[]}},onNext:function(t){if(a.call(this),!this.isStopped)for(var e=this.observers.slice(0),n=0,r=e.length;r>n;n++)e[n].onNext(t)},dispose:function(){this.isDisposed=!0,this.observers=null}}),n.create=function(t,e){return new Ze(t,e)},n}(je),Ye=D.AsyncSubject=function(t){function e(t){if(a.call(this),!this.isStopped)return this.observers.push(t),new Qe(this,t);var e=this.exception,n=this.hasValue,r=this.value;return e?t.onError(e):n?(t.onNext(r),t.onCompleted()):t.onCompleted(),ne}function n(){t.call(this,e),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return H(n,t),U(n.prototype,Ae,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){var t,e,n;if(a.call(this),!this.isStopped){var r=this.observers.slice(0);this.isStopped=!0;var i=this.value,o=this.hasValue;if(o)for(e=0,n=r.length;n>e;e++)t=r[e],t.onNext(i),t.onCompleted();else for(e=0,n=r.length;n>e;e++)r[e].onCompleted();this.observers=[]}},onError:function(t){if(a.call(this),!this.isStopped){var e=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var n=0,r=e.length;r>n;n++)e[n].onError(t);this.observers=[]}},onNext:function(t){a.call(this),this.isStopped||(this.value=t,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),n}(je),Ze=function(t){function e(t){return this.observable.subscribe(t)}function n(n,r){t.call(this,e),this.observer=n,this.observable=r}return H(n,t),U(n.prototype,Ae,{onCompleted:function(){this.observer.onCompleted()},onError:function(t){this.observer.onError(t)},onNext:function(t){this.observer.onNext(t)}}),n}(je);return"function"==typeof define&&"object"==typeof define.amd&&define.amd?(t.Rx=D,define(function(){return D})):(E?"object"==typeof module&&module&&module.exports==E?module.exports=D:E=D:t.Rx=D,e)})(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.1.18/rx.modern.js b/ajax/libs/rxjs/2.1.18/rx.modern.js new file mode 100644 index 000000000..b72b33984 --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.modern.js @@ -0,0 +1,4936 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +(function (window, undefined) { + + var freeExports = typeof exports == 'object' && exports, + freeModule = typeof module == 'object' && module && module.exports == freeExports && module, + freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal) { + window = freeGlobal; + } + + /** + * @name Rx + * @type Object + */ + var Rx = { Internals: {} }; + + // Defaults + function noop() { } + function identity(x) { return x; } + function defaultNow() { return new Date().getTime(); } + function defaultComparer(x, y) { return isEqual(x, y); } + function defaultSubComparer(x, y) { return x - y; } + function defaultKeySerializer(x) { return x.toString(); } + function defaultError(err) { throw err; } + + // 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); + } + } + + /** Used to determine if values are of the language type Object */ + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + /** `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 = 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. + * + * @memberOf 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. + * + * @memberOf CompositeDisposable# + */ + 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. + * + * @memberOf 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. + * + * @memberOf CompositeDisposable# + * @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 + * + * @memberOf CompositeDisposable# + * @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. + * + * @memberOf Disposable# + */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * + * @static + * @memberOf Disposable + * @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. + * + * @static + * @memberOf Disposable + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + /** + * 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. + * + * @constructor + */ + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () { + this.isDisposed = false; + this.current = null; + }; + + var SingleAssignmentDisposablePrototype = SingleAssignmentDisposable.prototype; + + /** + * Gets or sets the underlying disposable. After disposal, the result of getting this method is undefined. + * + * @memberOf SingleAssignmentDisposable# + * @param {Disposable} [value] The new underlying disposable. + * @returns {Disposable} The underlying disposable. + */ + SingleAssignmentDisposablePrototype.disposable = function (value) { + return !value ? this.getDisposable() : this.setDisposable(value); + }; + + /** + * Gets the underlying disposable. After disposal, the result of getting this method is undefined. + * + * @memberOf SingleAssignmentDisposable# + * @returns {Disposable} The underlying disposable. + */ + SingleAssignmentDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * + * @memberOf SingleAssignmentDisposable# + * @param {Disposable} value The new underlying disposable. + */ + SingleAssignmentDisposablePrototype.setDisposable = function (value) { + if (this.current) { + throw new Error('Disposable has already been assigned'); + } + var shouldDispose = this.isDisposed; + if (!shouldDispose) { + this.current = value; + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable. + * + * @memberOf SingleAssignmentDisposable# + */ + SingleAssignmentDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + /** + * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. + * + * @constructor + */ + var SerialDisposable = Rx.SerialDisposable = function () { + this.isDisposed = false; + this.current = null; + }; + + /** + * Gets the underlying disposable. + * @return The underlying disposable + */ + SerialDisposable.prototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * + * @memberOf SerialDisposable# + * @param {Disposable} value The new underlying disposable. + */ + SerialDisposable.prototype.setDisposable = function (value) { + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + if (old) { + old.dispose(); + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Gets or sets the underlying disposable. + * If the SerialDisposable has already been disposed, assignment to this property causes immediate disposal of the given disposable object. Assigning this property disposes the previous disposable object. + * + * @memberOf SerialDisposable# + * @param {Disposable} [value] The new underlying disposable. + * @returns {Disposable} The underlying disposable. + */ + SerialDisposable.prototype.disposable = function (value) { + if (!value) { + return this.getDisposable(); + } else { + this.setDisposable(value); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + * + * @memberOf SerialDisposable# + */ + SerialDisposable.prototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + /** + * @constructor + * @private + */ + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + /** @private */ + 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 + * + * @memberOf RefCountDisposable# + */ + 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. + * + * @memberOf RefCountDisposable# + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.H + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + /** + * @constructor + * @private + */ + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler, this.disposable = disposable, this.isDisposed = false; + } + + /** + * @private + * @memberOf ScheduledDisposable# + */ + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + /** + * @private + * @constructor + */ + function ScheduledItem(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(); + } + + /** + * @private + * @memberOf ScheduledItem# + */ + ScheduledItem.prototype.invoke = function () { + this.disposable.disposable(this.invokeCore()); + }; + + /** + * @private + * @memberOf ScheduledItem# + */ + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + /** + * @private + * @memberOf ScheduledItem# + */ + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + /** + * @private + * @memberOf ScheduledItem# + */ + 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. + * + * @memberOf Scheduler# + * @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 = 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. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler# + * @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 = window.setInterval(function () { + s = action(s); + }, period); + return disposableCreate(function () { + window.clearInterval(id); + }); + }; + + /** + * Schedules an action to be executed. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler# + * @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. + * + * @memberOf Scheduler + * @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. + * + * @memberOf Scheduler + * @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. + * + * @memberOf Scheduler + * @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. + * + * @memberOf Scheduler + * @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. + * + * @static + * @memberOf Scheduler + * @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 schedulerNoBlockError = 'Scheduler is not allowed to block the thread'; + + /** + * Gets a scheduler that schedules work immediately on the current thread. + * + * @memberOf Scheduler + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { + return action(this, state); + } + + function scheduleRelative(state, dueTime, action) { + if (dueTime > 0) throw new Error(schedulerNoBlockError); + 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; + + /** + * @private + * @constructor + */ + function Trampoline() { + queue = new PriorityQueue(4); + } + + /** + * @private + * @memberOf Trampoline + */ + Trampoline.prototype.dispose = function () { + queue = null; + }; + + /** + * @private + * @memberOf Trampoline + */ + Trampoline.prototype.run = function () { + var item; + while (queue.length > 0) { + item = queue.dequeue(); + if (!item.isCancelled()) { + 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), + t; + if (!queue) { + t = new Trampoline(); + try { + queue.enqueue(si); + t.run(); + } catch (e) { + throw e; + } finally { + t.dispose(); + } + } 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 === null; }; + currentScheduler.ensureTrampoline = function (action) { + if (queue === null) { + return this.schedule(action); + } else { + return action(); + } + }; + + return currentScheduler; + }()); + + /** + * @private + */ + var SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + /** + * @constructor + * @private + */ + 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; + }()); + + /** Provides a set of extension methods for virtual time scheduling. */ + Rx.VirtualTimeScheduler = (function (_super) { + + 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; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. + * + * @memberOf VirtualTimeScheduler# + * @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. + * + * @memberOf VirtualTimeScheduler# + * @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. + * + * @memberOf VirtualTimeScheduler# + * @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. + * + * @memberOf VirtualTimeScheduler# + */ + VirtualTimeSchedulerPrototype.start = function () { + var next; + if (!this.isEnabled) { + this.isEnabled = true; + do { + next = this.getNext(); + if (next !== null) { + if (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. + * + * @memberOf VirtualTimeScheduler# + */ + 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 next; + 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 { + next = this.getNext(); + if (next !== null && this.comparer(next.dueTime, time) <= 0) { + if (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. + * + * @memberOf VirtualTimeScheduler# + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.advanceBy = function (time) { + var dt = this.add(this.clock, time); + var dueToClock = this.comparer(this.clock, dt); + if (dueToClock > 0) { + throw new Error(argumentOutOfRange); + } + if (dueToClock === 0) { + return; + } + return this.advanceTo(dt); + }; + + /** + * Advances the scheduler's clock by the specified relative time. + * + * @memberOf VirtualTimeScheduler# + * @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. + * + * @memberOf VirtualTimeScheduler# + * @returns {ScheduledItem} The next scheduled item. + */ + VirtualTimeSchedulerPrototype.getNext = function () { + var next; + while (this.queue.length > 0) { + next = this.queue.peek(); + if (next.isCancelled()) { + this.queue.dequeue(); + } else { + return next; + } + } + return null; + }; + + /** + * Schedules an action to be executed at dueTime. + * + * @memberOf VirtualTimeScheduler# + * @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. + * + * @memberOf VirtualTimeScheduler# + * @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, + run = function (scheduler, state1) { + self.queue.remove(si); + return action(scheduler, state1); + }, + si = new ScheduledItem(self, state, run, dueTime, self.comparer); + self.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. + * + * @memberOf HistoricalScheduler + * @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; + }; + + /** + * @private + * @memberOf HistoricalScheduler + */ + 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 scheduleMethod, clearMethod = noop; + (function () { + function postMessageSupported () { + // Ensure not in a worker + if (!window.postMessage || window.importScripts) { return false; } + var isAsync = false, + oldHandler = window.onmessage; + // Test for async + window.onmessage = function () { isAsync = true; }; + window.postMessage('','*'); + window.onmessage = oldHandler; + + return isAsync; + } + + // Check for setImmediate first for Node v0.11+ + if (typeof window.setImmediate === 'function') { + scheduleMethod = window.setImmediate; + clearMethod = clearImmediate; + } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } 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 (window.addEventListener) { + window.addEventListener('message', onGlobalPostMessage, false); + } else { + window.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + window.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!window.MessageChannel) { + var channel = new window.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 window && 'onreadystatechange' in window.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = window.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + window.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return window.setTimeout(action, 0); }; + clearMethod = window.clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + * + * @memberOf Scheduler + */ + 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 = window.setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + window.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; + } + + var NotificationPrototype = Notification.prototype; + + /** + * 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. + */ + NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { + if (arguments.length === 1 && typeof observerOrOnNext === 'object') { + return this._acceptObservable(observerOrOnNext); + } + return this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notification + * @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. + */ + NotificationPrototype.toObservable = function (scheduler) { + var notification = this; + scheduler = scheduler || immediateScheduler; + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + if (notification.kind === 'N') { + observer.onCompleted(); + } + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * + * @static + * @memberOf Notification + * @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.bind(notification); + notification._acceptObservable = _acceptObservable.bind(notification); + notification.toString = toString.bind(notification); + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * + * @static s + * @memberOf Notification + * @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.bind(notification); + notification._acceptObservable = _acceptObservable.bind(notification); + notification.toString = toString.bind(notification); + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * + * @static + * @memberOf Notification + * @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.bind(notification); + notification._acceptObservable = _acceptObservable.bind(notification); + notification.toString = toString.bind(notification); + return notification; + }; + }()); + + /** + * @constructor + * @private + */ + var Enumerator = Rx.Internals.Enumerator = function (moveNext, getCurrent, dispose) { + this.moveNext = moveNext; + this.getCurrent = getCurrent; + this.dispose = dispose; + }; + + /** + * @static + * @memberOf Enumerator + * @private + */ + var enumeratorCreate = Enumerator.create = function (moveNext, getCurrent, dispose) { + var done = false; + dispose || (dispose = noop); + return new Enumerator(function () { + if (done) { + return false; + } + var result = moveNext(); + if (!result) { + done = true; + dispose(); + } + return result; + }, function () { return getCurrent(); }, function () { + if (!done) { + dispose(); + done = true; + } + }); + }; + + /** @private */ + var Enumerable = Rx.Internals.Enumerable = (function () { + + /** + * @constructor + * @private + */ + function Enumerable(getEnumerator) { + this.getEnumerator = getEnumerator; + } + + /** + * @private + * @memberOf Enumerable# + */ + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e = sources.getEnumerator(), isDisposed = false, subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, ex, hasNext = false; + if (!isDisposed) { + try { + hasNext = e.moveNext(); + if (hasNext) { + current = e.getCurrent(); + } else { + e.dispose(); + } + } catch (exception) { + ex = exception; + e.dispose(); + } + } else { + return; + } + if (ex) { + observer.onError(ex); + return; + } + if (!hasNext) { + observer.onCompleted(); + return; + } + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + e.dispose(); + })); + }); + }; + + /** + * @private + * @memberOf Enumerable# + */ + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e = sources.getEnumerator(), isDisposed = false, lastException; + var subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, ex, hasNext; + hasNext = false; + if (!isDisposed) { + try { + hasNext = e.moveNext(); + if (hasNext) { + current = e.getCurrent(); + } + } catch (exception) { + ex = exception; + } + } else { + return; + } + if (ex) { + observer.onError(ex); + return; + } + if (!hasNext) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + return Enumerable; + }()); + + /** + * @static + * @private + * @memberOf Enumerable + */ + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount === undefined) { + repeatCount = -1; + } + return new Enumerable(function () { + var current, left = repeatCount; + return enumeratorCreate(function () { + if (left === 0) { + return false; + } + if (left > 0) { + left--; + } + current = value; + return true; + }, function () { return current; }); + }); + }; + + /** + * @static + * @private + * @memberOf Enumerable + */ + var enumerableFor = Enumerable.forEach = function (source, selector) { + selector || (selector = identity); + return new Enumerable(function () { + var current, index = -1; + return enumeratorCreate( + function () { + if (++index < source.length) { + current = selector(source[index], index); + return true; + } + return false; + }, + function () { return current; } + ); + }); + }; + + /** + * 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. + * + * @constructor + * @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. + * + * @memberOf AnonymousObserver + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * + * @memberOf AnonymousObserver + * @param {Any{ error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + * + * @memberOf AnonymousObserver + */ + 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)); + + /** @private */ + 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(); + } + + /** @private */ + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + /** @private */ + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + /** @private */ + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + /** @private */ + 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(); + })); + } + }; + + /** @private */ + 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 () { + + /** + * @constructor + * @private + */ + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + 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(); + } + }); + }); + }; + + /** + * 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; + if (typeof observerOrOnNext === 'object') { + subscriber = observerOrOnNext; + } else { + subscriber = observerCreate(observerOrOnNext, onError, onCompleted); + } + + return this._subscribe(subscriber); + }; + + /** + * Creates a list from an observable sequence. + * + * @memberOf Observable + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + function accumulator(list, i) { + var newList = list.slice(0); + newList.push(i); + return newList; + } + return this.scan([], accumulator).startWith([]).finalValue(); + }; + + return Observable; + })(); + + /** + * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. + * + * @example + * 1 - res = Rx.Observable.start(function () { console.log('hello'); }); + * 2 - res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); + * 2 - 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, scheduler, context) { + return observableToAsync(func, scheduler, context)(); + }; + + /** + * 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 + * 1 - res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); + * 2 - res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); + * 2 - 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, scheduler, context) { + 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(); + }; + }; + /** + * 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; + }); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * 1 - res = Rx.Observable.create(function (observer) { return function () { } ); + * + * @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 = function (subscribe) { + return new AnonymousObservable(function (o) { + return disposableCreate(subscribe(o)); + }); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * 1 - res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * @static + * @memberOf Observable + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.createWithDisposable = function (subscribe) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * 1 - res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @static + * @memberOf Observable + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence. + * @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); + } + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * 1 - res = Rx.Observable.empty(); + * 2 - res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @static + * @memberOf Observable + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * 1 - res = Rx.Observable.fromArray([1,2,3]); + * 2 - res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @static + * @memberOf Observable + * @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) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0; + return scheduler.scheduleRecursive(function (self) { + if (count < array.length) { + 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 + * 1 - res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); + * 2 - res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); + * @static + * @memberOf Observable + * @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) { + 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). + * + * @static + * @memberOf Observable + * @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 + * 1 - res = Rx.Observable.range(0, 10); + * 2 - res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @static + * @memberOf Observable + * @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) { + 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 + * 1 - res = Rx.Observable.repeat(42); + * 2 - 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); + * @static + * @memberOf Observable + * @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) { + scheduler || (scheduler = currentThreadScheduler); + if (repeatCount == null) { + repeatCount = -1; + } + return observableReturn(value, scheduler).repeat(repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'returnValue' for browsers 0) { + s = q.shift(); + subscribe(s); + } else { + activeCount--; + if (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; + if (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]); + * + * @static + * @memberOf Observable + * @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. + * + * @memberOf Observable# + * @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); + 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. + * + * @memberOf Observable + * @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]); + * @static + * @memberOf Observable + * @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++]; + 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. + * + * @memberOf Observable# + * @param {Observable} other The observable sequence 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) { + if (isOpen) { + observer.onNext(left); + } + }, observer.onError.bind(observer), function () { + if (isOpen) { + observer.onCompleted(); + } + })); + + 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. + * + * @memberOf Observable# + * @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); + 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. + * + * @memberOf Observable# + * @param {Observable} other Observable sequence 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) { + 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); + * @memberOf Observable# + * @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; }); + + var next = function (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) { + 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); + } + + 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. + * + * @static + * @memberOf Observable + * @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. + * + * @static + * @memberOf Observable + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = slice.call(arguments); + 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 + * 1 - xs.bufferWithCount(10); + * 2 - xs.bufferWithCount(10, 1); + * + * @memberOf Observable# + * @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 (skip === undefined) { + 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. + * + * @memberOf Observable# + * @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. + * + * 1 - var obs = observable.distinctUntilChanged(); + * 2 - var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * 3 - var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @memberOf Observable# + * @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 + * 1 - observable.doAction(observer); + * 2 - observable.doAction(onNext); + * 3 - observable.doAction(onNext, onError); + * 4 - observable.doAction(onNext, onError, onCompleted); + * + * @memberOf Observable# + * @param {Mixed} 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 = 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 (exception) { + if (!onError) { + observer.onError(exception); + } else { + try { + onError(exception); + } catch (e) { + observer.onError(e); + } + observer.onError(exception); + } + }, 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 + * 1 - obs = observable.finallyAction(function () { console.log('sequence ended'; }); + * + * @memberOf Observable# + * @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 = source.subscribe(observer); + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * + * @memberOf Observable# + * @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. + * + * @memberOf Observable# + * @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 (exception) { + observer.onNext(notificationCreateOnError(exception)); + 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 + * 1 - repeated = source.repeat(); + * 2 - repeated = source.repeat(42); + * + * @memberOf Observable# + * @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. + * + * @example + * 1 - retried = retry.repeat(); + * 2 - retried = retry.repeat(42); + * + * @memberOf Observable# + * @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. + * + * 1 - scanned = source.scan(function (acc, x) { return acc + x; }); + * 2 - scanned = source.scan(0, function (acc, x) { return acc + x; }); + * + * @memberOf Observable# + * @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 seed, hasSeed = false, accumulator; + if (arguments.length === 2) { + seed = arguments[0]; + accumulator = arguments[1]; + hasSeed = true; + } else { + accumulator = arguments[0]; + } + var source = this; + return observableDefer(function () { + var hasAccumulation = false, accumulation; + return source.select(function (x) { + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + return accumulation; + }); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * + * @memberOf Observable# + * @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. + * + * 1 - source.startWith(1, 2, 3); + * 2 - 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, using an optional scheduler to drain the queue. + * + * @example + * 1 - obs = source.takeLast(5); + * 2 - obs = source.takeLast(5, Rx.Scheduler.timeout); + * + * @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. + * + * @memberOf Observable# + * @param {Number} count Number of elements to take from the end of the source sequence. + * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion 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, scheduler) { + return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); + }; + + /** + * 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. + * + * @memberOf Observable# + * @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); + if (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. + * + * 1 - xs.windowWithCount(10); + * 2 - xs.windowWithCount(10, 1); + * + * @memberOf Observable# + * @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 (skip == null) { + 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 the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * 1 - 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(); + }); + }); + }; + + /** + * 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 + * 1 - obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); + * + * @memberOf Observable# + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, keySerializer) { + var source = this; + keySelector || (keySelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var hashSet = {}; + return source.subscribe(function (x) { + var key, serializedKey, otherKey, hasMatch = false; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (exception) { + observer.onError(exception); + return; + } + for (otherKey in hashSet) { + if (serializedKey === otherKey) { + hasMatch = true; + break; + } + } + if (!hasMatch) { + hashSet[serializedKey] = null; + 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 + * 1 - 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(); }); + * + * @memberOf Observable# + * @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} [keySerializer] Used to serialize the given object into a string for object comparison. + * @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, keySerializer) { + return this.groupByUntil(keySelector, elementSelector, function () { + return observableNever(); + }, keySerializer); + }; + + /** + * 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 + * 1 - 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(); }); + * + * @memberOf Observable# + * @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} [keySerializer] Used to serialize the given object into a string for object comparison. + * @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, keySerializer) { + var source = this; + elementSelector || (elementSelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var map = {}, + groupDisposable = new CompositeDisposable(), + refCountDisposable = new RefCountDisposable(groupDisposable); + groupDisposable.add(source.subscribe(function (x) { + var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + fireNewMapEntry = false; + try { + writer = map[serializedKey]; + if (!writer) { + writer = new Subject(); + map[serializedKey] = writer; + fireNewMapEntry = true; + } + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + if (fireNewMapEntry) { + group = new GroupedObservable(key, writer, refCountDisposable); + durationGroup = new GroupedObservable(key, writer); + try { + duration = durationSelector(durationGroup); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + observer.onNext(group); + md = new SingleAssignmentDisposable(); + groupDisposable.add(md); + var expire = function () { + if (serializedKey in map) { + delete map[serializedKey]; + writer.onCompleted(); + } + groupDisposable.remove(md); + }; + md.setDisposable(duration.take(1).subscribe(noop, function (exn) { + for (w in map) { + map[w].onError(exn); + } + observer.onError(exn); + }, function () { + expire(); + })); + } + try { + element = elementSelector(x); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + writer.onNext(element); + }, function (ex) { + for (var w in map) { + map[w].onError(ex); + } + observer.onError(ex); + }, function () { + for (var w in map) { + map[w].onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * + * @memberOf Observable# + * @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. + * + * @memberOf Observable# + * @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 selectMany(selector) { + return this.select(selector).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 + * 1 - 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. + * + * 1 - 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. + * + * 1 - source.selectMany(Rx.Observable.fromArray([1,2,3])); + * + * @memberOf Observable# + * @param selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto. + * @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.selectMany = observableProto.flatMap = function (selector, resultSelector) { + if (resultSelector) { + return this.selectMany(function (x) { + return selector(x).select(function (y) { + return resultSelector(x, y); + }); + }); + } + if (typeof selector === 'function') { + return selectMany.call(this, selector); + } + return selectMany.call(this, function () { + return selector; + }); + }; + + /** + * 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 and + * then transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * + * @example + * 1 - 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 + * and then transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * + * 1 - 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. + * and then transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * + * 1 - 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. + * @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 that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectManyLatest = observableProto.flatMapLatest = function (selector, resultSelector) { + return this.selectMany(selector, resultSelector).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * + * @memberOf Observable# + * @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. + * + * 1 - source.skipWhile(function (value) { return value < 10; }); + * 1 - source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * + * @memberOf Observable# + * @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). + * + * 1 - source.take(5); + * 2 - source.take(0, Rx.Scheduler.timeout); + * + * @memberOf Observable# + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case -1;return n.pop(),r.pop(),i}function d(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:F.call(t)}function b(t,e){for(var n=Array(t),r=0;t>r;r++)n[r]=e();return n}function v(t,e){this.scheduler=t,this.disposable=e,this.isDisposed=!1}function m(t,e,n,r,i){this.scheduler=t,this.state=e,this.action=n,this.dueTime=r,this.comparer=i||s,this.disposable=new ee}function y(t,n){return new He(function(r){var i=new ee,o=new re;return o.setDisposable(i),i.setDisposable(t.subscribe(r.onNext.bind(r),function(t){var i,s;try{s=n(t)}catch(u){return r.onError(u),e}i=new ee,o.setDisposable(i),i.setDisposable(s.subscribe(r))},r.onCompleted.bind(r))),o})}function w(t,n){var r=this;return new He(function(i){var o=0,s=t.length;return r.subscribe(function(r){if(s>o){var u,c=t[o++];try{u=n(r,c)}catch(a){return i.onError(a),e}i.onNext(u)}else i.onCompleted()},i.onError.bind(i),i.onCompleted.bind(i))})}function g(t){return this.select(t).mergeObservable()}var E="object"==typeof exports&&exports,x=("object"==typeof module&&module&&module.exports==E&&module,"object"==typeof global&&global);x.global===x&&(t=x);var C,D={Internals:{}},A="Sequence contains no elements.",S="Argument out of range",_="Object has been disposed",N={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},O="[object Arguments]",R="[object Array]",W="[object Boolean]",k="[object Date]",j="[object Function]",q="[object Number]",T="[object Object]",I="[object RegExp]",M="[object String]",P=Object.prototype.toString,L=Object.prototype.hasOwnProperty,V=P.call(arguments)==O;try{C=!(P.call(document)==T&&!({toString:0}+""))}catch(z){C=!0}V||(l=function(t){return t&&"object"==typeof t?L.call(t,"callee"):!1}),f(/x/)&&(f=function(t){return"function"==typeof t&&P.call(t)==j});var B=D.Internals.isEqual=function(t,e){return p(t,e,[],[])},F=Array.prototype.slice;({}).hasOwnProperty;var H=this.inherits=D.Internals.inherits=function(t,e){function n(){this.constructor=t}n.prototype=e.prototype,t.prototype=new n},U=D.Internals.addProperties=function(t){for(var e=F.call(arguments,1),n=0,r=e.length;r>n;n++){var i=e[n];for(var o in i)t[o]=i[o]}},G=D.Internals.addRef=function(t,e){return new He(function(n){return new X(e.getDisposable(),t.subscribe(n))})},J=function(t,e){this.id=t,this.value=e};J.prototype.compareTo=function(t){var e=this.value.compareTo(t.value);return 0===e&&(e=this.id-t.id),e};var K=function(t){this.items=Array(t),this.length=0},Q=K.prototype;Q.isHigherPriority=function(t,e){return 0>this.items[t].compareTo(this.items[e])},Q.percolate=function(t){if(!(t>=this.length||0>t)){var e=t-1>>1;if(!(0>e||e===t)&&this.isHigherPriority(t,e)){var n=this.items[t];this.items[t]=this.items[e],this.items[e]=n,this.percolate(e)}}},Q.heapify=function(t){if(t===e&&(t=0),!(t>=this.length||0>t)){var n=2*t+1,r=2*t+2,i=t;if(this.length>n&&this.isHigherPriority(n,i)&&(i=n),this.length>r&&this.isHigherPriority(r,i)&&(i=r),i!==t){var o=this.items[t];this.items[t]=this.items[i],this.items[i]=o,this.heapify(i)}}},Q.peek=function(){return this.items[0].value},Q.removeAt=function(t){this.items[t]=this.items[--this.length],delete this.items[this.length],this.heapify()},Q.dequeue=function(){var t=this.peek();return this.removeAt(0),t},Q.enqueue=function(t){var e=this.length++;this.items[e]=new J(K.count++,t),this.percolate(e)},Q.remove=function(t){for(var e=0;this.length>e;e++)if(this.items[e].value===t)return this.removeAt(e),!0;return!1},K.count=0;var X=D.CompositeDisposable=function(){this.disposables=d(arguments,0),this.isDisposed=!1,this.length=this.disposables.length},Y=X.prototype;Y.add=function(t){this.isDisposed?t.dispose():(this.disposables.push(t),this.length++)},Y.remove=function(t){var e=!1;if(!this.isDisposed){var n=this.disposables.indexOf(t);-1!==n&&(e=!0,this.disposables.splice(n,1),this.length--,t.dispose())}return e},Y.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()}},Y.clear=function(){var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()},Y.contains=function(t){return-1!==this.disposables.indexOf(t)},Y.toArray=function(){return this.disposables.slice(0)};var Z=D.Disposable=function(t){this.isDisposed=!1,this.action=t||n};Z.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var $=Z.create=function(t){return new Z(t)},te=Z.empty={dispose:n},ee=D.SingleAssignmentDisposable=function(){this.isDisposed=!1,this.current=null},ne=ee.prototype;ne.disposable=function(t){return t?this.setDisposable(t):this.getDisposable()},ne.getDisposable=function(){return this.current},ne.setDisposable=function(t){if(this.current)throw Error("Disposable has already been assigned");var e=this.isDisposed;e||(this.current=t),e&&t&&t.dispose()},ne.dispose=function(){var t;this.isDisposed||(this.isDisposed=!0,t=this.current,this.current=null),t&&t.dispose()};var re=D.SerialDisposable=function(){this.isDisposed=!1,this.current=null};re.prototype.getDisposable=function(){return this.current},re.prototype.setDisposable=function(t){var e,n=this.isDisposed;n||(e=this.current,this.current=t),e&&e.dispose(),n&&t&&t.dispose()},re.prototype.disposable=function(t){return t?(this.setDisposable(t),e):this.getDisposable()},re.prototype.dispose=function(){var t;this.isDisposed||(this.isDisposed=!0,t=this.current,this.current=null),t&&t.dispose()};var ie=D.RefCountDisposable=function(){function t(t){this.disposable=t,this.disposable.count++,this.isInnerDisposed=!1}function e(t){this.underlyingDisposable=t,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return t.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()))},e.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},e.prototype.getDisposable=function(){return this.isDisposed?te:new t(this)},e}();v.prototype.dispose=function(){var t=this;this.scheduler.schedule(function(){t.isDisposed||(t.isDisposed=!0,t.disposable.dispose())})},m.prototype.invoke=function(){this.disposable.disposable(this.invokeCore())},m.prototype.compareTo=function(t){return this.comparer(this.dueTime,t.dueTime)},m.prototype.isCancelled=function(){return this.disposable.isDisposed},m.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var oe=D.Scheduler=function(){function e(t,e,n,r){this.now=t,this._schedule=e,this._scheduleRelative=n,this._scheduleAbsolute=r}function n(t,e){var n=e.first,r=e.second,i=new X,o=function(e){r(e,function(e){var n=!1,r=!1,s=t.scheduleWithState(e,function(t,e){return n?i.remove(s):r=!0,o(e),te});r||(i.add(s),n=!0)})};return o(n),i}function r(t,e,n){var r=e.first,i=e.second,o=new X,s=function(e){i(e,function(e,r){var i=!1,u=!1,c=t[n].call(t,e,r,function(t,e){return i?o.remove(c):u=!0,s(e),te});u||(o.add(c),i=!0)})};return s(r),o}function o(t,e){return e(),te}var s=e.prototype;return s.catchException=function(t){return new pe(this,t)},s.schedulePeriodic=function(t,e){return this.schedulePeriodicWithState(null,t,function(){e()})},s.schedulePeriodicWithState=function(e,n,r){var i=e,o=t.setInterval(function(){i=r(i)},n);return $(function(){t.clearInterval(o)})},s.schedule=function(t){return this._schedule(t,o)},s.scheduleWithState=function(t,e){return this._schedule(t,e)},s.scheduleWithRelative=function(t,e){return this._scheduleRelative(e,t,o)},s.scheduleWithRelativeAndState=function(t,e,n){return this._scheduleRelative(t,e,n)},s.scheduleWithAbsolute=function(t,e){return this._scheduleAbsolute(e,t,o)},s.scheduleWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute(t,e,n)},s.scheduleRecursive=function(t){return this.scheduleRecursiveWithState(t,function(t,e){t(function(){e(t)})})},s.scheduleRecursiveWithState=function(t,e){return this.scheduleWithState({first:t,second:e},function(t,e){return n(t,e)})},s.scheduleRecursiveWithRelative=function(t,e){return this.scheduleRecursiveWithRelativeAndState(e,t,function(t,e){t(function(n){e(t,n)})})},s.scheduleRecursiveWithRelativeAndState=function(t,e,n){return this._scheduleRelative({first:t,second:n},e,function(t,e){return r(t,e,"scheduleWithRelativeAndState")})},s.scheduleRecursiveWithAbsolute=function(t,e){return this.scheduleRecursiveWithAbsoluteAndState(e,t,function(t,e){t(function(n){e(t,n)})})},s.scheduleRecursiveWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute({first:t,second:n},e,function(t,e){return r(t,e,"scheduleWithAbsoluteAndState")})},e.now=i,e.normalize=function(t){return 0>t&&(t=0),t},e}(),se="Scheduler is not allowed to block the thread",ue=oe.immediate=function(){function t(t,e){return e(this,t)}function e(t,e,n){if(e>0)throw Error(se);return n(this,t)}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new oe(i,t,e,n)}(),ce=oe.currentThread=function(){function t(){o=new K(4)}function e(t,e){return this.scheduleWithRelativeAndState(t,0,e)}function n(e,n,r){var i,s=this.now()+oe.normalize(n),u=new m(this,e,r,s);if(o)o.enqueue(u);else{i=new t;try{o.enqueue(u),i.run()}catch(c){throw c}finally{i.dispose()}}return u.disposable}function r(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}var o;t.prototype.dispose=function(){o=null},t.prototype.run=function(){for(var t;o.length>0;)if(t=o.dequeue(),!t.isCancelled()){for(;t.dueTime-oe.now()>0;);t.isCancelled()||t.invoke()}};var s=new oe(i,e,n,r);return s.scheduleRequired=function(){return null===o},s.ensureTrampoline=function(t){return null===o?this.schedule(t):t()},s}(),ae=function(){function t(t,e){e(0,this._period);try{this._state=this._action(this._state)}catch(n){throw this._cancel.dispose(),n}}function e(t,e,n,r){this._scheduler=t,this._state=e,this._period=n,this._action=r}return e.prototype.start=function(){var e=new ee;return this._cancel=e,e.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,t.bind(this))),e},e}();D.VirtualTimeScheduler=function(t){function n(){return this.toDateTimeOffset(this.clock)}function r(t,e){return this.scheduleAbsoluteWithState(t,this.clock,e)}function i(t,e,n){return this.scheduleRelativeWithState(t,this.toRelative(e),n)}function o(t,e,n){return this.scheduleRelativeWithState(t,this.toRelative(e-this.now()),n)}function s(t,e){return e(),te}function u(e,s){this.clock=e,this.comparer=s,this.isEnabled=!1,this.queue=new K(1024),t.call(this,n,r,i,o)}H(u,t);var c=u.prototype;return c.schedulePeriodicWithState=function(t,e,n){var r=new ae(this,t,e,n);return r.start()},c.scheduleRelativeWithState=function(t,e,n){var r=this.add(this.clock,e);return this.scheduleAbsoluteWithState(t,r,n)},c.scheduleRelative=function(t,e){return this.scheduleRelativeWithState(e,t,s)},c.start=function(){var t;if(!this.isEnabled){this.isEnabled=!0;do t=this.getNext(),null!==t?(this.comparer(t.dueTime,this.clock)>0&&(this.clock=t.dueTime),t.invoke()):this.isEnabled=!1;while(this.isEnabled)}},c.stop=function(){this.isEnabled=!1},c.advanceTo=function(t){var e,n=this.comparer(this.clock,t);if(this.comparer(this.clock,t)>0)throw Error(S);if(0!==n&&!this.isEnabled){this.isEnabled=!0;do e=this.getNext(),null!==e&&0>=this.comparer(e.dueTime,t)?(this.comparer(e.dueTime,this.clock)>0&&(this.clock=e.dueTime),e.invoke()):this.isEnabled=!1;while(this.isEnabled);this.clock=t}},c.advanceBy=function(t){var n=this.add(this.clock,t),r=this.comparer(this.clock,n);if(r>0)throw Error(S);return 0!==r?this.advanceTo(n):e},c.sleep=function(t){var e=this.add(this.clock,t);if(this.comparer(this.clock,e)>=0)throw Error(S);this.clock=e},c.getNext=function(){for(var t;this.queue.length>0;){if(t=this.queue.peek(),!t.isCancelled())return t;this.queue.dequeue()}return null},c.scheduleAbsolute=function(t,e){return this.scheduleAbsoluteWithState(e,t,s)},c.scheduleAbsoluteWithState=function(t,e,n){var r=this,i=function(t,e){return r.queue.remove(o),n(t,e)},o=new m(r,t,i,e,r.comparer);return r.queue.enqueue(o),o.disposable},u}(oe),D.HistoricalScheduler=function(t){function e(e,n){var r=null==e?0:e,i=n||s;t.call(this,r,i)}H(e,t);var n=e.prototype;return n.add=function(t,e){return t+e},n.toDateTimeOffset=function(t){return new Date(t).getTime()},n.toRelative=function(t){return t},e}(D.VirtualTimeScheduler);var he,le=n;(function(){function e(){if(!t.postMessage||t.importScripts)return!1;var e=!1,n=t.onmessage;return t.onmessage=function(){e=!0},t.postMessage("","*"),t.onmessage=n,e}function n(t){if("string"==typeof t.data&&t.data.substring(0,r.length)===r){var e=t.data.substring(r.length),n=i[e];n(),delete i[e]}}if("function"==typeof t.setImmediate)he=t.setImmediate,le=clearImmediate;else if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))he=process.nextTick;else if(e()){var r="ms.rx.schedule"+Math.random(),i={},o=0;t.addEventListener?t.addEventListener("message",n,!1):t.attachEvent("onmessage",n,!1),he=function(e){var n=o++;i[n]=e,t.postMessage(r+n,"*")}}else if(t.MessageChannel){var s=new t.MessageChannel,u={},c=0;s.port1.onmessage=function(t){var e=t.data,n=u[e];n(),delete u[e]},he=function(t){var e=c++;u[e]=t,s.port2.postMessage(e)}}else"document"in t&&"onreadystatechange"in t.document.createElement("script")?he=function(e){var n=t.document.createElement("script");n.onreadystatechange=function(){e(),n.onreadystatechange=null,n.parentNode.removeChild(n),n=null},t.document.documentElement.appendChild(n)}:(he=function(e){return t.setTimeout(e,0)},le=t.clearTimeout)})();var fe=oe.timeout=function(){function e(t,e){var n=this,r=new ee,i=he(function(){r.isDisposed||r.setDisposable(e(n,t))});return new X(r,$(function(){le(i)}))}function n(e,n,r){var i=this,o=oe.normalize(n);if(0===o)return i.scheduleWithState(e,r);var s=new ee,u=t.setTimeout(function(){s.isDisposed||s.setDisposable(r(i,e))},o);return new X(s,$(function(){t.clearTimeout(u)}))}function r(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new oe(i,e,n,r)}(),pe=function(t){function e(){return this._scheduler.now()}function n(t,e){return this._scheduler.scheduleWithState(t,this._wrap(e))}function r(t,e,n){return this._scheduler.scheduleWithRelativeAndState(t,e,this._wrap(n))}function i(t,e,n){return this._scheduler.scheduleWithAbsoluteAndState(t,e,this._wrap(n))}function o(o,s){this._scheduler=o,this._handler=s,this._recursiveOriginal=null,this._recursiveWrapper=null,t.call(this,e,n,r,i)}return H(o,t),o.prototype._clone=function(t){return new o(t,this._handler)},o.prototype._wrap=function(t){var e=this;return function(n,r){try{return t(e._getRecursiveWrapper(n),r)}catch(i){if(!e._handler(i))throw i;return te}}},o.prototype._getRecursiveWrapper=function(t){if(this._recursiveOriginal!==t){this._recursiveOriginal=t;var e=this._clone(t);e._recursiveOriginal=t,e._recursiveWrapper=e,this._recursiveWrapper=e}return this._recursiveWrapper},o.prototype.schedulePeriodicWithState=function(t,e,n){var r=this,i=!1,o=new ee;return o.setDisposable(this._scheduler.schedulePeriodicWithState(t,e,function(t){if(i)return null;try{return n(t)}catch(e){if(i=!0,!r._handler(e))throw e;return o.dispose(),null}})),o},o}(oe),de=D.Notification=function(){function t(t,e){this.hasValue=null==e?!1:e,this.kind=t}var e=t.prototype;return e.accept=function(t,e,n){return 1===arguments.length&&"object"==typeof t?this._acceptObservable(t):this._accept(t,e,n)},e.toObservable=function(t){var e=this;return t=t||ue,new He(function(n){return t.schedule(function(){e._acceptObservable(n),"N"===e.kind&&n.onCompleted()})})},t}(),be=de.createOnNext=function(){function t(t){return t(this.value)}function e(t){return t.onNext(this.value)}function n(){return"OnNext("+this.value+")"}return function(r){var i=new de("N",!0);return i.value=r,i._accept=t.bind(i),i._acceptObservable=e.bind(i),i.toString=n.bind(i),i}}(),ve=de.createOnError=function(){function t(t,e){return e(this.exception)}function e(t){return t.onError(this.exception)}function n(){return"OnError("+this.exception+")"}return function(r){var i=new de("E");return i.exception=r,i._accept=t.bind(i),i._acceptObservable=e.bind(i),i.toString=n.bind(i),i}}(),me=de.createOnCompleted=function(){function t(t,e,n){return n()}function e(t){return t.onCompleted()}function n(){return"OnCompleted()"}return function(){var r=new de("C");return r._accept=t.bind(r),r._acceptObservable=e.bind(r),r.toString=n.bind(r),r}}(),ye=D.Internals.Enumerator=function(t,e,n){this.moveNext=t,this.getCurrent=e,this.dispose=n},we=ye.create=function(t,e,r){var i=!1;return r||(r=n),new ye(function(){if(i)return!1;var e=t();return e||(i=!0,r()),e},function(){return e()},function(){i||(r(),i=!0)})},ge=D.Internals.Enumerable=function(){function t(t){this.getEnumerator=t}return t.prototype.concat=function(){var t=this;return new He(function(n){var r=t.getEnumerator(),i=!1,o=new re,s=ue.scheduleRecursive(function(t){var s,u,c=!1;if(!i){try{c=r.moveNext(),c?s=r.getCurrent():r.dispose()}catch(a){u=a,r.dispose()}if(u)return n.onError(u),e;if(!c)return n.onCompleted(),e;var h=new ee;o.setDisposable(h),h.setDisposable(s.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){t()}))}});return new X(o,s,$(function(){i=!0,r.dispose()}))})},t.prototype.catchException=function(){var t=this;return new He(function(n){var r,i=t.getEnumerator(),o=!1,s=new re,u=ue.scheduleRecursive(function(t){var u,c,a;if(a=!1,!o){try{a=i.moveNext(),a&&(u=i.getCurrent())}catch(h){c=h}if(c)return n.onError(c),e;if(!a)return r?n.onError(r):n.onCompleted(),e;var l=new ee;s.setDisposable(l),l.setDisposable(u.subscribe(n.onNext.bind(n),function(e){r=e,t()},n.onCompleted.bind(n)))}});return new X(s,u,$(function(){o=!0}))})},t}(),Ee=ge.repeat=function(t,n){return n===e&&(n=-1),new ge(function(){var e,r=n;return we(function(){return 0===r?!1:(r>0&&r--,e=t,!0)},function(){return e})})},xe=ge.forEach=function(t,e){return e||(e=r),new ge(function(){var n,r=-1;return we(function(){return++r0&&(t=!this.isAcquired,this.isAcquired=!0),t&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(t){var r;if(!(n.queue.length>0))return n.isAcquired=!1,e;r=n.queue.shift();try{r()}catch(i){throw n.queue=[],n.hasFaulted=!0,i}t()}))},n.prototype.dispose=function(){t.prototype.dispose.call(this),this.disposable.dispose()},n}(Se),Re=function(t){function e(){t.apply(this,arguments)}return H(e,t),e.prototype.next=function(e){t.prototype.next.call(this,e),this.ensureActive()},e.prototype.error=function(e){t.prototype.error.call(this,e),this.ensureActive()},e.prototype.completed=function(){t.prototype.completed.call(this),this.ensureActive()},e}(Oe),We=D.Observable=function(){function t(t){this._subscribe=t}return Ae=t.prototype,Ae.finalValue=function(){var t=this;return new He(function(e){var n,r=!1;return t.subscribe(function(t){r=!0,n=t},e.onError.bind(e),function(){r?(e.onNext(n),e.onCompleted()):e.onError(Error(A))})})},Ae.subscribe=Ae.forEach=function(t,e,n){var r;return r="object"==typeof t?t:De(t,e,n),this._subscribe(r)},Ae.toArray=function(){function t(t,e){var n=t.slice(0);return n.push(e),n}return this.scan([],t).startWith([]).finalValue()},t}();We.start=function(t,e,n){return ke(t,e,n)()};var ke=We.toAsync=function(t,n,r){return n||(n=fe),function(){var i=arguments,o=new Qe;return n.schedule(function(){var n;try{n=t.apply(r,i)}catch(s){return o.onError(s),e}o.onNext(n),o.onCompleted()}),o.asObservable()}};Ae.observeOn=function(t){var e=this;return new He(function(n){return e.subscribe(new Re(t,n))})},Ae.subscribeOn=function(t){var e=this;return new He(function(n){var r=new ee,i=new re;return i.setDisposable(r),r.setDisposable(t.schedule(function(){i.setDisposable(new v(t,e.subscribe(n)))})),i})},We.create=function(t){return new He(function(e){return $(t(e))})},We.createWithDisposable=function(t){return new He(t)};var je=We.defer=function(t){return new He(function(e){var n;try{n=t()}catch(r){return Pe(r).subscribe(e)}return n.subscribe(e)})},qe=We.empty=function(t){return t||(t=ue),new He(function(e){return t.schedule(function(){e.onCompleted()})})},Te=We.fromArray=function(t,e){return e||(e=ce),new He(function(n){var r=0;return e.scheduleRecursive(function(e){t.length>r?(n.onNext(t[r++]),e()):n.onCompleted()})})};We.generate=function(t,n,r,i,o){return o||(o=ce),new He(function(s){var u=!0,c=t;return o.scheduleRecursive(function(t){var o,a;try{u?u=!1:c=r(c),o=n(c),o&&(a=i(c))}catch(h){return s.onError(h),e}o?(s.onNext(a),t()):s.onCompleted()})})};var Ie=We.never=function(){return new He(function(){return te})};We.range=function(t,e,n){return n||(n=ce),new He(function(r){return n.scheduleRecursiveWithState(0,function(n,i){e>n?(r.onNext(t+n),i(n+1)):r.onCompleted()})})},We.repeat=function(t,e,n){return n||(n=ce),null==e&&(e=-1),Me(t,n).repeat(e)};var Me=We["return"]=We.returnValue=function(t,e){return e||(e=ue),new He(function(n){return e.schedule(function(){n.onNext(t),n.onCompleted()})})},Pe=We["throw"]=We.throwException=function(t,e){return e||(e=ue),new He(function(n){return e.schedule(function(){n.onError(t)})})};We.using=function(t,e){return new He(function(n){var r,i,o=te;try{r=t(),r&&(o=r),i=e(r)}catch(s){return new X(Pe(s).subscribe(n),o)}return new X(i.subscribe(n),o)})},Ae.amb=function(t){var e=this;return new He(function(n){function r(){o||(o=s,a.dispose())}function i(){o||(o=u,c.dispose())}var o,s="L",u="R",c=new ee,a=new ee;return c.setDisposable(e.subscribe(function(t){r(),o===s&&n.onNext(t)},function(t){r(),o===s&&n.onError(t)},function(){r(),o===s&&n.onCompleted()})),a.setDisposable(t.subscribe(function(t){i(),o===u&&n.onNext(t)},function(t){i(),o===u&&n.onError(t)},function(){i(),o===u&&n.onCompleted()})),new X(c,a)})},We.amb=function(){function t(t,e){return t.amb(e)}for(var e=Ie(),n=d(arguments,0),r=0,i=n.length;i>r;r++)e=t(e,n[r]);return e},Ae["catch"]=Ae.catchException=function(t){return"function"==typeof t?y(this,t):Le([this,t])};var Le=We.catchException=We["catch"]=function(){var t=d(arguments,0);return xe(t).catchException()};Ae.combineLatest=function(){var t=F.call(arguments);return Array.isArray(t[0])?t[0].unshift(this):t.unshift(this),Ve.apply(this,t)};var Ve=We.combineLatest=function(){var t=F.call(arguments),n=t.pop();return Array.isArray(t[0])&&(t=t[0]),new He(function(r){function i(t){var i;if(c[t]=!0,a||(a=c.every(function(t){return t}))){try{i=n.apply(null,l)}catch(o){return r.onError(o),e}r.onNext(i)}else h.filter(function(e,n){return n!==t}).every(function(t){return t})&&r.onCompleted()}function o(t){h[t]=!0,h.every(function(t){return t})&&r.onCompleted()}for(var s=function(){return!1},u=t.length,c=b(u,s),a=!1,h=b(u,s),l=Array(u),f=Array(u),p=0;u>p;p++)(function(e){f[e]=new ee,f[e].setDisposable(t[e].subscribe(function(t){l[e]=t,i(e)},r.onError.bind(r),function(){o(e)}))})(p);return new X(f)})};Ae.concat=function(){var t=F.call(arguments,0);return t.unshift(this),ze.apply(this,t)};var ze=We.concat=function(){var t=d(arguments,0);return xe(t).concat()};Ae.concatObservable=Ae.concatAll=function(){return this.merge(1)},Ae.merge=function(t){if("number"!=typeof t)return Be(this,t);var e=this;return new He(function(n){var r=0,i=new X,o=!1,s=[],u=function(t){var e=new ee;i.add(e),e.setDisposable(t.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){var t;i.remove(e),s.length>0?(t=s.shift(),u(t)):(r--,o&&0===r&&n.onCompleted())}))};return i.add(e.subscribe(function(e){t>r?(r++,u(e)):s.push(e)},n.onError.bind(n),function(){o=!0,0===r&&n.onCompleted()})),i})};var Be=We.merge=function(){var t,e;return arguments[0]?arguments[0].now?(t=arguments[0],e=F.call(arguments,1)):(t=ue,e=F.call(arguments,0)):(t=ue,e=F.call(arguments,1)),Array.isArray(e[0])&&(e=e[0]),Te(e,t).mergeObservable()};Ae.mergeObservable=Ae.mergeAll=function(){var t=this;return new He(function(e){var n=new X,r=!1,i=new ee;return n.add(i),i.setDisposable(t.subscribe(function(t){var i=new ee;n.add(i),i.setDisposable(t.subscribe(function(t){e.onNext(t)},e.onError.bind(e),function(){n.remove(i),r&&1===n.length&&e.onCompleted()}))},e.onError.bind(e),function(){r=!0,1===n.length&&e.onCompleted()})),n})},Ae.onErrorResumeNext=function(t){if(!t)throw Error("Second observable is required");return Fe([this,t])};var Fe=We.onErrorResumeNext=function(){var t=d(arguments,0);return new He(function(e){var n=0,r=new re,i=ue.scheduleRecursive(function(i){var o,s;t.length>n?(o=t[n++],s=new ee,r.setDisposable(s),s.setDisposable(o.subscribe(e.onNext.bind(e),function(){i()},function(){i()}))):e.onCompleted()});return new X(r,i)})};Ae.skipUntil=function(t){var e=this;return new He(function(n){var r=!1,i=new X(e.subscribe(function(t){r&&n.onNext(t)},n.onError.bind(n),function(){r&&n.onCompleted()})),o=new ee;return i.add(o),o.setDisposable(t.subscribe(function(){r=!0,o.dispose()},n.onError.bind(n),function(){o.dispose()})),i})},Ae["switch"]=Ae.switchLatest=function(){var t=this;return new He(function(e){var n=!1,r=new re,i=!1,o=0,s=t.subscribe(function(t){var s=new ee,u=++o;n=!0,r.setDisposable(s),s.setDisposable(t.subscribe(function(t){o===u&&e.onNext(t)},function(t){o===u&&e.onError(t)},function(){o===u&&(n=!1,i&&e.onCompleted())}))},e.onError.bind(e),function(){i=!0,n||e.onCompleted()});return new X(s,r)})},Ae.takeUntil=function(t){var e=this;return new He(function(r){return new X(e.subscribe(r),t.subscribe(r.onCompleted.bind(r),r.onError.bind(r),n))})},Ae.zip=function(){if(Array.isArray(arguments[0]))return w.apply(this,arguments);var t=this,n=F.call(arguments),i=n.pop();return n.unshift(t),new He(function(o){function s(t){a[t]=!0,a.every(function(t){return t})&&o.onCompleted()}for(var u=n.length,c=b(u,function(){return[]}),a=b(u,function(){return!1}),h=function(n){var s,u;if(c.every(function(t){return t.length>0})){try{u=c.map(function(t){return t.shift()}),s=i.apply(t,u)}catch(h){return o.onError(h),e}o.onNext(s)}else a.filter(function(t,e){return e!==n}).every(r)&&o.onCompleted()},l=Array(u),f=0;u>f;f++)(function(t){l[t]=new ee,l[t].setDisposable(n[t].subscribe(function(e){c[t].push(e),h(t)},o.onError.bind(o),function(){s(t)}))})(f);return new X(l)})},We.zip=function(){var t=F.call(arguments,0),e=t.shift();return e.zip.apply(e,t)},We.zipArray=function(){var t=F.call(arguments);return new He(function(n){function i(t){if(u.every(function(t){return t.length>0})){var i=u.map(function(t){return t.shift()});n.onNext(i)}else if(c.filter(function(e,n){return n!==t}).every(r))return n.onCompleted(),e}function o(t){return c[t]=!0,c.every(r)?(n.onCompleted(),e):e}for(var s=t.length,u=b(s,function(){return[]}),c=b(s,function(){return!1}),a=Array(s),h=0;s>h;h++)(function(e){a[e]=new ee,a[e].setDisposable(t[e].subscribe(function(t){u[e].push(t),i(e)},n.onError.bind(n),function(){o(e)}))})(h);var l=new X(a);return l.add($(function(){for(var t=0,e=u.length;e>t;t++)u[t]=[]})),l})},Ae.asObservable=function(){var t=this;return new He(function(e){return t.subscribe(e)})},Ae.bufferWithCount=function(t,n){return n===e&&(n=t),this.windowWithCount(t,n).selectMany(function(t){return t.toArray()}).where(function(t){return t.length>0})},Ae.dematerialize=function(){var t=this;return new He(function(e){return t.subscribe(function(t){return t.accept(e)},e.onError.bind(e),e.onCompleted.bind(e))})},Ae.distinctUntilChanged=function(t,n){var i=this;return t||(t=r),n||(n=o),new He(function(r){var o,s=!1;return i.subscribe(function(i){var u,c=!1;try{u=t(i)}catch(a){return r.onError(a),e}if(s)try{c=n(o,u)}catch(a){return r.onError(a),e}s&&c||(s=!0,o=u,r.onNext(i))},r.onError.bind(r),r.onCompleted.bind(r))})},Ae["do"]=Ae.doAction=function(t,e,n){var r,i=this;return"function"==typeof t?r=t:(r=t.onNext.bind(t),e=t.onError.bind(t),n=t.onCompleted.bind(t)),new He(function(t){return i.subscribe(function(e){try{r(e)}catch(n){t.onError(n)}t.onNext(e)},function(n){if(e){try{e(n)}catch(r){t.onError(r)}t.onError(n)}else t.onError(n)},function(){if(n){try{n()}catch(e){t.onError(e)}t.onCompleted()}else t.onCompleted()})})},Ae["finally"]=Ae.finallyAction=function(t){var e=this;return new He(function(n){var r=e.subscribe(n); +return $(function(){try{r.dispose()}catch(e){throw e}finally{t()}})})},Ae.ignoreElements=function(){var t=this;return new He(function(e){return t.subscribe(n,e.onError.bind(e),e.onCompleted.bind(e))})},Ae.materialize=function(){var t=this;return new He(function(e){return t.subscribe(function(t){e.onNext(be(t))},function(t){e.onNext(ve(t)),e.onCompleted()},function(){e.onNext(me()),e.onCompleted()})})},Ae.repeat=function(t){return Ee(this,t).concat()},Ae.retry=function(t){return Ee(this,t).catchException()},Ae.scan=function(){var t,e,n=!1;2===arguments.length?(t=arguments[0],e=arguments[1],n=!0):e=arguments[0];var r=this;return je(function(){var i,o=!1;return r.select(function(r){return o?i=e(i,r):(i=n?e(t,r):r,o=!0),i})})},Ae.skipLast=function(t){var e=this;return new He(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&n.onNext(r.shift())},n.onError.bind(n),n.onCompleted.bind(n))})},Ae.startWith=function(){var t,e,n=0;return arguments.length&&"now"in Object(arguments[0])?(e=arguments[0],n=1):e=ue,t=F.call(arguments,n),xe([Te(t,e),this]).concat()},Ae.takeLast=function(t,e){return this.takeLastBuffer(t).selectMany(function(t){return Te(t,e)})},Ae.takeLastBuffer=function(t){var e=this;return new He(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},n.onError.bind(n),function(){n.onNext(r),n.onCompleted()})})},Ae.windowWithCount=function(t,e){var n=this;if(0>=t)throw Error(S);if(null==e&&(e=t),0>=e)throw Error(S);return new He(function(r){var i=new ee,o=new ie(i),s=0,u=[],c=function(){var t=new Ke;u.push(t),r.onNext(G(t,o))};return c(),i.setDisposable(n.subscribe(function(n){for(var r,i=0,o=u.length;o>i;i++)u[i].onNext(n);var a=s-t+1;a>=0&&0===a%e&&(r=u.shift(),r.onCompleted()),s++,0===s%e&&c()},function(t){for(;u.length>0;)u.shift().onError(t);r.onError(t)},function(){for(;u.length>0;)u.shift().onCompleted();r.onCompleted()})),o})},Ae.defaultIfEmpty=function(t){var n=this;return t===e&&(t=null),new He(function(e){var r=!1;return n.subscribe(function(t){r=!0,e.onNext(t)},e.onError.bind(e),function(){r||e.onNext(t),e.onCompleted()})})},Ae.distinct=function(t,n){var i=this;return t||(t=r),n||(n=u),new He(function(r){var o={};return i.subscribe(function(i){var s,u,c,a=!1;try{s=t(i),u=n(s)}catch(h){return r.onError(h),e}for(c in o)if(u===c){a=!0;break}a||(o[u]=null,r.onNext(i))},r.onError.bind(r),r.onCompleted.bind(r))})},Ae.groupBy=function(t,e,n){return this.groupByUntil(t,e,function(){return Ie()},n)},Ae.groupByUntil=function(t,i,o,s){var c=this;return i||(i=r),s||(s=u),new He(function(r){var u={},a=new X,h=new ie(a);return a.add(c.subscribe(function(c){var l,f,p,d,b,v,m,y,w,g;try{v=t(c),m=s(v)}catch(E){for(g in u)u[g].onError(E);return r.onError(E),e}d=!1;try{w=u[m],w||(w=new Ke,u[m]=w,d=!0)}catch(E){for(g in u)u[g].onError(E);return r.onError(E),e}if(d){b=new Ge(v,w,h),f=new Ge(v,w);try{l=o(f)}catch(E){for(g in u)u[g].onError(E);return r.onError(E),e}r.onNext(b),y=new ee,a.add(y);var x=function(){m in u&&(delete u[m],w.onCompleted()),a.remove(y)};y.setDisposable(l.take(1).subscribe(n,function(t){for(g in u)u[g].onError(t);r.onError(t)},function(){x()}))}try{p=i(c)}catch(E){for(g in u)u[g].onError(E);return r.onError(E),e}w.onNext(p)},function(t){for(var e in u)u[e].onError(t);r.onError(t)},function(){for(var t in u)u[t].onCompleted();r.onCompleted()})),h})},Ae.select=Ae.map=function(t,n){var r=this;return new He(function(i){var o=0;return r.subscribe(function(s){var u;try{u=t.call(n,s,o++,r)}catch(c){return i.onError(c),e}i.onNext(u)},i.onError.bind(i),i.onCompleted.bind(i))})},Ae.pluck=function(t){return this.select(function(e){return e[t]})},Ae.selectMany=Ae.flatMap=function(t,e){return e?this.selectMany(function(n){return t(n).select(function(t){return e(n,t)})}):"function"==typeof t?g.call(this,t):g.call(this,function(){return t})},Ae.selectManyLatest=Ae.flatMapLatest=function(t,e){return this.selectMany(t,e).switchLatest()},Ae.skip=function(t){if(0>t)throw Error(S);var e=this;return new He(function(n){var r=t;return e.subscribe(function(t){0>=r?n.onNext(t):r--},n.onError.bind(n),n.onCompleted.bind(n))})},Ae.skipWhile=function(t,n){var r=this;return new He(function(i){var o=0,s=!1;return r.subscribe(function(u){if(!s)try{s=!t.call(n,u,o++,r)}catch(c){return i.onError(c),e}s&&i.onNext(u)},i.onError.bind(i),i.onCompleted.bind(i))})},Ae.take=function(t,e){if(0>t)throw Error(S);if(0===t)return qe(e);var n=this;return new He(function(e){var r=t;return n.subscribe(function(t){r>0&&(r--,e.onNext(t),0===r&&e.onCompleted())},e.onError.bind(e),e.onCompleted.bind(e))})},Ae.takeWhile=function(t,n){var r=this;return new He(function(i){var o=0,s=!0;return r.subscribe(function(u){if(s){try{s=t.call(n,u,o++,r)}catch(c){return i.onError(c),e}s?i.onNext(u):i.onCompleted()}},i.onError.bind(i),i.onCompleted.bind(i))})},Ae.where=Ae.filter=function(t,n){var r=this;return new He(function(i){var o=0;return r.subscribe(function(s){var u;try{u=t.call(n,s,o++,r)}catch(c){return i.onError(c),e}u&&i.onNext(s)},i.onError.bind(i),i.onCompleted.bind(i))})};var He=D.Internals.AnonymousObservable=function(t){function n(r){function i(t){var e=new Ue(t);if(ce.scheduleRequired())ce.schedule(function(){try{e.disposable(r(e))}catch(t){if(!e.fail(t))throw t}});else try{e.disposable(r(e))}catch(n){if(!e.fail(n))throw n}return e}return this instanceof n?(t.call(this,i),e):new n(r)}return H(n,t),n}(We),Ue=function(t){function e(e){t.call(this),this.observer=e,this.m=new ee}H(e,t);var n=e.prototype;return n.next=function(t){var e=!1;try{this.observer.onNext(t),e=!0}catch(n){throw n}finally{e||this.dispose()}},n.error=function(t){try{this.observer.onError(t)}catch(e){throw e}finally{this.dispose()}},n.completed=function(){try{this.observer.onCompleted()}catch(t){throw t}finally{this.dispose()}},n.disposable=function(t){return this.m.disposable(t)},n.dispose=function(){t.prototype.dispose.call(this),this.m.dispose()},e}(Se),Ge=function(t){function e(t){return this.underlyingObservable.subscribe(t)}function n(n,r,i){t.call(this,e),this.key=n,this.underlyingObservable=i?new He(function(t){return new X(i.getDisposable(),r.subscribe(t))}):r}return H(n,t),n}(We),Je=function(t,e){this.subject=t,this.observer=e};Je.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}};var Ke=D.Subject=function(t){function e(t){return a.call(this),this.isStopped?this.exception?(t.onError(this.exception),te):(t.onCompleted(),te):(this.observers.push(t),new Je(this,t))}function n(){t.call(this,e),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return H(n,t),U(n.prototype,Ce,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(a.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var e=0,n=t.length;n>e;e++)t[e].onCompleted();this.observers=[]}},onError:function(t){if(a.call(this),!this.isStopped){var e=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var n=0,r=e.length;r>n;n++)e[n].onError(t);this.observers=[]}},onNext:function(t){if(a.call(this),!this.isStopped)for(var e=this.observers.slice(0),n=0,r=e.length;r>n;n++)e[n].onNext(t)},dispose:function(){this.isDisposed=!0,this.observers=null}}),n.create=function(t,e){return new Xe(t,e)},n}(We),Qe=D.AsyncSubject=function(t){function e(t){if(a.call(this),!this.isStopped)return this.observers.push(t),new Je(this,t);var e=this.exception,n=this.hasValue,r=this.value;return e?t.onError(e):n?(t.onNext(r),t.onCompleted()):t.onCompleted(),te}function n(){t.call(this,e),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return H(n,t),U(n.prototype,Ce,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){var t,e,n;if(a.call(this),!this.isStopped){var r=this.observers.slice(0);this.isStopped=!0;var i=this.value,o=this.hasValue;if(o)for(e=0,n=r.length;n>e;e++)t=r[e],t.onNext(i),t.onCompleted();else for(e=0,n=r.length;n>e;e++)r[e].onCompleted();this.observers=[]}},onError:function(t){if(a.call(this),!this.isStopped){var e=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var n=0,r=e.length;r>n;n++)e[n].onError(t);this.observers=[]}},onNext:function(t){a.call(this),this.isStopped||(this.value=t,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),n}(We),Xe=function(t){function e(t){return this.observable.subscribe(t)}function n(n,r){t.call(this,e),this.observer=n,this.observable=r}return H(n,t),U(n.prototype,Ce,{onCompleted:function(){this.observer.onCompleted()},onError:function(t){this.observer.onError(t)},onNext:function(t){this.observer.onNext(t)}}),n}(We);return"function"==typeof define&&"object"==typeof define.amd&&define.amd?(t.Rx=D,define(function(){return D})):(E?"object"==typeof module&&module&&module.exports==E?module.exports=D:E=D:t.Rx=D,e)})(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.1.18/rx.node.js b/ajax/libs/rxjs/2.1.18/rx.node.js new file mode 100644 index 000000000..d8a66c326 --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.node.js @@ -0,0 +1,172 @@ +var Rx = require('./rx'); +require('./rx.aggregates'); +require('./rx.binding'); +require('./rx.coincidence'); +require('./rx.experimental'); +require('./rx.joinpatterns'); +require('./rx.testing'); +require('./rx.time'); + +// Add specific Node functions +var EventEmitter = require('events').EventEmitter, + slice = Array.prototype.slice; + +Rx.Node = { + /** + * Converts a callback function to an observable sequence. + * + * @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. + */ + fromCallback: function (func, scheduler, context) { + scheduler || (scheduler = Rx.Scheduler.timeout); + return function () { + var args = slice.call(arguments, 0), + subject = new Rx.AsyncSubject(); + + scheduler.schedule(function () { + function handler() { + subject.onNext(arguments); + subject.onCompleted(); + } + + args.push(handler); + func.apply(context, args); + }); + + return subject.asObservable(); + }; + }, + + /** + * 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 {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} An async function which when applied, returns an observable sequence with the callback arguments as an array. + */ + fromNodeCallback: function (func, scheduler, context) { + scheduler || (scheduler = Rx.Scheduler.timeout); + return function () { + var args = slice.call(arguments, 0), + subject = new Rx.AsyncSubject(); + + scheduler.schedule(function () { + function handler(err) { + var handlerArgs = slice.call(arguments, 1); + + if (err) { + subject.onError(err); + return; + } + + subject.onNext(handlerArgs); + subject.onCompleted(); + } + + args.push(handler); + func.apply(context, args); + }); + + return subject.asObservable(); + }; + }, + + /** + * Handles an event from the given EventEmitter as an observable sequence. + * @param {EventEmitter} eventEmiiter The EventEmitter to subscribe to the given event. + * @param {String} eventName The event name to subscribe + * @returns {Observable} An observable sequence generated from the named event from the given EventEmitter. + */ + fromEvent: function (eventEmitter, eventName) { + return Rx.Observable.create(function (observer) { + function handler () { + observer.onNext(arguments); + } + + eventEmitter.on(eventName, handler); + + return function () { + eventEmitter.off(eventName, handler); + } + }).publish().refCount(); + }, + + /** + * Converts the given observable sequence to an event emitter with the given event name. + * The errors are handled on the 'error' event and completion on the 'end' event. + * @param {Observable} The observable sequence to convert to an EventEmitter. + * @param {String} eventName The event name to emit onNext calls. + * @returns {EventEmitter} An EventEmitter which emits the given eventName for each onNext call in addition to 'error' and 'end' events. + */ + toEventEmitter: function (observable, eventName) { + var e = new EventEmitter(); + + e.subscription = observable.subscribe( + function (x) { + e.emit(eventName, x); + }, + function (err) { + e.emit('error', err); + }, + function () { + e.emit('end'); + }); + + return e; + }, + + /** + * Converts a flowing stream to an Observable sequence. + * @param {Stream} stream A stream to convert to a observable sequence. + * @returns {Observable} An observable sequence which fires on each 'data' event as well as handling 'error' and 'end' events. + */ + fromStream: function (stream) { + return Rx.Observable.create(function (observer) { + function dataHandler (data) { + observer.onNext(data); + } + + function errorHandler (err) { + observer.onError(err); + } + + function endHandler () { + observer.onCompleted(); + } + + stream.on('data', dataHandler); + stream.on('error', errorHandler); + stream.on('end', endHandler); + + return function () { + stream.off('data', dataHandler); + stream.off('error', errorHandler); + stream.off('end', endHandler); + }; + }).publish().refCount(); + }, + + /** + * Writes an observable sequence to a stream + * @param {Observable} observable Observable sequence to write to a stream. + * @param {Stream} stream The stream to write to. + * @param {String} [encoding] The encoding of the item to write. + * @returns {Disposable} The subscription handle. + */ + writeToStream: function (observable, stream, encoding) { + return observable.subscribe( + function (x) { + stream.write(x, encoding); + }, + function (err) { + stream.emit('error', err); + }, function () { + stream.end(); + }); + } +}; + +module.exports = Rx; \ No newline at end of file diff --git a/ajax/libs/rxjs/2.1.18/rx.testing.js b/ajax/libs/rxjs/2.1.18/rx.testing.js new file mode 100644 index 000000000..b558bab0a --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.testing.js @@ -0,0 +1,487 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +(function (root, factory) { + var freeExports = typeof exports == 'object' && exports, + freeModule = typeof module == 'object' && module && module.exports == freeExports && module, + freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal) { + window = 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); + } +}(this, function (global, 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, + isEqual = Rx.Internals.isEqual; + + // Utilities + function defaultComparer(x, y) { + return isEqual(x, y); + } + + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + + /** + * @private + * @constructor + */ + function OnNextPredicate(predicate) { + this.predicate = predicate; + }; + + /** + * @private + * @memberOf OnNextPredicate# + */ + 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); + }; + + /** + * @private + * @constructor + */ + function OnErrorPredicate(predicate) { + this.predicate = predicate; + }; + + /** + * @private + * @memberOf OnErrorPredicate# + */ + 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); + }; + + /** + * @static + * type Object + */ + 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 -based 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 () { + for (var j = 0; j < observable.observers.length; j++) { + innerNotification.accept(observable.observers[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); + + /** @constructor */ + function TestScheduler() { + _super.call(this, 0, function (a, b) { return a - b; }); + } + + /** + * 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.1.18/rx.testing.min.js b/ajax/libs/rxjs/2.1.18/rx.testing.min.js new file mode 100644 index 000000000..c00bbf8cd --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.testing.min.js @@ -0,0 +1 @@ +(function(t,e){var n="object"==typeof exports&&exports,r=("object"==typeof module&&module&&module.exports==n&&module,"object"==typeof global&&global);r.global===r&&(window=r),"function"==typeof define&&define.amd?define(["rx","exports"],function(n,r){return t.Rx=e(t,r,n),t.Rx}):"object"==typeof module&&module&&module.exports===n?module.exports=e(t,module.exports,require("./rx")):t.Rx=e(t,{},t.Rx)})(this,function(t,e,n){function r(t,e){return m(t,e)}function i(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:b.call(t)}function o(t){this.predicate=t}function s(t){this.predicate=t}var u=n.Observer,c=n.Observable,a=n.Notification,h=n.VirtualTimeScheduler,l=n.Disposable,f=l.empty,p=l.create,d=n.CompositeDisposable,b=(n.SingleAssignmentDisposable,Array.prototype.slice),v=n.Internals.inherits,m=n.Internals.isEqual;o.prototype.equals=function(t){return t===this?!0:null==t?!1:"N"!==t.kind?!1:this.predicate(t.value)},s.prototype.equals=function(t){return t===this?!0:null==t?!1:"E"!==t.kind?!1:this.predicate(t.exception)};var y=n.ReactiveTest={created:100,subscribed:200,disposed:1e3,onNext:function(t,e){return"function"==typeof e?new w(t,new o(e)):new w(t,a.createOnNext(e))},onError:function(t,e){return"function"==typeof e?new w(t,new s(e)):new w(t,a.createOnError(e))},onCompleted:function(t){return new w(t,a.createOnCompleted())},subscribe:function(t,e){return new g(t,e)}},w=n.Recorded=function(t,e,n){this.time=t,this.value=e,this.comparer=n||r};w.prototype.equals=function(t){return this.time===t.time&&this.comparer(this.value,t.value)},w.prototype.toString=function(){return""+this.value+"@"+this.time};var g=n.Subscription=function(t,e){this.subscribe=t,this.unsubscribe=e||Number.MAX_VALUE};g.prototype.equals=function(t){return this.subscribe===t.subscribe&&this.unsubscribe===t.unsubscribe},g.prototype.toString=function(){return"("+this.subscribe+", "+this.unsubscribe===Number.MAX_VALUE?"Infinite":this.unsubscribe+")"};var E=n.MockDisposable=function(t){this.scheduler=t,this.disposes=[],this.disposes.push(this.scheduler.clock)};E.prototype.dispose=function(){this.disposes.push(this.scheduler.clock)};var x=function(t){function e(e){t.call(this),this.scheduler=e,this.messages=[]}v(e,t);var n=e.prototype;return n.onNext=function(t){this.messages.push(new w(this.scheduler.clock,a.createOnNext(t)))},n.onError=function(t){this.messages.push(new w(this.scheduler.clock,a.createOnError(t)))},n.onCompleted=function(){this.messages.push(new w(this.scheduler.clock,a.createOnCompleted()))},e}(u),C=function(t){function e(t){var e=this;this.observers.push(t),this.subscriptions.push(new g(this.scheduler.clock));var n=this.subscriptions.length-1;return p(function(){var r=e.observers.indexOf(t);e.observers.splice(r,1),e.subscriptions[n]=new g(e.subscriptions[n].subscribe,e.scheduler.clock)})}function n(n,r){t.call(this,e);var i,o,s=this;this.scheduler=n,this.messages=r,this.subscriptions=[],this.observers=[];for(var u=0,c=this.messages.length;c>u;u++)i=this.messages[u],o=i.value,function(t){n.scheduleAbsoluteWithState(null,i.time,function(){for(var e=0;s.observers.length>e;e++)t.accept(s.observers[e]);return f})}(o)}return v(n,t),n}(c),D=function(t){function e(t){var e,n,r=this;this.subscriptions.push(new g(this.scheduler.clock));for(var i=this.subscriptions.length-1,o=new d,s=0,u=this.messages.length;u>s;s++)e=this.messages[s],n=e.value,function(n){o.add(r.scheduler.scheduleRelativeWithState(null,e.time,function(){return n.accept(t),f}))}(n);return p(function(){r.subscriptions[i]=new g(r.subscriptions[i].subscribe,r.scheduler.clock),o.dispose()})}function n(n,r){t.call(this,e),this.scheduler=n,this.messages=r,this.subscriptions=[]}return v(n,t),n}(c);return n.TestScheduler=function(t){function e(){t.call(this,0,function(t,e){return t-e})}return v(e,t),e.prototype.scheduleAbsoluteWithState=function(e,n,r){return this.clock>=n&&(n=this.clock+1),t.prototype.scheduleAbsoluteWithState.call(this,e,n,r)},e.prototype.add=function(t,e){return t+e},e.prototype.toDateTimeOffset=function(t){return new Date(t).getTime()},e.prototype.toRelative=function(t){return t},e.prototype.startWithTiming=function(t,e,n,r){var i,o,s=this.createObserver();return this.scheduleAbsoluteWithState(null,e,function(){return i=t(),f}),this.scheduleAbsoluteWithState(null,n,function(){return o=i.subscribe(s),f}),this.scheduleAbsoluteWithState(null,r,function(){return o.dispose(),f}),this.start(),s},e.prototype.startWithDispose=function(t,e){return this.startWithTiming(t,y.created,y.subscribed,e)},e.prototype.startWithCreate=function(t){return this.startWithTiming(t,y.created,y.subscribed,y.disposed)},e.prototype.createHotObservable=function(){var t=i(arguments,0);return new C(this,t)},e.prototype.createColdObservable=function(){var t=i(arguments,0);return new D(this,t)},e.prototype.createObserver=function(){return new x(this)},e}(h),n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.1.18/rx.time.js b/ajax/libs/rxjs/2.1.18/rx.time.js new file mode 100644 index 000000000..9444ffe40 --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.time.js @@ -0,0 +1,1213 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +(function (root, factory) { + var freeExports = typeof exports == 'object' && exports, + freeModule = typeof module == 'object' && module && module.exports == freeExports && module, + freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal) { + window = 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); + } +}(this, function (global, exp, Rx, undefined) { + + // Refernces + var Observable = Rx.Observable, + observableProto = Observable.prototype, + AnonymousObservable = Rx.Internals.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, + BinaryObserver = Rx.Internals.BinaryObserver, + addRef = Rx.Internals.addRef, + normalizeTime = Rx.Scheduler.normalize; + + function observableTimerDate(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithAbsolute(dueTime, function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerDateAndPeriod(dueTime, period, scheduler) { + var p = normalizeTime(period); + return new AnonymousObservable(function (observer) { + var count = 0, d = dueTime; + return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { + var now; + if (p > 0) { + now = scheduler.now(); + d = d + p; + if (d <= now) { + d = now + p; + } + } + observer.onNext(count++); + self(d); + }); + }); + } + + function observableTimerTimeSpan(dueTime, scheduler) { + var d = normalizeTime(dueTime); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithRelative(d, function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { + if (dueTime === period) { + return new AnonymousObservable(function (observer) { + return scheduler.schedulePeriodicWithState(0, period, function (count) { + observer.onNext(count); + return count + 1; + }); + }); + } + return 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); + * + * @static + * @memberOf Observable + * @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) { + scheduler || (scheduler = timeoutScheduler); + return observableTimerTimeSpanAndPeriod(period, period, scheduler); + }; + + /** + * 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); + * + * @static + * @memberOf Observable + * @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; + 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); + } + if (period === undefined) { + return observableTimerTimeSpan(dueTime, scheduler); + } + return observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); + }; + + function observableDelayTimeSpan(dueTime, scheduler) { + var source = this; + 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.disposable(d); + d.disposable(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(dueTime, scheduler) { + var self = this; + return observableDefer(function () { + var timeSpan = dueTime - scheduler.now(); + return observableDelayTimeSpan.call(self, timeSpan, scheduler); + }); + } + + /** + * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. + * + * @example + * 1 - res = Rx.Observable.timer(new Date()); + * 2 - res = Rx.Observable.timer(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) { + scheduler || (scheduler = timeoutScheduler); + return dueTime instanceof Date ? + observableDelayDate.call(this, dueTime.getTime(), scheduler) : + observableDelayTimeSpan.call(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); + * + * @memberOf Observable + * @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) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var cancelable = new SerialDisposable(), hasvalue = false, id = 0, subscription, value = null; + subscription = source.subscribe(function (x) { + var currentId, d; + hasvalue = true; + value = x; + id++; + currentId = id; + d = new SingleAssignmentDisposable(); + cancelable.disposable(d); + d.disposable(scheduler.scheduleWithRelative(dueTime, function () { + if (hasvalue && id === currentId) { + observer.onNext(value); + } + hasvalue = false; + })); + }, function (exception) { + cancelable.dispose(); + observer.onError(exception); + hasvalue = false; + id++; + }, function () { + cancelable.dispose(); + if (hasvalue) { + observer.onNext(value); + } + observer.onCompleted(); + hasvalue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * 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 + * + * @memberOf Observable# + * @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; + if (timeShiftOrScheduler === undefined) { + timeShift = timeSpan; + } + if (scheduler === undefined) { + scheduler = timeoutScheduler; + } + if (typeof timeShiftOrScheduler === 'number') { + timeShift = timeShiftOrScheduler; + } else if (typeof timeShiftOrScheduler === 'object') { + timeShift = timeSpan; + scheduler = timeShiftOrScheduler; + } + return new AnonymousObservable(function (observer) { + var createTimer, + groupDisposable, + nextShift = timeShift, + nextSpan = timeSpan, + q = [], + refCountDisposable, + timerD = new SerialDisposable(), + totalTime = 0; + groupDisposable = new CompositeDisposable(timerD); + refCountDisposable = new RefCountDisposable(groupDisposable); + createTimer = function () { + var isShift, isSpan, m, newTotalTime, ts; + m = new SingleAssignmentDisposable(); + timerD.disposable(m); + isSpan = false; + isShift = false; + if (nextSpan === nextShift) { + isSpan = true; + isShift = true; + } else if (nextSpan < nextShift) { + isSpan = true; + } else { + isShift = true; + } + newTotalTime = isSpan ? nextSpan : nextShift; + ts = newTotalTime - totalTime; + totalTime = newTotalTime; + if (isSpan) { + nextSpan += timeShift; + } + if (isShift) { + nextShift += timeShift; + } + m.disposable(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(); + })); + }; + q.push(new Subject()); + observer.onNext(addRef(q[0], refCountDisposable)); + createTimer(); + groupDisposable.add(source.subscribe(function (x) { + var i, s; + for (i = 0; i < q.length; i++) { + s = q[i]; + s.onNext(x); + } + }, function (e) { + var i, s; + for (i = 0; i < q.length; i++) { + s = q[i]; + s.onError(e); + } + observer.onError(e); + }, function () { + var i, s; + for (i = 0; i < q.length; i++) { + s = q[i]; + s.onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * 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; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var createTimer, + groupDisposable, + n = 0, + refCountDisposable, + s, + timerD = new SerialDisposable(), + windowId = 0; + groupDisposable = new CompositeDisposable(timerD); + refCountDisposable = new RefCountDisposable(groupDisposable); + createTimer = function (id) { + var m = new SingleAssignmentDisposable(); + timerD.disposable(m); + m.disposable(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); + })); + }; + s = new Subject(); + 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)); + } + if (newWindow) { + createTimer(newId); + } + }, function (e) { + s.onError(e); + observer.onError(e); + }, function () { + s.onCompleted(); + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * 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 + * + * @memberOf Observable# + * @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 + * + * @memberOf Observable# + * @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); + * + * @memberOf Observable# + * @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; + scheduler || (scheduler = timeoutScheduler); + return observableDefer(function () { + var last = scheduler.now(); + return source.select(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); + * + * @memberOf Observable# + * @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) { + scheduler || (scheduler = timeoutScheduler); + return this.select(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); + } + if (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 + * + * @memberOf Observable# + * @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) { + scheduler || (scheduler = timeoutScheduler); + if (typeof intervalOrSampler === 'number') { + return sampleObservable(this, observableinterval(intervalOrSampler, scheduler)); + } + return 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 + * + * @memberOf 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) { + var schedulerMethod, source = this; + other || (other = observableThrow(new Error('Timeout'))); + scheduler || (scheduler = timeoutScheduler); + if (dueTime instanceof Date) { + schedulerMethod = function (dt, action) { + scheduler.scheduleWithAbsolute(dt, action); + }; + } else { + schedulerMethod = function (dt, action) { + scheduler.scheduleWithRelative(dt, action); + }; + } + return new AnonymousObservable(function (observer) { + var createTimer, + id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + subscription.disposable(original); + createTimer = function () { + var myId = id; + timer.disposable(schedulerMethod(dueTime, function () { + switched = id === myId; + var timerWins = switched; + if (timerWins) { + subscription.disposable(other.subscribe(observer)); + } + })); + }; + createTimer(); + original.disposable(source.subscribe(function (x) { + var onNextWins = !switched; + if (onNextWins) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + var onErrorWins = !switched; + if (onErrorWins) { + id++; + observer.onError(e); + } + }, function () { + var onCompletedWins = !switched; + if (onCompletedWins) { + 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(); + * }); + * + * @static + * @memberOf Observable + * @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) { + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { + if (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; } + * ); + * + * @static + * @memberOf Observable + * @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) { + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithRelative(0, function (self) { + if (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 + * + * @memberOf Observable# + * @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) { + scheduler || (scheduler = timeoutScheduler); + return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return 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 + * + * @memberOf Observable# + * @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)); + * + * @memberOf Observable# + * @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); }); + * + * @memberOf Observable# + * @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. + * @memberOf Observable# + * @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) { + 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. + * @memberOf Observable# + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) { + return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); }); + }; + + /** + * 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. + * @memberOf Observable# + * @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; + 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. + * @memberOf Observable# + * @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; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var t = scheduler.scheduleWithRelative(duration, function () { + observer.onCompleted(); + }); + + return new CompositeDisposable(t, 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. + * @memberOf Observable# + * @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; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false, + t = scheduler.scheduleWithRelative(duration, function () { open = true; }), + d = source.subscribe(function (x) { + if (open) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + + return new CompositeDisposable(t, d); + }); + }; + + /** + * 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]); + * @memberOf Obseravble# + * @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) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var open = false, + t = scheduler.scheduleWithAbsolute(startTime, function () { open = true; }), + d = source.subscribe(function (x) { + if (open) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + + return new CompositeDisposable(t, d); + }); + }; + + /** + * 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]); + * @memberOf Observable# + * @param {Number} 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) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler.scheduleWithAbsolute(endTime, function () { + observer.onCompleted(); + }), source.subscribe(observer)); + }); + }; + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.1.18/rx.time.min.js b/ajax/libs/rxjs/2.1.18/rx.time.min.js new file mode 100644 index 000000000..ce8c462b9 --- /dev/null +++ b/ajax/libs/rxjs/2.1.18/rx.time.min.js @@ -0,0 +1 @@ +(function(t,e){var n="object"==typeof exports&&exports,r=("object"==typeof module&&module&&module.exports==n&&module,"object"==typeof global&&global);r.global===r&&(window=r),"function"==typeof define&&define.amd?define(["rx","exports"],function(n,r){return t.Rx=e(t,r,n),t.Rx}):"object"==typeof module&&module&&module.exports===n?module.exports=e(t,module.exports,require("./rx")):t.Rx=e(t,{},t.Rx)})(this,function(t,e,n,r){function i(t,e){return new p(function(n){return e.scheduleWithAbsolute(t,function(){n.onNext(0),n.onCompleted()})})}function o(t,e,n){var r=N(e);return new p(function(e){var i=0,o=t;return n.scheduleRecursiveWithAbsolute(o,function(t){var s;r>0&&(s=n.now(),o+=r,s>=o&&(o=s+r)),e.onNext(i++),t(o)})})}function s(t,e){var n=N(t);return new p(function(t){return e.scheduleWithRelative(n,function(){t.onNext(0),t.onCompleted()})})}function u(t,e,n){return t===e?new p(function(t){return n.schedulePeriodicWithState(0,e,function(e){return t.onNext(e),e+1})}):d(function(){return o(n.now()+t,e,n)})}function c(t,e){var n=this;return new p(function(r){var i,o=!1,s=new x,u=null,c=[],a=!1;return i=n.materialize().timestamp(e).subscribe(function(n){var i,h;"E"===n.value.kind?(c=[],c.push(n),u=n.value.exception,h=!a):(c.push({value:n.value,timestamp:n.timestamp+t}),h=!o,o=!0),h&&(null!==u?r.onError(u):(i=new g,s.disposable(i),i.disposable(e.scheduleRecursiveWithRelative(t,function(t){var n,i,s,h;if(null===u){a=!0;do s=null,c.length>0&&0>=c[0].timestamp-e.now()&&(s=c.shift().value),null!==s&&s.accept(r);while(null!==s);h=!1,i=0,c.length>0?(h=!0,i=Math.max(0,c[0].timestamp-e.now())):o=!1,n=u,a=!1,null!==n?r.onError(n):h&&t(i)}}))))}),new E(i,s)})}function a(t,e){var n=this;return d(function(){var r=t-e.now();return c.call(n,r,e)})}function h(t,e){return new p(function(n){function r(){s&&(s=!1,n.onNext(o)),i&&n.onCompleted()}var i,o,s;return new E(t.subscribe(function(t){s=!0,o=t},n.onError.bind(n),function(){i=!0}),e.subscribe(r,n.onError.bind(n),r))})}var l=n.Observable,f=l.prototype,p=n.Internals.AnonymousObservable,d=l.defer,b=l.empty,v=l.never,m=l.throwException,y=l.fromArray,w=n.Scheduler.timeout,g=n.SingleAssignmentDisposable,x=n.SerialDisposable,E=n.CompositeDisposable,C=n.RefCountDisposable,D=n.Subject,A=(n.Internals.BinaryObserver,n.Internals.addRef),N=n.Scheduler.normalize,S=l.interval=function(t,e){return e||(e=w),u(t,t,e)},O=l.timer=function(t,e,n){var c;return n||(n=w),e!==r&&"number"==typeof e?c=e:e!==r&&"object"==typeof e&&(n=e),t instanceof Date&&c===r?i(t.getTime(),n):t instanceof Date&&c!==r?(c=e,o(t.getTime(),c,n)):c===r?s(t,n):u(t,c,n)};return f.delay=function(t,e){return e||(e=w),t instanceof Date?a.call(this,t.getTime(),e):c.call(this,t,e)},f.throttle=function(t,e){e||(e=w);var n=this;return new p(function(r){var i,o=new x,s=!1,u=0,c=null;return i=n.subscribe(function(n){var i,a;s=!0,c=n,u++,i=u,a=new g,o.disposable(a),a.disposable(e.scheduleWithRelative(t,function(){s&&u===i&&r.onNext(c),s=!1}))},function(t){o.dispose(),r.onError(t),s=!1,u++},function(){o.dispose(),s&&r.onNext(c),r.onCompleted(),s=!1,u++}),new E(i,o)})},f.windowWithTime=function(t,e,n){var i,o=this;return e===r&&(i=t),n===r&&(n=w),"number"==typeof e?i=e:"object"==typeof e&&(i=t,n=e),new p(function(e){var r,s,u,c=i,a=t,h=[],l=new x,f=0;return s=new E(l),u=new C(s),r=function(){var t,o,s,p,d;s=new g,l.disposable(s),o=!1,t=!1,a===c?(o=!0,t=!0):c>a?o=!0:t=!0,p=o?a:c,d=p-f,f=p,o&&(a+=i),t&&(c+=i),s.disposable(n.scheduleWithRelative(d,function(){var n;t&&(n=new D,h.push(n),e.onNext(A(n,u))),o&&(n=h.shift(),n.onCompleted()),r()}))},h.push(new D),e.onNext(A(h[0],u)),r(),s.add(o.subscribe(function(t){var e,n;for(e=0;h.length>e;e++)n=h[e],n.onNext(t)},function(t){var n,r;for(n=0;h.length>n;n++)r=h[n],r.onError(t);e.onError(t)},function(){var t,n;for(t=0;h.length>t;t++)n=h[t],n.onCompleted();e.onCompleted()})),u})},f.windowWithTimeOrCount=function(t,e,n){var r=this;return n||(n=w),new p(function(i){var o,s,u,c,a=0,h=new x,l=0;return s=new E(h),u=new C(s),o=function(e){var r=new g;h.disposable(r),r.disposable(n.scheduleWithRelative(t,function(){var t;e===l&&(a=0,t=++l,c.onCompleted(),c=new D,i.onNext(A(c,u)),o(t))}))},c=new D,i.onNext(A(c,u)),o(0),s.add(r.subscribe(function(t){var n=0,r=!1;c.onNext(t),a++,a===e&&(r=!0,a=0,n=++l,c.onCompleted(),c=new D,i.onNext(A(c,u))),r&&o(n)},function(t){c.onError(t),i.onError(t)},function(){c.onCompleted(),i.onCompleted()})),u})},f.bufferWithTime=function(){return this.windowWithTime.apply(this,arguments).selectMany(function(t){return t.toArray()})},f.bufferWithTimeOrCount=function(t,e,n){return this.windowWithTimeOrCount(t,e,n).selectMany(function(t){return t.toArray()})},f.timeInterval=function(t){var e=this;return t||(t=w),d(function(){var n=t.now();return e.select(function(e){var r=t.now(),i=r-n;return n=r,{value:e,interval:i}})})},f.timestamp=function(t){return t||(t=w),this.select(function(e){return{value:e,timestamp:t.now()}})},f.sample=function(t,e){return e||(e=w),"number"==typeof t?h(this,S(t,e)):h(this,t)},f.timeout=function(t,e,n){var r,i=this;return e||(e=m(Error("Timeout"))),n||(n=w),r=t instanceof Date?function(t,e){n.scheduleWithAbsolute(t,e)}:function(t,e){n.scheduleWithRelative(t,e)},new p(function(n){var o,s=0,u=new g,c=new x,a=!1,h=new x;return c.disposable(u),o=function(){var i=s;h.disposable(r(t,function(){a=s===i;var t=a;t&&c.disposable(e.subscribe(n))}))},o(),u.disposable(i.subscribe(function(t){var e=!a;e&&(s++,n.onNext(t),o())},function(t){var e=!a;e&&(s++,n.onError(t))},function(){var t=!a;t&&(s++,n.onCompleted())})),new E(c,h)})},l.generateWithAbsoluteTime=function(t,e,n,i,o,s){return s||(s=w),new p(function(u){var c,a,h=!0,l=!1,f=t;return s.scheduleRecursiveWithAbsolute(s.now(),function(t){l&&u.onNext(c);try{h?h=!1:f=n(f),l=e(f),l&&(c=i(f),a=o(f))}catch(s){return u.onError(s),r}l?t(a):u.onCompleted()})})},l.generateWithRelativeTime=function(t,e,n,i,o,s){return s||(s=w),new p(function(u){var c,a,h=!0,l=!1,f=t;return s.scheduleRecursiveWithRelative(0,function(t){l&&u.onNext(c);try{h?h=!1:f=n(f),l=e(f),l&&(c=i(f),a=o(f))}catch(s){return u.onError(s),r}l?t(a):u.onCompleted()})})},f.delaySubscription=function(t,e){return e||(e=w),this.delayWithSelector(O(t,e),function(){return b()})},f.delayWithSelector=function(t,e){var n,i,o=this;return"function"==typeof t?i=t:(n=t,i=e),new p(function(t){var e=new E,s=!1,u=function(){s&&0===e.length&&t.onCompleted()},c=new x,a=function(){c.setDisposable(o.subscribe(function(n){var o;try{o=i(n)}catch(s){return t.onError(s),r}var c=new g;e.add(c),c.setDisposable(o.subscribe(function(){t.onNext(n),e.remove(c),u()},t.onError.bind(t),function(){t.onNext(n),e.remove(c),u()}))},t.onError.bind(t),function(){s=!0,c.dispose(),u()}))};return n?c.setDisposable(n.subscribe(function(){a()},t.onError.bind(t),function(){a()})):a(),new E(c,e)})},f.timeoutWithSelector=function(t,e,n){if(1===arguments.length){e=t;var t=v()}n||(n=m(Error("Timeout")));var i=this;return new p(function(o){var s=new x,u=new x,c=new g;s.setDisposable(c);var a=0,h=!1,l=function(t){var e=a,r=function(){return a===e},i=new g;u.setDisposable(i),i.setDisposable(t.subscribe(function(){r()&&s.setDisposable(n.subscribe(o)),i.dispose()},function(t){r()&&o.onError(t)},function(){r()&&s.setDisposable(n.subscribe(o))}))};l(t);var f=function(){var t=!h;return t&&a++,t};return c.setDisposable(i.subscribe(function(t){if(f()){o.onNext(t);var n;try{n=e(t)}catch(i){return o.onError(i),r}l(n)}},function(t){f()&&o.onError(t)},function(){f()&&o.onCompleted()})),new E(s,u)})},f.throttleWithSelector=function(t){var e=this;return new p(function(n){var i,o=!1,s=new x,u=0,c=e.subscribe(function(e){var c;try{c=t(e)}catch(a){return n.onError(a),r}o=!0,i=e,u++;var h=u,l=new g;s.setDisposable(l),l.setDisposable(c.subscribe(function(){o&&u===h&&n.onNext(i),o=!1,l.dispose()},n.onError.bind(n),function(){o&&u===h&&n.onNext(i),o=!1,l.dispose()}))},function(t){s.dispose(),n.onError(t),o=!1,u++},function(){s.dispose(),o&&n.onNext(i),n.onCompleted(),o=!1,u++});return new E(c,s)})},f.skipLastWithTime=function(t,e){e||(e=w);var n=this;return new p(function(r){var i=[];return n.subscribe(function(n){var o=e.now();for(i.push({interval:o,value:n});i.length>0&&o-i[0].interval>=t;)r.onNext(i.shift().value)},r.onError.bind(r),function(){for(var n=e.now();i.length>0&&n-i[0].interval>=t;)r.onNext(i.shift().value);r.onCompleted()})})},f.takeLastWithTime=function(t,e,n){return this.takeLastBufferWithTime(t,e).selectMany(function(t){return y(t,n)})},f.takeLastBufferWithTime=function(t,e){var n=this;return e||(e=w),new p(function(r){var i=[];return n.subscribe(function(n){var r=e.now();for(i.push({interval:r,value:n});i.length>0&&r-i[0].interval>=t;)i.shift()},r.onError.bind(r),function(){for(var n=e.now(),o=[];i.length>0;){var s=i.shift();t>=n-s.interval&&o.push(s.value)}r.onNext(o),r.onCompleted()})})},f.takeWithTime=function(t,e){var n=this;return e||(e=w),new p(function(r){var i=e.scheduleWithRelative(t,function(){r.onCompleted()});return new E(i,n.subscribe(r))})},f.skipWithTime=function(t,e){var n=this;return e||(e=w),new p(function(r){var i=!1,o=e.scheduleWithRelative(t,function(){i=!0}),s=n.subscribe(function(t){i&&r.onNext(t)},r.onError.bind(r),r.onCompleted.bind(r));return new E(o,s)})},f.skipUntilWithTime=function(t,e){e||(e=w);var n=this;return new p(function(r){var i=!1,o=e.scheduleWithAbsolute(t,function(){i=!0}),s=n.subscribe(function(t){i&&r.onNext(t)},r.onError.bind(r),r.onCompleted.bind(r));return new E(o,s)})},f.takeUntilWithTime=function(t,e){e||(e=w);var n=this;return new p(function(r){return new E(e.scheduleWithAbsolute(t,function(){r.onCompleted()}),n.subscribe(r))})},n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/package.json b/ajax/libs/rxjs/package.json index c284b9b87..4a57c9519 100644 --- a/ajax/libs/rxjs/package.json +++ b/ajax/libs/rxjs/package.json @@ -3,7 +3,7 @@ "filename": "rx.min.js", "title": "Reactive Extensions for JavaScript (RxJS)", "description": "Library for composing asynchronous and event-based operations in JavaScript", - "version": "2.1.15", + "version": "2.1.18", "homepage": "http://rx.codeplex.com", "author": { "name": "Cloud Programmability Team",