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 pathaverage.js
59 lines (53 loc) · 1.97 KB
/
average.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
56
57
58
59
var AverageObservable = (function (__super__) {
inherits(AverageObservable, __super__);
function AverageObservable(source, fn) {
this.source = source;
this._fn = fn;
__super__.call(this);
}
AverageObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new AverageObserver(o, this._fn, this.source));
};
return AverageObservable;
}(ObservableBase));
var AverageObserver = (function(__super__) {
inherits(AverageObserver, __super__);
function AverageObserver(o, fn, s) {
this._o = o;
this._fn = fn;
this._s = s;
this._c = 0;
this._t = 0;
__super__.call(this);
}
AverageObserver.prototype.next = function (x) {
if(this._fn) {
var r = tryCatch(this._fn)(x, this._c++, this._s);
if (r === errorObj) { return this._o.onError(r.e); }
this._t += r;
} else {
this._c++;
this._t += x;
}
};
AverageObserver.prototype.error = function (e) { this._o.onError(e); };
AverageObserver.prototype.completed = function () {
if (this._c === 0) { return this._o.onError(new EmptyError()); }
this._o.onNext(this._t / this._c);
this._o.onCompleted();
};
return AverageObserver;
}(AbstractObserver));
/**
* 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.
* @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) {
var source = this, fn;
if (isFunction(keySelector)) {
fn = bindCallback(keySelector, thisArg, 3);
}
return new AverageObservable(source, fn);
};