This repository was archived by the owner on Apr 20, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathsum.js
55 lines (48 loc) · 1.81 KB
/
sum.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
var SumObservable = (function (__super__) {
inherits(SumObservable, __super__);
function SumObservable(source, fn) {
this.source = source;
this._fn = fn;
__super__.call(this);
}
SumObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new SumObserver(o, this._fn, this.source));
};
return SumObservable;
}(ObservableBase));
var SumObserver = (function (__super__) {
inherits(SumObserver, __super__);
function SumObserver(o, fn, s) {
this._o = o;
this._fn = fn;
this._s = s;
this._i = 0;
this._c = 0;
__super__.call(this);
}
SumObserver.prototype.next = function (x) {
if (this._fn) {
var result = tryCatch(this._fn)(x, this._i++, this._s);
if (result === errorObj) { return this._o.onError(result.e); }
this._c += result;
} else {
this._c += x;
}
};
SumObserver.prototype.error = function (e) { this._o.onError(e); };
SumObserver.prototype.completed = function () {
this._o.onNext(this._c);
this._o.onCompleted();
};
return SumObserver;
}(AbstractObserver));
/**
* 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.
* @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) {
var fn = bindCallback(keySelector, thisArg, 3);
return new SumObservable(this, fn);
};