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 pathsingle.js
70 lines (66 loc) · 2.28 KB
/
single.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
var SingleObserver = (function(__super__) {
inherits(SingleObserver, __super__);
function SingleObserver(o, obj, s) {
this._o = o;
this._obj = obj;
this._s = s;
this._i = 0;
this._hv = false;
this._v = null;
__super__.call(this);
}
SingleObserver.prototype.next = function (x) {
var shouldYield = false;
if (this._obj.predicate) {
var res = tryCatch(this._obj.predicate)(x, this._i++, this._s);
if (res === errorObj) { return this._o.onError(res.e); }
Boolean(res) && (shouldYield = true);
} else if (!this._obj.predicate) {
shouldYield = true;
}
if (shouldYield) {
if (this._hv) {
return this._o.onError(new Error('Sequence contains more than one matching element'));
}
this._hv = true;
this._v = x;
}
};
SingleObserver.prototype.error = function (e) { this._o.onError(e); };
SingleObserver.prototype.completed = function () {
if (this._hv) {
this._o.onNext(this._v);
this._o.onCompleted();
}
else if (this._obj.defaultValue === undefined) {
this._o.onError(new EmptyError());
} else {
this._o.onNext(this._obj.defaultValue);
this._o.onCompleted();
}
};
return SingleObserver;
}(AbstractObserver));
/**
* 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.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.single = function (predicate, thisArg) {
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 AnonymousObservable(function (o) {
return source.subscribe(new SingleObserver(o, obj, source));
}, source);
};