rx.core.testing.js
40.1 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information.
;(function (factory) {
var objectTypes = {
'function': true,
'object': true
};
function checkGlobal(value) {
return (value && value.Object === Object) ? value : null;
}
var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null;
var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null;
var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global);
var freeSelf = checkGlobal(objectTypes[typeof self] && self);
var freeWindow = checkGlobal(objectTypes[typeof window] && window);
var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null;
var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')();
// Because of build optimizers
if (typeof define === 'function' && define.amd) {
define(['./rx.core'], function (Rx, exports) {
return factory(root, exports, Rx);
});
} else if (typeof module === 'object' && module && module.exports === freeExports) {
module.exports = factory(root, module.exports, require('./rx.core'));
} else {
root.Rx = factory(root, {}, root.Rx);
}
}.call(this, function (root, exp, Rx, undefined) {
// Defaults
var Observer = Rx.Observer,
Observable = Rx.Observable,
Disposable = Rx.Disposable,
disposableEmpty = Disposable.empty,
disposableCreate = Disposable.create,
CompositeDisposable = Rx.CompositeDisposable,
SingleAssignmentDisposable = Rx.SingleAssignmentDisposable,
Scheduler = Rx.Scheduler,
ScheduledItem = Rx.internals.ScheduledItem,
SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive,
PriorityQueue = Rx.internals.PriorityQueue,
inherits = Rx.internals.inherits,
notImplemented = Rx.helpers.notImplemented,
defaultComparer = Rx.helpers.defaultComparer = function (a, b) { return isEqual(a, b); };
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification() {
}
Notification.prototype._accept = function (onNext, onError, onCompleted) {
throw new NotImplementedError();
};
Notification.prototype._acceptObserver = function (onNext, onError, onCompleted) {
throw new NotImplementedError();
};
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
* @param {Function | Observer} observerOrOnNext Function to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Function to invoke for an OnError notification.
* @param {Function} onCompleted Function to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObserver(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var self = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (o) {
return scheduler.schedule(self, function (_, notification) {
notification._acceptObserver(o);
notification.kind === 'N' && o.onCompleted();
});
});
};
return Notification;
})();
var OnNextNotification = (function (__super__) {
inherits(OnNextNotification, __super__);
function OnNextNotification(value) {
this.value = value;
this.kind = 'N';
}
OnNextNotification.prototype._accept = function (onNext) {
return onNext(this.value);
};
OnNextNotification.prototype._acceptObserver = function (o) {
return o.onNext(this.value);
};
OnNextNotification.prototype.toString = function () {
return 'OnNext(' + this.value + ')';
};
return OnNextNotification;
}(Notification));
var OnErrorNotification = (function (__super__) {
inherits(OnErrorNotification, __super__);
function OnErrorNotification(error) {
this.error = error;
this.kind = 'E';
}
OnErrorNotification.prototype._accept = function (onNext, onError) {
return onError(this.error);
};
OnErrorNotification.prototype._acceptObserver = function (o) {
return o.onError(this.error);
};
OnErrorNotification.prototype.toString = function () {
return 'OnError(' + this.error + ')';
};
return OnErrorNotification;
}(Notification));
var OnCompletedNotification = (function (__super__) {
inherits(OnCompletedNotification, __super__);
function OnCompletedNotification() {
this.kind = 'C';
}
OnCompletedNotification.prototype._accept = function (onNext, onError, onCompleted) {
return onCompleted();
};
OnCompletedNotification.prototype._acceptObserver = function (o) {
return o.onCompleted();
};
OnCompletedNotification.prototype.toString = function () {
return 'OnCompleted()';
};
return OnCompletedNotification;
}(Notification));
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = function (value) {
return new OnNextNotification(value);
};
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = function (error) {
return new OnErrorNotification(error);
};
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = function () {
return new OnCompletedNotification();
};
/** Used to determine if values are of the language type Object */
var dontEnums = ['toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'],
dontEnumsLength = dontEnums.length;
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dateTag] = typedArrayTags[errorTag] =
typedArrayTags[funcTag] = typedArrayTags[mapTag] =
typedArrayTags[numberTag] = typedArrayTags[objectTag] =
typedArrayTags[regexpTag] = typedArrayTags[setTag] =
typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
var objectProto = Object.prototype,
hasOwnProperty = objectProto.hasOwnProperty,
objToString = objectProto.toString,
MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
var keys = Object.keys || (function() {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function(obj) {
if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
throw new TypeError('Object.keys called on non-object');
}
var result = [], prop, i;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
}());
function equalObjects(object, other, equalFunc, isLoose, stackA, stackB) {
var objProps = keys(object),
objLength = objProps.length,
othProps = keys(other),
othLength = othProps.length;
if (objLength !== othLength && !isLoose) {
return false;
}
var index = objLength, key;
while (index--) {
key = objProps[index];
if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
var skipCtor = isLoose;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key],
result;
if (!(result === undefined ? equalFunc(objValue, othValue, isLoose, stackA, stackB) : result)) {
return false;
}
skipCtor || (skipCtor = key === 'constructor');
}
if (!skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
if (objCtor !== othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor === 'function' && objCtor instanceof objCtor &&
typeof othCtor === 'function' && othCtor instanceof othCtor)) {
return false;
}
}
return true;
}
function equalByTag(object, other, tag) {
switch (tag) {
case boolTag:
case dateTag:
return +object === +other;
case errorTag:
return object.name === other.name && object.message === other.message;
case numberTag:
return (object !== +object) ?
other !== +other :
object === +other;
case regexpTag:
case stringTag:
return object === (other + '');
}
return false;
}
var isObject = Rx.internals.isObject = function(value) {
var type = typeof value;
return !!value && (type === 'object' || type === 'function');
};
function isObjectLike(value) {
return !!value && typeof value === 'object';
}
function isLength(value) {
return typeof value === 'number' && value > -1 && value % 1 === 0 && value <= MAX_SAFE_INTEGER;
}
var isHostObject = (function() {
try {
Object({ 'toString': 0 } + '');
} catch(e) {
return function() { return false; };
}
return function(value) {
return typeof value.toString !== 'function' && typeof (value + '') === 'string';
};
}());
function isTypedArray(value) {
return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
}
var isArray = Array.isArray || function(value) {
return isObjectLike(value) && isLength(value.length) && objToString.call(value) === arrayTag;
};
function arraySome (array, predicate) {
var index = -1,
length = array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
function equalArrays(array, other, equalFunc, isLoose, stackA, stackB) {
var index = -1,
arrLength = array.length,
othLength = other.length;
if (arrLength !== othLength && !(isLoose && othLength > arrLength)) {
return false;
}
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index],
result;
if (result !== undefined) {
if (result) {
continue;
}
return false;
}
// Recursively compare arrays (susceptible to call stack limits).
if (isLoose) {
if (!arraySome(other, function(othValue) {
return arrValue === othValue || equalFunc(arrValue, othValue, isLoose, stackA, stackB);
})) {
return false;
}
} else if (!(arrValue === othValue || equalFunc(arrValue, othValue, isLoose, stackA, stackB))) {
return false;
}
}
return true;
}
function baseIsEqualDeep(object, other, equalFunc, isLoose, stackA, stackB) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = arrayTag,
othTag = arrayTag;
if (!objIsArr) {
objTag = objToString.call(object);
if (objTag === argsTag) {
objTag = objectTag;
} else if (objTag !== objectTag) {
objIsArr = isTypedArray(object);
}
}
if (!othIsArr) {
othTag = objToString.call(other);
if (othTag === argsTag) {
othTag = objectTag;
}
}
var objIsObj = objTag === objectTag && !isHostObject(object),
othIsObj = othTag === objectTag && !isHostObject(other),
isSameTag = objTag === othTag;
if (isSameTag && !(objIsArr || objIsObj)) {
return equalByTag(object, other, objTag);
}
if (!isLoose) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, isLoose, stackA, stackB);
}
}
if (!isSameTag) {
return false;
}
// Assume cyclic values are equal.
// For more information on detecting circular references see https://es5.github.io/#JO.
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] === object) {
return stackB[length] === other;
}
}
// Add `object` and `other` to the stack of traversed objects.
stackA.push(object);
stackB.push(other);
var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, isLoose, stackA, stackB);
stackA.pop();
stackB.pop();
return result;
}
function baseIsEqual(value, other, isLoose, stackA, stackB) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, baseIsEqual, isLoose, stackA, stackB);
}
var isEqual = Rx.internals.isEqual = function (value, other) {
return baseIsEqual(value, other);
};
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function createTick(self) {
return function tick(command, recurse) {
recurse(0, self._period);
var state = tryCatch(self._action)(self._state);
if (state === errorObj) {
self._cancel.dispose();
thrower(state.e);
}
self._state = state;
};
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveFuture(0, this._period, createTick(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/** Provides a set of extension methods for virtual time scheduling. */
var VirtualTimeScheduler = Rx.VirtualTimeScheduler = (function (__super__) {
inherits(VirtualTimeScheduler, __super__);
/**
* Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer.
*
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function VirtualTimeScheduler(initialClock, comparer) {
this.clock = initialClock;
this.comparer = comparer;
this.isEnabled = false;
this.queue = new PriorityQueue(1024);
__super__.call(this);
}
var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype;
VirtualTimeSchedulerPrototype.now = function () {
return this.toAbsoluteTime(this.clock);
};
VirtualTimeSchedulerPrototype.schedule = function (state, action) {
return this.scheduleAbsolute(state, this.clock, action);
};
VirtualTimeSchedulerPrototype.scheduleFuture = function (state, dueTime, action) {
var dt = dueTime instanceof Date ?
this.toRelativeTime(dueTime - this.now()) :
this.toRelativeTime(dueTime);
return this.scheduleRelative(state, dt, action);
};
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
VirtualTimeSchedulerPrototype.add = notImplemented;
/**
* Converts an absolute time to a number
* @param {Any} The absolute time.
* @returns {Number} The absolute time in ms
*/
VirtualTimeSchedulerPrototype.toAbsoluteTime = notImplemented;
/**
* Converts the TimeSpan value to a relative virtual time value.
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
VirtualTimeSchedulerPrototype.toRelativeTime = notImplemented;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
VirtualTimeSchedulerPrototype.schedulePeriodic = function (state, period, action) {
var s = new SchedulePeriodicRecursive(this, state, period, action);
return s.start();
};
/**
* Schedules an action to be executed after dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelative = function (state, dueTime, action) {
var runAt = this.add(this.clock, dueTime);
return this.scheduleAbsolute(state, runAt, action);
};
/**
* Starts the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.start = function () {
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null) {
this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
}
};
/**
* Stops the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.stop = function () {
this.isEnabled = false;
};
/**
* Advances the scheduler's clock to the specified time, running all work till that point.
* @param {Number} time Absolute time to advance the scheduler's clock to.
*/
VirtualTimeSchedulerPrototype.advanceTo = function (time) {
var dueToClock = this.comparer(this.clock, time);
if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); }
if (dueToClock === 0) { return; }
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null && this.comparer(next.dueTime, time) <= 0) {
this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
this.clock = time;
}
};
/**
* Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.advanceBy = function (time) {
var dt = this.add(this.clock, time),
dueToClock = this.comparer(this.clock, dt);
if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); }
if (dueToClock === 0) { return; }
this.advanceTo(dt);
};
/**
* Advances the scheduler's clock by the specified relative time.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.sleep = function (time) {
var dt = this.add(this.clock, time);
if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); }
this.clock = dt;
};
/**
* Gets the next scheduled item to be executed.
* @returns {ScheduledItem} The next scheduled item.
*/
VirtualTimeSchedulerPrototype.getNext = function () {
while (this.queue.length > 0) {
var next = this.queue.peek();
if (next.isCancelled()) {
this.queue.dequeue();
} else {
return next;
}
}
return null;
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsolute = function (state, dueTime, action) {
var self = this;
function run(scheduler, state1) {
self.queue.remove(si);
return action(scheduler, state1);
}
var si = new ScheduledItem(this, state, run, dueTime, this.comparer);
this.queue.enqueue(si);
return si.disposable;
};
return VirtualTimeScheduler;
}(Scheduler));
function OnNextPredicate(predicate) {
this.predicate = predicate;
}
OnNextPredicate.prototype.equals = function (other) {
if (other === this) { return true; }
if (other == null) { return false; }
if (other.kind !== 'N') { return false; }
return this.predicate(other.value);
};
function OnErrorPredicate(predicate) {
this.predicate = predicate;
}
OnErrorPredicate.prototype.equals = function (other) {
if (other === this) { return true; }
if (other == null) { return false; }
if (other.kind !== 'E') { return false; }
return this.predicate(other.error);
};
var ReactiveTest = Rx.ReactiveTest = {
/** Default virtual time used for creation of observable sequences in unit tests. */
created: 100,
/** Default virtual time used to subscribe to observable sequences in unit tests. */
subscribed: 200,
/** Default virtual time used to dispose subscriptions in unit tests. */
disposed: 1000,
/**
* Factory method for an OnNext notification record at a given time with a given value or a predicate function.
*
* 1 - ReactiveTest.onNext(200, 42);
* 2 - ReactiveTest.onNext(200, function (x) { return x.length == 2; });
*
* @param ticks Recorded virtual time the OnNext notification occurs.
* @param value Recorded value stored in the OnNext notification or a predicate.
* @return Recorded OnNext notification.
*/
onNext: function (ticks, value) {
return typeof value === 'function' ?
new Recorded(ticks, new OnNextPredicate(value)) :
new Recorded(ticks, Notification.createOnNext(value));
},
/**
* Factory method for an OnError notification record at a given time with a given error.
*
* 1 - ReactiveTest.onNext(200, new Error('error'));
* 2 - ReactiveTest.onNext(200, function (e) { return e.message === 'error'; });
*
* @param ticks Recorded virtual time the OnError notification occurs.
* @param exception Recorded exception stored in the OnError notification.
* @return Recorded OnError notification.
*/
onError: function (ticks, error) {
return typeof error === 'function' ?
new Recorded(ticks, new OnErrorPredicate(error)) :
new Recorded(ticks, Notification.createOnError(error));
},
/**
* Factory method for an OnCompleted notification record at a given time.
*
* @param ticks Recorded virtual time the OnCompleted notification occurs.
* @return Recorded OnCompleted notification.
*/
onCompleted: function (ticks) {
return new Recorded(ticks, Notification.createOnCompleted());
},
/**
* Factory method for a subscription record based on a given subscription and disposal time.
*
* @param start Virtual time indicating when the subscription was created.
* @param end Virtual time indicating when the subscription was disposed.
* @return Subscription object.
*/
subscribe: function (start, end) {
return new Subscription(start, end);
}
};
/**
* Creates a new object recording the production of the specified value at the given virtual time.
*
* @constructor
* @param {Number} time Virtual time the value was produced on.
* @param {Mixed} value Value that was produced.
* @param {Function} comparer An optional comparer.
*/
var Recorded = Rx.Recorded = function (time, value, comparer) {
this.time = time;
this.value = value;
this.comparer = comparer || defaultComparer;
};
/**
* Checks whether the given recorded object is equal to the current instance.
*
* @param {Recorded} other Recorded object to check for equality.
* @returns {Boolean} true if both objects are equal; false otherwise.
*/
Recorded.prototype.equals = function (other) {
return this.time === other.time && this.comparer(this.value, other.value);
};
/**
* Returns a string representation of the current Recorded value.
*
* @returns {String} String representation of the current Recorded value.
*/
Recorded.prototype.toString = function () {
return this.value.toString() + '@' + this.time;
};
/**
* Creates a new subscription object with the given virtual subscription and unsubscription time.
*
* @constructor
* @param {Number} subscribe Virtual time at which the subscription occurred.
* @param {Number} unsubscribe Virtual time at which the unsubscription occurred.
*/
var Subscription = Rx.Subscription = function (start, end) {
this.subscribe = start;
this.unsubscribe = end || Number.MAX_VALUE;
};
/**
* Checks whether the given subscription is equal to the current instance.
* @param other Subscription object to check for equality.
* @returns {Boolean} true if both objects are equal; false otherwise.
*/
Subscription.prototype.equals = function (other) {
return this.subscribe === other.subscribe && this.unsubscribe === other.unsubscribe;
};
/**
* Returns a string representation of the current Subscription value.
* @returns {String} String representation of the current Subscription value.
*/
Subscription.prototype.toString = function () {
return '(' + this.subscribe + ', ' + (this.unsubscribe === Number.MAX_VALUE ? 'Infinite' : this.unsubscribe) + ')';
};
var MockDisposable = Rx.MockDisposable = function (scheduler) {
this.scheduler = scheduler;
this.disposes = [];
this.disposes.push(this.scheduler.clock);
};
MockDisposable.prototype.dispose = function () {
this.disposes.push(this.scheduler.clock);
};
var MockObserver = (function (__super__) {
inherits(MockObserver, __super__);
function MockObserver(scheduler) {
__super__.call(this);
this.scheduler = scheduler;
this.messages = [];
}
var MockObserverPrototype = MockObserver.prototype;
MockObserverPrototype.onNext = function (value) {
this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnNext(value)));
};
MockObserverPrototype.onError = function (e) {
this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnError(e)));
};
MockObserverPrototype.onCompleted = function () {
this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnCompleted()));
};
return MockObserver;
})(Observer);
function MockPromise(scheduler, messages) {
var self = this;
this.scheduler = scheduler;
this.messages = messages;
this.subscriptions = [];
this.observers = [];
for (var i = 0, len = this.messages.length; i < len; i++) {
var message = this.messages[i],
notification = message.value;
(function (innerNotification) {
scheduler.scheduleAbsolute(null, message.time, function () {
var obs = self.observers.slice(0);
for (var j = 0, jLen = obs.length; j < jLen; j++) {
innerNotification.accept(obs[j]);
}
return disposableEmpty;
});
})(notification);
}
}
MockPromise.prototype.then = function (onResolved, onRejected) {
var self = this;
this.subscriptions.push(new Subscription(this.scheduler.clock));
var index = this.subscriptions.length - 1;
var newPromise;
var observer = Rx.Observer.create(
function (x) {
var retValue = onResolved(x);
if (retValue && typeof retValue.then === 'function') {
newPromise = retValue;
} else {
var ticks = self.scheduler.clock;
newPromise = new MockPromise(self.scheduler, [Rx.ReactiveTest.onNext(ticks, undefined), Rx.ReactiveTest.onCompleted(ticks)]);
}
var idx = self.observers.indexOf(observer);
self.observers.splice(idx, 1);
self.subscriptions[index] = new Subscription(self.subscriptions[index].subscribe, self.scheduler.clock);
},
function (err) {
onRejected(err);
var idx = self.observers.indexOf(observer);
self.observers.splice(idx, 1);
self.subscriptions[index] = new Subscription(self.subscriptions[index].subscribe, self.scheduler.clock);
}
);
this.observers.push(observer);
return newPromise || new MockPromise(this.scheduler, this.messages);
};
var HotObservable = (function (__super__) {
inherits(HotObservable, __super__);
function HotObservable(scheduler, messages) {
__super__.call(this);
var message, notification, observable = this;
this.scheduler = scheduler;
this.messages = messages;
this.subscriptions = [];
this.observers = [];
for (var i = 0, len = this.messages.length; i < len; i++) {
message = this.messages[i];
notification = message.value;
(function (innerNotification) {
scheduler.scheduleAbsolute(null, message.time, function () {
var obs = observable.observers.slice(0);
for (var j = 0, jLen = obs.length; j < jLen; j++) {
innerNotification.accept(obs[j]);
}
return disposableEmpty;
});
})(notification);
}
}
HotObservable.prototype._subscribe = function (o) {
var observable = this;
this.observers.push(o);
this.subscriptions.push(new Subscription(this.scheduler.clock));
var index = this.subscriptions.length - 1;
return disposableCreate(function () {
var idx = observable.observers.indexOf(o);
observable.observers.splice(idx, 1);
observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock);
});
};
return HotObservable;
})(Observable);
var ColdObservable = (function (__super__) {
inherits(ColdObservable, __super__);
function ColdObservable(scheduler, messages) {
__super__.call(this);
this.scheduler = scheduler;
this.messages = messages;
this.subscriptions = [];
}
ColdObservable.prototype._subscribe = function (o) {
var message, notification, observable = this;
this.subscriptions.push(new Subscription(this.scheduler.clock));
var index = this.subscriptions.length - 1;
var d = new CompositeDisposable();
for (var i = 0, len = this.messages.length; i < len; i++) {
message = this.messages[i];
notification = message.value;
(function (innerNotification) {
d.add(observable.scheduler.scheduleRelative(null, message.time, function () {
innerNotification.accept(o);
return disposableEmpty;
}));
})(notification);
}
return disposableCreate(function () {
observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock);
d.dispose();
});
};
return ColdObservable;
})(Observable);
/** Virtual time scheduler used for testing applications and libraries built using Reactive Extensions. */
Rx.TestScheduler = (function (__super__) {
inherits(TestScheduler, __super__);
function baseComparer(x, y) {
return x > y ? 1 : (x < y ? -1 : 0);
}
function TestScheduler() {
__super__.call(this, 0, baseComparer);
}
/**
* Schedules an action to be executed at the specified virtual time.
*
* @param state State passed to the action to be executed.
* @param dueTime Absolute virtual time at which to execute the action.
* @param action Action to be executed.
* @return Disposable object used to cancel the scheduled action (best effort).
*/
TestScheduler.prototype.scheduleAbsolute = function (state, dueTime, action) {
dueTime <= this.clock && (dueTime = this.clock + 1);
return __super__.prototype.scheduleAbsolute.call(this, state, dueTime, action);
};
/**
* Adds a relative virtual time to an absolute virtual time value.
*
* @param absolute Absolute virtual time value.
* @param relative Relative virtual time value to add.
* @return Resulting absolute virtual time sum value.
*/
TestScheduler.prototype.add = function (absolute, relative) {
return absolute + relative;
};
/**
* Converts the absolute virtual time value to a DateTimeOffset value.
*
* @param absolute Absolute virtual time value to convert.
* @return Corresponding DateTimeOffset value.
*/
TestScheduler.prototype.toAbsoluteTime = function (absolute) {
return new Date(absolute).getTime();
};
/**
* Converts the TimeSpan value to a relative virtual time value.
*
* @param timeSpan TimeSpan value to convert.
* @return Corresponding relative virtual time value.
*/
TestScheduler.prototype.toRelativeTime = function (timeSpan) {
return timeSpan;
};
/**
* Starts the test scheduler and uses the specified virtual times to invoke the factory function, subscribe to the resulting sequence, and dispose the subscription.
*
* @param create Factory method to create an observable sequence.
* @param created Virtual time at which to invoke the factory to create an observable sequence.
* @param subscribed Virtual time at which to subscribe to the created observable sequence.
* @param disposed Virtual time at which to dispose the subscription.
* @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active.
*/
TestScheduler.prototype.startScheduler = function (createFn, settings) {
settings || (settings = {});
settings.created == null && (settings.created = ReactiveTest.created);
settings.subscribed == null && (settings.subscribed = ReactiveTest.subscribed);
settings.disposed == null && (settings.disposed = ReactiveTest.disposed);
var observer = this.createObserver(), source, subscription;
this.scheduleAbsolute(null, settings.created, function () {
source = createFn();
return disposableEmpty;
});
this.scheduleAbsolute(null, settings.subscribed, function () {
subscription = source.subscribe(observer);
return disposableEmpty;
});
this.scheduleAbsolute(null, settings.disposed, function () {
subscription.dispose();
return disposableEmpty;
});
this.start();
return observer;
};
/**
* Creates a hot observable using the specified timestamped notification messages either as an array or arguments.
* @param messages Notifications to surface through the created sequence at their specified absolute virtual times.
* @return Hot observable sequence that can be used to assert the timing of subscriptions and notifications.
*/
TestScheduler.prototype.createHotObservable = function () {
var len = arguments.length, args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
args = new Array(len);
for (var i = 0; i < len; i++) { args[i] = arguments[i]; }
}
return new HotObservable(this, args);
};
/**
* Creates a cold observable using the specified timestamped notification messages either as an array or arguments.
* @param messages Notifications to surface through the created sequence at their specified virtual time offsets from the sequence subscription time.
* @return Cold observable sequence that can be used to assert the timing of subscriptions and notifications.
*/
TestScheduler.prototype.createColdObservable = function () {
var len = arguments.length, args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
args = new Array(len);
for (var i = 0; i < len; i++) { args[i] = arguments[i]; }
}
return new ColdObservable(this, args);
};
/**
* Creates a resolved promise with the given value and ticks
* @param {Number} ticks The absolute time of the resolution.
* @param {Any} value The value to yield at the given tick.
* @returns {MockPromise} A mock Promise which fulfills with the given value.
*/
TestScheduler.prototype.createResolvedPromise = function (ticks, value) {
return new MockPromise(this, [Rx.ReactiveTest.onNext(ticks, value), Rx.ReactiveTest.onCompleted(ticks)]);
};
/**
* Creates a rejected promise with the given reason and ticks
* @param {Number} ticks The absolute time of the resolution.
* @param {Any} reason The reason for rejection to yield at the given tick.
* @returns {MockPromise} A mock Promise which rejects with the given reason.
*/
TestScheduler.prototype.createRejectedPromise = function (ticks, reason) {
return new MockPromise(this, [Rx.ReactiveTest.onError(ticks, reason)]);
};
/**
* Creates an observer that records received notification messages and timestamps those.
* @return Observer that can be used to assert the timing of received notifications.
*/
TestScheduler.prototype.createObserver = function () {
return new MockObserver(this);
};
return TestScheduler;
})(VirtualTimeScheduler);
return Rx;
}));