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 pathfirst.js
72 lines (66 loc) · 2.24 KB
/
first.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
60
61
62
63
64
65
66
67
68
69
70
71
72
var FirstObservable = (function (__super__) {
inherits(FirstObservable, __super__);
function FirstObservable(source, obj) {
this.source = source;
this._obj = obj;
__super__.call(this);
}
FirstObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new FirstObserver(o, this._obj, this.source));
};
return FirstObservable;
}(ObservableBase));
var FirstObserver = (function(__super__) {
inherits(FirstObserver, __super__);
function FirstObserver(o, obj, s) {
this._o = o;
this._obj = obj;
this._s = s;
this._i = 0;
__super__.call(this);
}
FirstObserver.prototype.next = function (x) {
if (this._obj.predicate) {
var res = tryCatch(this._obj.predicate)(x, this._i++, this._s);
if (res === errorObj) { return this._o.onError(res.e); }
if (Boolean(res)) {
this._o.onNext(x);
this._o.onCompleted();
}
} else if (!this._obj.predicate) {
this._o.onNext(x);
this._o.onCompleted();
}
};
FirstObserver.prototype.error = function (e) { this._o.onError(e); };
FirstObserver.prototype.completed = function () {
if (this._obj.defaultValue === undefined) {
this._o.onError(new EmptyError());
} else {
this._o.onNext(this._obj.defaultValue);
this._o.onCompleted();
}
};
return FirstObserver;
}(AbstractObserver));
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.
* @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 () {
var obj = {}, source = this;
if (typeof arguments[0] === 'object') {
obj = arguments[0];
} else {
obj = {
predicate: arguments[0],
thisArg: arguments[1],
defaultValue: arguments[2]
};
}
if (isFunction (obj.predicate)) {
var fn = obj.predicate;
obj.predicate = bindCallback(fn, obj.thisArg, 3);
}
return new FirstObservable(this, obj);
};