PageRenderTime 29ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/files/rxjs/3.1.1/rx.aggregates.js

https://gitlab.com/Mirros/jsdelivr
JavaScript | 864 lines | 656 code | 57 blank | 151 comment | 133 complexity | 59723824bcca0da79a725606ec499930 MD5 | raw file
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. ;(function (factory) {
  3. var objectTypes = {
  4. 'function': true,
  5. 'object': true
  6. };
  7. var
  8. freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
  9. freeSelf = objectTypes[typeof self] && self.Object && self,
  10. freeWindow = objectTypes[typeof window] && window && window.Object && window,
  11. freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
  12. moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
  13. freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global;
  14. var root = root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this;
  15. // Because of build optimizers
  16. if (typeof define === 'function' && define.amd) {
  17. define(['./rx'], function (Rx, exports) {
  18. return factory(root, exports, Rx);
  19. });
  20. } else if (typeof module === 'object' && module && module.exports === freeExports) {
  21. module.exports = factory(root, module.exports, require('./rx'));
  22. } else {
  23. root.Rx = factory(root, {}, root.Rx);
  24. }
  25. }.call(this, function (root, exp, Rx, undefined) {
  26. // References
  27. var Observable = Rx.Observable,
  28. observableProto = Observable.prototype,
  29. CompositeDisposable = Rx.CompositeDisposable,
  30. AnonymousObservable = Rx.AnonymousObservable,
  31. AbstractObserver = Rx.internals.AbstractObserver,
  32. disposableEmpty = Rx.Disposable.empty,
  33. isEqual = Rx.internals.isEqual,
  34. helpers = Rx.helpers,
  35. not = helpers.not,
  36. defaultComparer = helpers.defaultComparer,
  37. identity = helpers.identity,
  38. defaultSubComparer = helpers.defaultSubComparer,
  39. isFunction = helpers.isFunction,
  40. isPromise = helpers.isPromise,
  41. isArrayLike = helpers.isArrayLike,
  42. isIterable = helpers.isIterable,
  43. inherits = Rx.internals.inherits,
  44. observableFromPromise = Observable.fromPromise,
  45. observableFrom = Observable.from,
  46. bindCallback = Rx.internals.bindCallback,
  47. EmptyError = Rx.EmptyError,
  48. ObservableBase = Rx.ObservableBase,
  49. ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError;
  50. var errorObj = {e: {}};
  51. var tryCatchTarget;
  52. function tryCatcher() {
  53. try {
  54. return tryCatchTarget.apply(this, arguments);
  55. } catch (e) {
  56. errorObj.e = e;
  57. return errorObj;
  58. }
  59. }
  60. function tryCatch(fn) {
  61. if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
  62. tryCatchTarget = fn;
  63. return tryCatcher;
  64. }
  65. function thrower(e) {
  66. throw e;
  67. }
  68. function extremaBy(source, keySelector, comparer) {
  69. return new AnonymousObservable(function (o) {
  70. var hasValue = false, lastKey = null, list = [];
  71. return source.subscribe(function (x) {
  72. var comparison, key;
  73. try {
  74. key = keySelector(x);
  75. } catch (ex) {
  76. o.onError(ex);
  77. return;
  78. }
  79. comparison = 0;
  80. if (!hasValue) {
  81. hasValue = true;
  82. lastKey = key;
  83. } else {
  84. try {
  85. comparison = comparer(key, lastKey);
  86. } catch (ex1) {
  87. o.onError(ex1);
  88. return;
  89. }
  90. }
  91. if (comparison > 0) {
  92. lastKey = key;
  93. list = [];
  94. }
  95. if (comparison >= 0) { list.push(x); }
  96. }, function (e) { o.onError(e); }, function () {
  97. o.onNext(list);
  98. o.onCompleted();
  99. });
  100. }, source);
  101. }
  102. function firstOnly(x) {
  103. if (x.length === 0) { throw new EmptyError(); }
  104. return x[0];
  105. }
  106. var ReduceObservable = (function(__super__) {
  107. inherits(ReduceObservable, __super__);
  108. function ReduceObservable(source, acc, hasSeed, seed) {
  109. this.source = source;
  110. this.acc = acc;
  111. this.hasSeed = hasSeed;
  112. this.seed = seed;
  113. __super__.call(this);
  114. }
  115. ReduceObservable.prototype.subscribeCore = function(observer) {
  116. return this.source.subscribe(new InnerObserver(observer,this));
  117. };
  118. function InnerObserver(o, parent) {
  119. this.o = o;
  120. this.acc = parent.acc;
  121. this.hasSeed = parent.hasSeed;
  122. this.seed = parent.seed;
  123. this.hasAccumulation = false;
  124. this.result = null;
  125. this.hasValue = false;
  126. this.isStopped = false;
  127. }
  128. InnerObserver.prototype.onNext = function (x) {
  129. if (this.isStopped) { return; }
  130. !this.hasValue && (this.hasValue = true);
  131. if (this.hasAccumulation) {
  132. this.result = tryCatch(this.acc)(this.result, x);
  133. } else {
  134. this.result = this.hasSeed ? tryCatch(this.acc)(this.seed, x) : x;
  135. this.hasAccumulation = true;
  136. }
  137. if (this.result === errorObj) { this.o.onError(this.result.e); }
  138. };
  139. InnerObserver.prototype.onError = function (e) {
  140. if (!this.isStopped) { this.isStopped = true; this.o.onError(e); }
  141. };
  142. InnerObserver.prototype.onCompleted = function () {
  143. if (!this.isStopped) {
  144. this.isStopped = true;
  145. this.hasValue && this.o.onNext(this.result);
  146. !this.hasValue && this.hasSeed && this.o.onNext(this.seed);
  147. !this.hasValue && !this.hasSeed && this.o.onError(new EmptyError());
  148. this.o.onCompleted();
  149. }
  150. };
  151. InnerObserver.prototype.dispose = function () { this.isStopped = true; };
  152. InnerObserver.prototype.fail = function(e) {
  153. if (!this.isStopped) {
  154. this.isStopped = true;
  155. this.o.onError(e);
  156. return true;
  157. }
  158. return false;
  159. };
  160. return ReduceObservable;
  161. }(ObservableBase));
  162. /**
  163. * 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.
  164. * For aggregation behavior with incremental intermediate results, see Observable.scan.
  165. * @param {Function} accumulator An accumulator function to be invoked on each element.
  166. * @param {Any} [seed] The initial accumulator value.
  167. * @returns {Observable} An observable sequence containing a single element with the final accumulator value.
  168. */
  169. observableProto.reduce = function (accumulator) {
  170. var hasSeed = false;
  171. if (arguments.length === 2) {
  172. hasSeed = true;
  173. var seed = arguments[1];
  174. }
  175. return new ReduceObservable(this, accumulator, hasSeed, seed);
  176. };
  177. var SomeObserver = (function (__super__) {
  178. inherits(SomeObserver, __super__);
  179. function SomeObserver(o, fn, s) {
  180. this._o = o;
  181. this._fn = fn;
  182. this._s = s;
  183. this._i = 0;
  184. __super__.call(this);
  185. }
  186. SomeObserver.prototype.next = function (x) {
  187. var result = tryCatch(this._fn)(x, this._i++, this._s);
  188. if (result === errorObj) { return this._o.onError(result.e); }
  189. if (Boolean(result)) {
  190. this._o.onNext(true);
  191. this._o.onCompleted();
  192. }
  193. };
  194. SomeObserver.prototype.error = function (e) { this._o.onError(e); };
  195. SomeObserver.prototype.completed = function () {
  196. this._o.onNext(false);
  197. this._o.onCompleted();
  198. };
  199. return SomeObserver;
  200. }(AbstractObserver));
  201. /**
  202. * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.
  203. * @param {Function} [predicate] A function to test each element for a condition.
  204. * @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.
  205. */
  206. observableProto.some = function (predicate, thisArg) {
  207. var source = this, fn = bindCallback(predicate, thisArg, 3);
  208. return new AnonymousObservable(function (o) {
  209. return source.subscribe(new SomeObserver(o, fn, source));
  210. });
  211. };
  212. var IsEmptyObserver = (function(__super__) {
  213. inherits(IsEmptyObserver, __super__);
  214. function IsEmptyObserver(o) {
  215. this._o = o;
  216. __super__.call(this);
  217. }
  218. IsEmptyObserver.prototype.next = function () {
  219. this._o.onNext(false);
  220. this._o.onCompleted();
  221. };
  222. IsEmptyObserver.prototype.error = function (e) { this._o.onError(e); };
  223. IsEmptyObserver.prototype.completed = function () {
  224. this._o.onNext(true);
  225. this._o.onCompleted();
  226. };
  227. return IsEmptyObserver;
  228. }(AbstractObserver));
  229. /**
  230. * Determines whether an observable sequence is empty.
  231. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.
  232. */
  233. observableProto.isEmpty = function () {
  234. var source = this;
  235. return new AnonymousObservable(function (o) {
  236. return source.subscribe(new IsEmptyObserver(o));
  237. }, source);
  238. };
  239. var EveryObserver = (function (__super__) {
  240. inherits(EveryObserver, __super__);
  241. function EveryObserver(o, fn, s) {
  242. this._o = o;
  243. this._fn = fn;
  244. this._s = s;
  245. this._i = 0;
  246. __super__.call(this);
  247. }
  248. EveryObserver.prototype.next = function (x) {
  249. var result = tryCatch(this._fn)(x, this._i++, this._s);
  250. if (result === errorObj) { return this._o.onError(result.e); }
  251. if (!Boolean(result)) {
  252. this._o.onNext(false);
  253. this._o.onCompleted();
  254. }
  255. };
  256. EveryObserver.prototype.error = function (e) { this._o.onError(e); };
  257. EveryObserver.prototype.completed = function () {
  258. this._o.onNext(true);
  259. this._o.onCompleted();
  260. };
  261. return EveryObserver;
  262. }(AbstractObserver));
  263. /**
  264. * Determines whether all elements of an observable sequence satisfy a condition.
  265. * @param {Function} [predicate] A function to test each element for a condition.
  266. * @param {Any} [thisArg] Object to use as this when executing callback.
  267. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.
  268. */
  269. observableProto.every = function (predicate, thisArg) {
  270. var source = this, fn = bindCallback(predicate, thisArg, 3);
  271. return new AnonymousObservable(function (o) {
  272. return source.subscribe(new EveryObserver(o, fn, source));
  273. }, this);
  274. };
  275. /**
  276. * Determines whether an observable sequence includes a specified element with an optional equality comparer.
  277. * @param searchElement The value to locate in the source sequence.
  278. * @param {Number} [fromIndex] An equality comparer to compare elements.
  279. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index.
  280. */
  281. observableProto.includes = function (searchElement, fromIndex) {
  282. var source = this;
  283. function comparer(a, b) {
  284. return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b)));
  285. }
  286. return new AnonymousObservable(function (o) {
  287. var i = 0, n = +fromIndex || 0;
  288. Math.abs(n) === Infinity && (n = 0);
  289. if (n < 0) {
  290. o.onNext(false);
  291. o.onCompleted();
  292. return disposableEmpty;
  293. }
  294. return source.subscribe(
  295. function (x) {
  296. if (i++ >= n && comparer(x, searchElement)) {
  297. o.onNext(true);
  298. o.onCompleted();
  299. }
  300. },
  301. function (e) { o.onError(e); },
  302. function () {
  303. o.onNext(false);
  304. o.onCompleted();
  305. });
  306. }, this);
  307. };
  308. /**
  309. * @deprecated use #includes instead.
  310. */
  311. observableProto.contains = function (searchElement, fromIndex) {
  312. //deprecate('contains', 'includes');
  313. observableProto.includes(searchElement, fromIndex);
  314. };
  315. /**
  316. * 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.
  317. * @example
  318. * res = source.count();
  319. * res = source.count(function (x) { return x > 3; });
  320. * @param {Function} [predicate]A function to test each element for a condition.
  321. * @param {Any} [thisArg] Object to use as this when executing callback.
  322. * @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.
  323. */
  324. observableProto.count = function (predicate, thisArg) {
  325. return predicate ?
  326. this.filter(predicate, thisArg).count() :
  327. this.reduce(function (count) { return count + 1; }, 0);
  328. };
  329. /**
  330. * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
  331. * @param {Any} searchElement Element to locate in the array.
  332. * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0.
  333. * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
  334. */
  335. observableProto.indexOf = function(searchElement, fromIndex) {
  336. var source = this;
  337. return new AnonymousObservable(function (o) {
  338. var i = 0, n = +fromIndex || 0;
  339. Math.abs(n) === Infinity && (n = 0);
  340. if (n < 0) {
  341. o.onNext(-1);
  342. o.onCompleted();
  343. return disposableEmpty;
  344. }
  345. return source.subscribe(
  346. function (x) {
  347. if (i >= n && x === searchElement) {
  348. o.onNext(i);
  349. o.onCompleted();
  350. }
  351. i++;
  352. },
  353. function (e) { o.onError(e); },
  354. function () {
  355. o.onNext(-1);
  356. o.onCompleted();
  357. });
  358. }, source);
  359. };
  360. /**
  361. * 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.
  362. * @param {Function} [selector] A transform function to apply to each element.
  363. * @param {Any} [thisArg] Object to use as this when executing callback.
  364. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.
  365. */
  366. observableProto.sum = function (keySelector, thisArg) {
  367. return keySelector && isFunction(keySelector) ?
  368. this.map(keySelector, thisArg).sum() :
  369. this.reduce(function (prev, curr) { return prev + curr; }, 0);
  370. };
  371. /**
  372. * Returns the elements in an observable sequence with the minimum key value according to the specified comparer.
  373. * @example
  374. * var res = source.minBy(function (x) { return x.value; });
  375. * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });
  376. * @param {Function} keySelector Key selector function.
  377. * @param {Function} [comparer] Comparer used to compare key values.
  378. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.
  379. */
  380. observableProto.minBy = function (keySelector, comparer) {
  381. comparer || (comparer = defaultSubComparer);
  382. return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; });
  383. };
  384. /**
  385. * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.
  386. * @example
  387. * var res = source.min();
  388. * var res = source.min(function (x, y) { return x.value - y.value; });
  389. * @param {Function} [comparer] Comparer used to compare elements.
  390. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.
  391. */
  392. observableProto.min = function (comparer) {
  393. return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); });
  394. };
  395. /**
  396. * Returns the elements in an observable sequence with the maximum key value according to the specified comparer.
  397. * @example
  398. * var res = source.maxBy(function (x) { return x.value; });
  399. * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });
  400. * @param {Function} keySelector Key selector function.
  401. * @param {Function} [comparer] Comparer used to compare key values.
  402. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.
  403. */
  404. observableProto.maxBy = function (keySelector, comparer) {
  405. comparer || (comparer = defaultSubComparer);
  406. return extremaBy(this, keySelector, comparer);
  407. };
  408. /**
  409. * Returns the maximum value in an observable sequence according to the specified comparer.
  410. * @example
  411. * var res = source.max();
  412. * var res = source.max(function (x, y) { return x.value - y.value; });
  413. * @param {Function} [comparer] Comparer used to compare elements.
  414. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.
  415. */
  416. observableProto.max = function (comparer) {
  417. return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); });
  418. };
  419. var AverageObserver = (function(__super__) {
  420. inherits(AverageObserver, __super__);
  421. function AverageObserver(o, fn, s) {
  422. this._o = o;
  423. this._fn = fn;
  424. this._s = s;
  425. this._c = 0;
  426. this._t = 0;
  427. __super__.call(this);
  428. }
  429. AverageObserver.prototype.next = function (x) {
  430. if(this._fn) {
  431. var r = tryCatch(this._fn)(x, this._c++, this._s);
  432. if (r === errorObj) { return this._o.onError(r.e); }
  433. this._t += r;
  434. } else {
  435. this._c++;
  436. this._t += x;
  437. }
  438. };
  439. AverageObserver.prototype.error = function (e) { this._o.onError(e); };
  440. AverageObserver.prototype.completed = function () {
  441. if (this._c === 0) { return this._o.onError(new EmptyError()); }
  442. this._o.onNext(this._t / this._c);
  443. this._o.onCompleted();
  444. };
  445. return AverageObserver;
  446. }(AbstractObserver));
  447. /**
  448. * 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.
  449. * @param {Function} [selector] A transform function to apply to each element.
  450. * @param {Any} [thisArg] Object to use as this when executing callback.
  451. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.
  452. */
  453. observableProto.average = function (keySelector, thisArg) {
  454. var source = this, fn;
  455. if (isFunction(keySelector)) {
  456. fn = bindCallback(keySelector, thisArg, 3);
  457. }
  458. return new AnonymousObservable(function (o) {
  459. return source.subscribe(new AverageObserver(o, fn, source));
  460. }, source);
  461. };
  462. /**
  463. * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.
  464. *
  465. * @example
  466. * var res = res = source.sequenceEqual([1,2,3]);
  467. * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });
  468. * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));
  469. * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });
  470. * @param {Observable} second Second observable sequence or array to compare.
  471. * @param {Function} [comparer] Comparer used to compare elements of both sequences.
  472. * @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.
  473. */
  474. observableProto.sequenceEqual = function (second, comparer) {
  475. var first = this;
  476. comparer || (comparer = defaultComparer);
  477. return new AnonymousObservable(function (o) {
  478. var donel = false, doner = false, ql = [], qr = [];
  479. var subscription1 = first.subscribe(function (x) {
  480. var equal, v;
  481. if (qr.length > 0) {
  482. v = qr.shift();
  483. try {
  484. equal = comparer(v, x);
  485. } catch (e) {
  486. o.onError(e);
  487. return;
  488. }
  489. if (!equal) {
  490. o.onNext(false);
  491. o.onCompleted();
  492. }
  493. } else if (doner) {
  494. o.onNext(false);
  495. o.onCompleted();
  496. } else {
  497. ql.push(x);
  498. }
  499. }, function(e) { o.onError(e); }, function () {
  500. donel = true;
  501. if (ql.length === 0) {
  502. if (qr.length > 0) {
  503. o.onNext(false);
  504. o.onCompleted();
  505. } else if (doner) {
  506. o.onNext(true);
  507. o.onCompleted();
  508. }
  509. }
  510. });
  511. (isArrayLike(second) || isIterable(second)) && (second = observableFrom(second));
  512. isPromise(second) && (second = observableFromPromise(second));
  513. var subscription2 = second.subscribe(function (x) {
  514. var equal;
  515. if (ql.length > 0) {
  516. var v = ql.shift();
  517. try {
  518. equal = comparer(v, x);
  519. } catch (exception) {
  520. o.onError(exception);
  521. return;
  522. }
  523. if (!equal) {
  524. o.onNext(false);
  525. o.onCompleted();
  526. }
  527. } else if (donel) {
  528. o.onNext(false);
  529. o.onCompleted();
  530. } else {
  531. qr.push(x);
  532. }
  533. }, function(e) { o.onError(e); }, function () {
  534. doner = true;
  535. if (qr.length === 0) {
  536. if (ql.length > 0) {
  537. o.onNext(false);
  538. o.onCompleted();
  539. } else if (donel) {
  540. o.onNext(true);
  541. o.onCompleted();
  542. }
  543. }
  544. });
  545. return new CompositeDisposable(subscription1, subscription2);
  546. }, first);
  547. };
  548. /**
  549. * Returns the element at a specified index in a sequence or default value if not found.
  550. * @param {Number} index The zero-based index of the element to retrieve.
  551. * @param {Any} [defaultValue] The default value to use if elementAt does not find a value.
  552. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.
  553. */
  554. observableProto.elementAt = function (index, defaultValue) {
  555. if (index < 0) { throw new ArgumentOutOfRangeError(); }
  556. var source = this;
  557. return new AnonymousObservable(function (o) {
  558. var i = index;
  559. return source.subscribe(
  560. function (x) {
  561. if (i-- === 0) {
  562. o.onNext(x);
  563. o.onCompleted();
  564. }
  565. },
  566. function (e) { o.onError(e); },
  567. function () {
  568. if (defaultValue === undefined) {
  569. o.onError(new ArgumentOutOfRangeError());
  570. } else {
  571. o.onNext(defaultValue);
  572. o.onCompleted();
  573. }
  574. });
  575. }, source);
  576. };
  577. /**
  578. * 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.
  579. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
  580. * @param {Any} [thisArg] Object to use as `this` when executing the predicate.
  581. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.
  582. */
  583. observableProto.single = function (predicate, thisArg) {
  584. if (isFunction(predicate)) { return this.filter(predicate, thisArg).single(); }
  585. var source = this;
  586. return new AnonymousObservable(function (o) {
  587. var value, seenValue = false;
  588. return source.subscribe(function (x) {
  589. if (seenValue) {
  590. o.onError(new Error('Sequence contains more than one element'));
  591. } else {
  592. value = x;
  593. seenValue = true;
  594. }
  595. }, function (e) { o.onError(e); }, function () {
  596. o.onNext(value);
  597. o.onCompleted();
  598. });
  599. }, source);
  600. };
  601. var FirstObserver = (function(__super__) {
  602. inherits(FirstObserver, __super__);
  603. function FirstObserver(o, obj, s) {
  604. this._o = o;
  605. this._obj = obj;
  606. this._s = s;
  607. this._i = 0;
  608. __super__.call(this);
  609. }
  610. FirstObserver.prototype.next = function (x) {
  611. if (this._obj.predicate) {
  612. var res = tryCatch(this._obj.predicate)(x, this._i++, this._s);
  613. if (res === errorObj) { return this._o.onError(res.e); }
  614. if (Boolean(res)) {
  615. this._o.onNext(x);
  616. this._o.onCompleted();
  617. }
  618. } else if (!this._obj.predicate) {
  619. this._o.onNext(x);
  620. this._o.onCompleted();
  621. }
  622. };
  623. FirstObserver.prototype.error = function (e) { this._o.onError(e); };
  624. FirstObserver.prototype.completed = function () {
  625. if (this._obj.defaultValue === undefined) {
  626. this._o.onError(new EmptyError());
  627. } else {
  628. this._o.onNext(this._obj.defaultValue);
  629. this._o.onCompleted();
  630. }
  631. };
  632. return FirstObserver;
  633. }(AbstractObserver));
  634. /**
  635. * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.
  636. * @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.
  637. */
  638. observableProto.first = function () {
  639. var obj = {}, source = this;
  640. if (typeof arguments[0] === 'object') {
  641. obj = arguments[0];
  642. } else {
  643. obj = {
  644. predicate: arguments[0],
  645. thisArg: arguments[1],
  646. defaultValue: arguments[2]
  647. };
  648. }
  649. if (isFunction (obj.predicate)) {
  650. var fn = obj.predicate;
  651. obj.predicate = bindCallback(fn, obj.thisArg, 3);
  652. }
  653. return new AnonymousObservable(function (o) {
  654. return source.subscribe(new FirstObserver(o, obj, source));
  655. }, source);
  656. };
  657. /**
  658. * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.
  659. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.
  660. */
  661. observableProto.last = function () {
  662. var obj = {}, source = this;
  663. if (typeof arguments[0] === 'object') {
  664. obj = arguments[0];
  665. } else {
  666. obj = {
  667. predicate: arguments[0],
  668. thisArg: arguments[1],
  669. defaultValue: arguments[2]
  670. };
  671. }
  672. if (isFunction (obj.predicate)) {
  673. var fn = obj.predicate;
  674. obj.predicate = bindCallback(fn, obj.thisArg, 3);
  675. }
  676. return new AnonymousObservable(function (o) {
  677. var value, seenValue = false, i = 0;
  678. return source.subscribe(
  679. function (x) {
  680. if (obj.predicate) {
  681. var res = tryCatch(obj.predicate)(x, i++, source);
  682. if (res === errorObj) { return o.onError(res.e); }
  683. if (res) {
  684. seenValue = true;
  685. value = x;
  686. }
  687. } else if (!obj.predicate) {
  688. seenValue = true;
  689. value = x;
  690. }
  691. },
  692. function (e) { o.onError(e); },
  693. function () {
  694. if (seenValue) {
  695. o.onNext(value);
  696. o.onCompleted();
  697. }
  698. else if (obj.defaultValue === undefined) {
  699. o.onError(new EmptyError());
  700. } else {
  701. o.onNext(obj.defaultValue);
  702. o.onCompleted();
  703. }
  704. });
  705. }, source);
  706. };
  707. function findValue (source, predicate, thisArg, yieldIndex) {
  708. var callback = bindCallback(predicate, thisArg, 3);
  709. return new AnonymousObservable(function (o) {
  710. var i = 0;
  711. return source.subscribe(function (x) {
  712. var shouldRun;
  713. try {
  714. shouldRun = callback(x, i, source);
  715. } catch (e) {
  716. o.onError(e);
  717. return;
  718. }
  719. if (shouldRun) {
  720. o.onNext(yieldIndex ? i : x);
  721. o.onCompleted();
  722. } else {
  723. i++;
  724. }
  725. }, function (e) { o.onError(e); }, function () {
  726. o.onNext(yieldIndex ? -1 : undefined);
  727. o.onCompleted();
  728. });
  729. }, source);
  730. }
  731. /**
  732. * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.
  733. * @param {Function} predicate The predicate that defines the conditions of the element to search for.
  734. * @param {Any} [thisArg] Object to use as `this` when executing the predicate.
  735. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.
  736. */
  737. observableProto.find = function (predicate, thisArg) {
  738. return findValue(this, predicate, thisArg, false);
  739. };
  740. /**
  741. * Searches for an element that matches the conditions defined by the specified predicate, and returns
  742. * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence.
  743. * @param {Function} predicate The predicate that defines the conditions of the element to search for.
  744. * @param {Any} [thisArg] Object to use as `this` when executing the predicate.
  745. * @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.
  746. */
  747. observableProto.findIndex = function (predicate, thisArg) {
  748. return findValue(this, predicate, thisArg, true);
  749. };
  750. /**
  751. * Converts the observable sequence to a Set if it exists.
  752. * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence.
  753. */
  754. observableProto.toSet = function () {
  755. if (typeof root.Set === 'undefined') { throw new TypeError(); }
  756. var source = this;
  757. return new AnonymousObservable(function (o) {
  758. var s = new root.Set();
  759. return source.subscribe(
  760. function (x) { s.add(x); },
  761. function (e) { o.onError(e); },
  762. function () {
  763. o.onNext(s);
  764. o.onCompleted();
  765. });
  766. }, source);
  767. };
  768. /**
  769. * Converts the observable sequence to a Map if it exists.
  770. * @param {Function} keySelector A function which produces the key for the Map.
  771. * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence.
  772. * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence.
  773. */
  774. observableProto.toMap = function (keySelector, elementSelector) {
  775. if (typeof root.Map === 'undefined') { throw new TypeError(); }
  776. var source = this;
  777. return new AnonymousObservable(function (o) {
  778. var m = new root.Map();
  779. return source.subscribe(
  780. function (x) {
  781. var key;
  782. try {
  783. key = keySelector(x);
  784. } catch (e) {
  785. o.onError(e);
  786. return;
  787. }
  788. var element = x;
  789. if (elementSelector) {
  790. try {
  791. element = elementSelector(x);
  792. } catch (e) {
  793. o.onError(e);
  794. return;
  795. }
  796. }
  797. m.set(key, element);
  798. },
  799. function (e) { o.onError(e); },
  800. function () {
  801. o.onNext(m);
  802. o.onCompleted();
  803. });
  804. }, source);
  805. };
  806. return Rx;
  807. }));