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 17
/
Copy pathl2o.js
2260 lines (2087 loc) · 87.3 KB
/
l2o.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
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
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
(function (window, undefined) {
var freeExports = typeof exports == 'object' && exports,
freeModule = typeof module == 'object' && module && module.exports == freeExports && module,
freeGlobal = typeof global == 'object' && global;
if (freeGlobal.global === freeGlobal) {
window = freeGlobal;
}
var Ix = { Internals: {} };
// Headers
function noop () { }
function identity (x) { return x; }
function defaultComparer (x, y) { return x > y ? 1 : x < y ? -1 : 0; }
function defaultEqualityComparer(x, y) { return isEqual(x, y); }
function defaultSerializer(x) { return x.toString(); }
var seqNoElements = 'Sequence contains no elements.';
var invalidOperation = 'Invalid operation';
var slice = Array.prototype.slice;
var hasProp = {}.hasOwnProperty;
/** @private */
var inherits = this.inherits = Ix.Internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
/** @private */
var addProperties = Ix.Internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
/** Used to determine if values are of the language type Object */
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
suportNodeClass;
try {
suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
suportNodeClass = true;
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
function isArguments(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
function isFunction(value) {
return typeof value == 'function';
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value == 'function' && toString.call(value) == funcClass;
};
}
var isEqual = Ix.Internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
var result;
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a &&
!(a && objectTypes[type]) &&
!(b && objectTypes[otherType])) {
return false;
}
// exit early for `null` and `undefined`, avoiding ES3's Function#call behavior
// http://es5.github.io/#x15.3.4.4
if (a == null || b == null) {
return a === b;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0`, treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `+0` vs. `-0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!suportNodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !supportsArgsClass && isArguments(a) ? Object : a.constructor,
ctorB = !supportsArgsClass && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB && !(
isFunction(ctorA) && ctorA instanceof ctorA &&
isFunction(ctorB) && ctorB instanceof ctorB
)) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
length = a.length;
size = b.length;
// compare lengths to determine if a deep comparison is necessary
result = size == a.length;
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
return result;
}
// deep compare each object
for(var key in b) {
if (hasOwnProperty.call(b, key)) {
// count properties and deep compare each property value
size++;
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], b[key], stackA, stackB));
}
}
if (result) {
// ensure both objects have the same number of properties
for (var key in a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
}
}
stackA.pop();
stackB.pop();
return result;
}
// Real Dictionary
var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647];
var noSuchkey = "no such key";
var duplicatekey = "duplicate key";
function isPrime(candidate) {
if (candidate & 1 === 0) {
return candidate === 2;
}
var num1 = Math.sqrt(candidate),
num2 = 3;
while (num2 <= num1) {
if (candidate % num2 === 0) {
return false;
}
num2 += 2;
}
return true;
}
function getPrime(min) {
var index, num, candidate;
for (index = 0; index < primes.length; ++index) {
num = primes[index];
if (num >= min) {
return num;
}
}
candidate = min | 1;
while (candidate < primes[primes.length - 1]) {
if (isPrime(candidate)) {
return candidate;
}
candidate += 2;
}
return min;
}
function stringHashFn(str) {
var hash = 0;
if (!str.length) {
return hash;
}
for (var i = 0, len = str.length; i < len; i++) {
var character = str.charCodeAt(i);
hash = ((hash<<5)-hash)+character;
hash = hash & hash;
}
return hash;
}
function numberHashFn(key) {
var c2 = 0x27d4eb2d;
key = (key ^ 61) ^ (key >>> 16);
key = key + (key << 3);
key = key ^ (key >>> 4);
key = key * c2;
key = key ^ (key >>> 15);
return key;
}
var getHashCode = (function () {
var uniqueIdCounter = 0;
return function (obj) {
if (obj == null) {
throw new Error(noSuchkey);
}
// Check for built-ins before tacking on our own for any object
if (typeof obj === 'string') {
return stringHashFn(obj);
}
if (typeof obj === 'number') {
return numberHashFn(obj);
}
if (typeof obj === 'boolean') {
return obj === true ? 1 : 0;
}
if (obj instanceof Date) {
return obj.getTime();
}
if (obj.getHashCode) {
return obj.getHashCode();
}
var id = 17 * uniqueIdCounter++;
obj.getHashCode = function () { return id; };
return id;
};
} ());
function newEntry() {
return { key: null, value: null, next: 0, hashCode: 0 };
}
// Dictionary implementation
var Dictionary = function (capacity, comparer) {
if (capacity < 0) {
throw new Error('out of range')
}
if (capacity > 0) {
this._initialize(capacity);
}
this.comparer = comparer || defaultComparer;
this.freeCount = 0;
this.size = 0;
this.freeList = -1;
};
DictionaryPrototype = Dictionary.prototype;
DictionaryPrototype._initialize = function (capacity) {
var prime = getPrime(capacity), i;
this.buckets = new Array(prime);
this.entries = new Array(prime);
for (i = 0; i < prime; i++) {
this.buckets[i] = -1;
this.entries[i] = newEntry();
}
this.freeList = -1;
};
DictionaryPrototype.add = function (key, value) {
return this._insert(key, value, true);
};
DictionaryPrototype._insert = function (key, value, add) {
if (!this.buckets) {
this._initialize(0);
}
var index3;
var num = getHashCode(key) & 2147483647;
var index1 = num % this.buckets.length;
for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) {
if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) {
if (add) {
throw new Error(duplicatekey);
}
this.entries[index2].value = value;
return;
}
}
if (this.freeCount > 0) {
index3 = this.freeList;
this.freeList = this.entries[index3].next;
--this.freeCount;
} else {
if (this.size === this.entries.length) {
this._resize();
index1 = num % this.buckets.length;
}
index3 = this.size;
++this.size;
}
this.entries[index3].hashCode = num;
this.entries[index3].next = this.buckets[index1];
this.entries[index3].key = key;
this.entries[index3].value = value;
this.buckets[index1] = index3;
};
DictionaryPrototype._resize = function () {
var prime = getPrime(this.size * 2),
numArray = new Array(prime);
for (index = 0; index < numArray.length; ++index) {
numArray[index] = -1;
}
var entryArray = new Array(prime);
for (index = 0; index < this.size; ++index) {
entryArray[index] = this.entries[index];
}
for (var index = this.size; index < prime; ++index) {
entryArray[index] = newEntry();
}
for (var index1 = 0; index1 < this.size; ++index1) {
var index2 = entryArray[index1].hashCode % prime;
entryArray[index1].next = numArray[index2];
numArray[index2] = index1;
}
this.buckets = numArray;
this.entries = entryArray;
};
DictionaryPrototype.remove = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647;
var index1 = num % this.buckets.length;
var index2 = -1;
for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) {
if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) {
if (index2 < 0) {
this.buckets[index1] = this.entries[index3].next;
} else {
this.entries[index2].next = this.entries[index3].next;
}
this.entries[index3].hashCode = -1;
this.entries[index3].next = this.freeList;
this.entries[index3].key = null;
this.entries[index3].value = null;
this.freeList = index3;
++this.freeCount;
return true;
} else {
index2 = index3;
}
}
}
return false;
};
DictionaryPrototype.clear = function () {
var index, len;
if (this.size <= 0) {
return;
}
for (index = 0, len = this.buckets.length; index < len; ++index) {
this.buckets[index] = -1;
}
for (index = 0; index < this.size; ++index) {
this.entries[index] = newEntry();
}
this.freeList = -1;
this.size = 0;
};
DictionaryPrototype._findEntry = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647;
for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) {
if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) {
return index;
}
}
}
return -1;
};
DictionaryPrototype.length = function () {
return this.size - this.freeCount;
};
DictionaryPrototype.tryGetValue = function (key) {
var entry = this._findEntry(key);
if (entry >= 0) {
return this.entries[entry].value;
}
return undefined;
};
DictionaryPrototype.getValues = function () {
var index = 0, results = [];
if (this.entries) {
for (var index1 = 0; index1 < this.size; index1++) {
if (this.entries[index1].hashCode >= 0) {
results[index++] = this.entries[index1].value;
}
}
}
return results;
};
DictionaryPrototype.get = function (key) {
var entry = this._findEntry(key);
if (entry >= 0) {
return this.entries[entry].value;
}
throw new Error(noSuchkey);
};
DictionaryPrototype.set = function (key, value) {
this._insert(key, value, false);
};
DictionaryPrototype.has = function (key) {
return this._findEntry(key) >= 0;
};
DictionaryPrototype.toEnumerable = function () {
var self = this;
return new Enumerable(function () {
var index = 0, current;
return enumeratorCreate(
function () {
if (!self.entries) {
return false;
}
while (true) {
if (index < self.size) {
if (self.entries[index].hashCode >= 0) {
var k = self.entries[index];
current = { key: k.key, value: k.value };
index++;
return true;
}
} else {
return false;
}
}
},
function () {
return current;
},
noop
);
});
};
var Lookup = (function () {
function Lookup(map) {
this.map = map;
}
var LookupPrototype = Lookup.prototype;
LookupPrototype.has = function (key) {
return this.map.has(key);
};
LookupPrototype.length = function () {
return this.map.length();
};
LookupPrototype.get = function (key) {
return enumerableFromArray(this.map.get(key));
};
LookupPrototype.toEnumerable = function () {
return this.map.toEnumerable().select(function (kvp) {
var e = enumerableFromArray(kvp.value);
e.key = kvp.key;
return e;
});
};
return Lookup;
}());
var Enumerator = Ix.Enumerator = function (moveNext, getCurrent, dispose) {
this.moveNext = moveNext;
this.getCurrent = getCurrent;
this.dispose = dispose;
};
var enumeratorCreate = Enumerator.create = function (moveNext, getCurrent, dispose) {
var done = false;
dispose || (dispose = noop);
return new Enumerator(function () {
if (done) {
return false;
}
var result = moveNext();
if (!result) {
done = true;
dispose();
}
return result;
}, function () { return getCurrent(); }, function () {
if (!done) {
dispose();
done = true;
}
});
};
/** @private Check for disposal */
function checkAndDispose(e) {
e && e.dispose();
}
/**
* Provides a set of methods to create and query Enumerable sequences.
*/
var Enumerable = Ix.Enumerable = (function () {
function Enumerable(getEnumerator) {
this.getEnumerator = getEnumerator;
}
var EnumerablePrototype = Enumerable.prototype;
function aggregate (seed, func, resultSelector) {
resultSelector || (resultSelector = identity);
var accumulate = seed, enumerator = this.getEnumerator(), i = 0;
try {
while (enumerator.moveNext()) {
accumulate = func(accumulate, enumerator.getCurrent(), i++, this);
}
} finally {
enumerator.dispose();
}
return resultSelector ? resultSelector(accumulate) : accumulate;
}
function aggregate1 (func) {
var accumulate, enumerator = this.getEnumerator(), i = 0;
try {
if (!enumerator.moveNext()) {
throw new Error(seqNoElements);
}
accumulate = enumerator.getCurrent();
while (enumerator.moveNext()) {
accumulate = func(accumulate, enumerator.getCurrent(), i++, this);
}
} catch (e) {
throw e;
} finally {
enumerator.dispose();
}
return accumulate;
}
/**
* Applies an accumulator function over a sequence. The specified seed value is used as the initial accumulator value, and the optional function is used to select the result value.
*
* @example
* sequence.aggregate(0, function (acc, item, index, seq) { return acc + x; });
* sequence.aggregate(function (acc, item, index, seq) { return acc + x; });
*
* @param {Any} seed The initial accumulator value.
* @param {Function} func An accumulator function to be invoked on each element.
* @resultSelector {Function} A function to transform the final accumulator value into the result value.
* @returns {Any} The transformed final accumulator value.
*/
EnumerablePrototype.aggregate = function(/* seed, func, resultSelector */) {
var f = arguments.length === 1 ? aggregate1 : aggregate;
return f.apply(this, arguments);
};
/**
* Apply a function against an accumulator and each value of the sequence (from left-to-right) as to reduce it to a single value.
*
* @example
* sequence.reduce(function (acc, x) { return acc + x; }, 0);
* sequence.reduce(function (acc, x) { return acc + x; });
*
* @param {Function} func Function to execute on each value in the sequence, taking four arguments:
* previousValue The value previously returned in the last invocation of the callback, or initialValue, if supplied.
* currentValue The current element being processed in the sequence.
* index The index of the current element being processed in the sequence.
* sequence The sequence reduce was called upon.
* @param {Any} initialValue Object to use as the first argument to the first call of the callback.
* @returns {Any} The transformed final accumulator value.
*/
EnumerablePrototype.reduce = function (/*func, seed */) {
return arguments.length === 2 ?
aggregate.call(this, arguments[1], arguments[0]) :
aggregate1.apply(this, arguments);
};
/**
* Determines whether all elements of a sequence satisfy a condition.
*
* @example
* sequence.all(function (item, index, seq) { return item % 2 === 0; });
*
* @param {Function} predicate A function to test each element for a condition.
* @returns {Boolean} true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.
*/
EnumerablePrototype.all = EnumerablePrototype.every = function (predicate, thisArg) {
var e = this.getEnumerator(), i = 0;
try {
while (e.moveNext()) {
if (!predicate.call(thisArg, e.getCurrent(), i++, this)) {
return false;
}
}
} catch (ex) {
throw ex;
} finally {
checkAndDispose(e);
}
return true;
};
EnumerablePrototype.every = EnumerablePrototype.all;
/**
* Determines whether any element of a sequence satisfies a condition if given, else if any items are in the sequence.
*
* @example
* sequence.any(function (item, index, seq) { return x % 2 === 0; });
* sequence.any();
*
* @param {Function} [predicate] An optional function to test each element for a condition.
* @returns {Boolean} true if any elements in the source sequence pass the test in the specified predicate; otherwise, false.
*/
EnumerablePrototype.any = function(predicate, thisArg) {
var e = this.getEnumerator(), i = 0;
try {
while (e.moveNext()) {
if (!predicate || predicate.call(thisArg, e.getCurrent(), i++, this)) {
return true;
}
}
} catch(ex) {
throw ex;
} finally {
checkAndDispose(e);
}
return false;
};
EnumerablePrototype.some = EnumerablePrototype.any;
/**
* Computes the average of a sequence of values that are obtained by invoking a transform function on each element of the input sequence.
*
* @param {Function} [selector] An optional transform function to apply to each element.
* @returns {Number} The average of the sequence of values.
*/
EnumerablePrototype.average = function(selector) {
if (selector) {
return this.select(selector).average();
}
var e = this.getEnumerator(), count = 0, sum = 0;
try {
while (e.moveNext()) {
count++;
sum += e.getCurrent();
}
} catch (ex) {
throw ex;
} finally {
checkAndDispose(e);
}
if (count === 0) {
throw new Error(seqNoElements);
}
return sum / count;
};
/**
* Concatenates two sequences.
*
* @returns {Enumerable} An Enumerable that contains the concatenated elements of the two input sequences.
*/
EnumerablePrototype.concat = function () {
var args = slice.call(arguments, 0);
args.unshift(this);
return enumerableConcat.apply(null, args);
};
/**
* Determines whether a sequence contains a specified element by using an optional comparer function
*
* @param {Any} value The value to locate in the sequence.
* @param {Function} [comparer] An equality comparer function to compare values.
* @returns {Boolean} true if the source sequence contains an element that has the specified value; otherwise, false.
*/
EnumerablePrototype.contains = function(value, comparer) {
comparer || (comparer = defaultEqualityComparer);
var e = this.getEnumerator();
try {
while (e.moveNext()) {
if (comparer(value, e.getCurrent())) {
return true;
}
}
} catch (ex) {
throw ex;
} finally {
checkAndDispose(e);
}
return false;
};
/**
* Returns a number that represents how many elements in the specified sequence satisfy a condition if specified, else the number of items in the sequence.
*
* @example
* sequence.count();
* sequence.count(function (item, index, seq) { return item % 2 === 0; });
*
* @param {Function} [predicate] A function to test each element for a condition.
* @returns {Number} A number that represents how many elements in the sequence satisfy the condition in the predicate function if specified, else number of items in the sequence.
*/
EnumerablePrototype.count = function(predicate, thisArg) {
var c = 0, i = 0, e = this.getEnumerator();
try {
while (e.moveNext()) {
if (!predicate || predicate.call(thisArg, e.getCurrent(), i++, this)) {
c++;
}
}
} catch (ex) {
throw ex;
} finally {
checkAndDispose(e);
}
return c;
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.
*
* @param {Any} [defaultValue] The value to return if the sequence is empty.
* @returns {Enumerable} An Enumerable that contains defaultValue if source is empty; otherwise, source.
*/
EnumerablePrototype.defaultIfEmpty = function(defaultValue) {
var parent = this;
return new Enumerable(function () {
var current, isFirst = true, hasDefault = false, e;
return enumeratorCreate(
function () {
e || (e = parent.getEnumerator());
if (hasDefault) { return false; }
if (isFirst) {
isFirst = false;
if (!e.moveNext()) {
current = defaultValue;
hasDefault = true;
return true;
} else {
current = e.getCurrent();
return true;
}
}
if (!e.moveNext()) { return false; }
current = e.getCurrent();
return true;
},
function () { return current; },
function () { checkAndDispose(e); }
);
});
};
function arrayIndexOf (item, comparer) {
comparer || (comparer = defaultEqualityComparer);
var idx = this.length;
while (idx--) {
if (comparer(this[idx], item)) {
return idx;
}
}
return -1;
}
function arrayRemove(item, comparer) {
var idx = arrayIndexOf.call(this, item, comparer);
if (idx === -1) {
return false;
}
this.splice(idx, 1);
return true;
}
/**
* Returns distinct elements from a sequence by using an optional comparer function to compare values.
* @example
* var result = Enumerable.fromArray([1,2,1,2,1,2]);
* var result = Enumerable.fromArray([1,2,1,2,1,2], function (x, y) { return x === y; });
* @param {Function} [comparer] a comparer function to compare the values.
* @returns {Enumerable} An Enumerable that contains distinct elements from the source sequence.
*/
EnumerablePrototype.distinct = function(comparer) {
comparer || (comparer = defaultEqualityComparer);
var parent = this;
return new Enumerable(function () {
var current, map = [], e;
return enumeratorCreate(
function () {
e || (e = parent.getEnumerator());
while (true) {
if (!e.moveNext()) {
return false;
}
var c = e.getCurrent();
if (arrayIndexOf.call(map, c, comparer) === -1) {
current = c;
map.push(current);
return true;
}
}
},
function () { return current; },
function () { checkAndDispose(e);}
);
});
};
/**
* Returns the element at a specified index in a sequence.
*
* @param {Number} index The zero-based index of the element to retrieve.
* @returns {Any} The element at the specified position in the source sequence.
*/
EnumerablePrototype.elementAt = function (index) {
return this.skip(index).first();
};
/**
* Returns the element at a specified index in a sequence or a default value if the index is out of range.
*
* @param {Number} index The zero-based index of the element to retrieve.
* @returns {Any} null if the index is outside the bounds of the source sequence; otherwise, the element at the specified position in the source sequence.
*/
EnumerablePrototype.elementAtOrDefault = function (index) {
return this.skip(index).firstOrDefault();
};
/**
* Produces the set difference of two sequences by using the specified comparer function to compare values.
*
* @param {Enumerable} second An Enumerable whose elements that also occur in the first sequence will cause those elements to be removed from the returned sequence.
* @param {Function} [comparer] A function to compare values.
* @returns {Enumerable} A sequence that contains the set difference of the elements of two sequences.
*/
EnumerablePrototype.except = function(second, comparer) {
comparer || (comparer = defaultEqualityComparer);
var parent = this;
return new Enumerable(function () {
var current, map = [], se = second.getEnumerator(), fe;
try {
while (se.moveNext()) {
map.push(se.getCurrent());
}
} catch(ex) {
throw ex;
} finally {
checkAndDispose(se);
}
return enumeratorCreate(
function () {
fe || (fe = parent.getEnumerator());
while (true) {
if (!fe.moveNext()) {
return false;
}
current = fe.getCurrent();
if (arrayIndexOf.call(map, current, comparer) === -1) {
map.push(current);
return true;
}
}
},
function () { return current; },
function () { checkAndDispose(fe); }
);
});