forked from dtao/lazy.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlazy.js
6276 lines (5588 loc) · 181 KB
/
lazy.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
/*
* @name Lazy.js
*
* @fileOverview
* Lazy.js is a lazy evaluation library for JavaScript.
*
* This has been done before. For examples see:
*
* - [wu.js](http://fitzgen.github.io/wu.js/)
* - [Linq.js](http://linqjs.codeplex.com/)
* - [from.js](https://github.com/suckgamoni/fromjs/)
* - [IxJS](http://rx.codeplex.com/)
* - [sloth.js](http://rfw.name/sloth.js/)
*
* However, at least at present, Lazy.js is faster (on average) than any of
* those libraries. It is also more complete, with nearly all of the
* functionality of [Underscore](http://underscorejs.org/) and
* [Lo-Dash](http://lodash.com/).
*
* Finding your way around the code
* --------------------------------
*
* At the heart of Lazy.js is the {@link Sequence} object. You create an initial
* sequence using {@link Lazy}, which can accept an array, object, or string.
* You can then "chain" together methods from this sequence, creating a new
* sequence with each call.
*
* Here's an example:
*
* var data = getReallyBigArray();
*
* var statistics = Lazy(data)
* .map(transform)
* .filter(validate)
* .reduce(aggregate);
*
* {@link Sequence} is the foundation of other, more specific sequence types.
*
* An {@link ArrayLikeSequence} provides indexed access to its elements.
*
* An {@link ObjectLikeSequence} consists of key/value pairs.
*
* A {@link StringLikeSequence} is like a string (duh): actually, it is an
* {@link ArrayLikeSequence} whose elements happen to be characters.
*
* An {@link AsyncSequence} is special: it iterates over its elements
* asynchronously (so calling `each` generally begins an asynchronous loop and
* returns immediately).
*
* For more information
* --------------------
*
* I wrote a blog post that explains a little bit more about Lazy.js, which you
* can read [here](http://philosopherdeveloper.com/posts/introducing-lazy-js.html).
*
* You can also [create an issue on GitHub](https://github.com/dtao/lazy.js/issues)
* if you have any issues with the library. I work through them eventually.
*
* [@dtao](https://github.com/dtao)
*/
(function(context) {
/**
* Wraps an object and returns a {@link Sequence}. For `null` or `undefined`,
* simply returns an empty sequence (see {@link Lazy.strict} for a stricter
* implementation).
*
* - For **arrays**, Lazy will create a sequence comprising the elements in
* the array (an {@link ArrayLikeSequence}).
* - For **objects**, Lazy will create a sequence of key/value pairs
* (an {@link ObjectLikeSequence}).
* - For **strings**, Lazy will create a sequence of characters (a
* {@link StringLikeSequence}).
*
* @public
* @param {Array|Object|string} source An array, object, or string to wrap.
* @returns {Sequence} The wrapped lazy object.
*
* @exampleHelpers
* // Utility functions to provide to all examples
* function increment(x) { return x + 1; }
* function isEven(x) { return x % 2 === 0; }
* function isPositive(x) { return x > 0; }
* function isNegative(x) { return x < 0; }
*
* @examples
* Lazy([1, 2, 4]) // instanceof Lazy.ArrayLikeSequence
* Lazy({ foo: "bar" }) // instanceof Lazy.ObjectLikeSequence
* Lazy("hello, world!") // instanceof Lazy.StringLikeSequence
* Lazy() // sequence: []
* Lazy(null) // sequence: []
*/
function Lazy(source) {
if (source instanceof Array) {
return new ArrayWrapper(source);
} else if (typeof source === "string") {
return new StringWrapper(source);
} else if (source instanceof Sequence) {
return source;
}
if (Lazy.extensions) {
var extensions = Lazy.extensions, length = extensions.length, result;
while (!result && length--) {
result = extensions[length](source);
}
if (result) {
return result;
}
}
return new ObjectWrapper(source);
}
Lazy.VERSION = '0.3.2';
/*** Utility methods of questionable value ***/
Lazy.noop = function noop() {};
Lazy.identity = function identity(x) { return x; };
/**
* Provides a stricter version of {@link Lazy} which throws an error when
* attempting to wrap `null`, `undefined`, or numeric or boolean values as a
* sequence.
*
* @public
* @returns {Function} A stricter version of the {@link Lazy} helper function.
*
* @examples
* var Strict = Lazy.strict();
*
* Strict() // throws
* Strict(null) // throws
* Strict(true) // throws
* Strict(5) // throws
* Strict([1, 2, 3]) // instanceof Lazy.ArrayLikeSequence
* Strict({ foo: "bar" }) // instanceof Lazy.ObjectLikeSequence
* Strict("hello, world!") // instanceof Lazy.StringLikeSequence
*
* // Let's also ensure the static functions are still there.
* Strict.range(3) // sequence: [0, 1, 2]
* Strict.generate(Date.now) // instanceof Lazy.GeneratedSequence
*/
Lazy.strict = function strict() {
function StrictLazy(source) {
if (source == null) {
throw new Error("You cannot wrap null or undefined using Lazy.");
}
if (typeof source === "number" || typeof source === "boolean") {
throw new Error("You cannot wrap primitive values using Lazy.");
}
return Lazy(source);
};
Lazy(Lazy).each(function(property, name) {
StrictLazy[name] = property;
});
return StrictLazy;
};
/**
* The `Sequence` object provides a unified API encapsulating the notion of
* zero or more consecutive elements in a collection, stream, etc.
*
* Lazy evaluation
* ---------------
*
* Generally speaking, creating a sequence should not be an expensive operation,
* and should not iterate over an underlying source or trigger any side effects.
* This means that chaining together methods that return sequences incurs only
* the cost of creating the `Sequence` objects themselves and not the cost of
* iterating an underlying data source multiple times.
*
* The following code, for example, creates 4 sequences and does nothing with
* `source`:
*
* var seq = Lazy(source) // 1st sequence
* .map(func) // 2nd
* .filter(pred) // 3rd
* .reverse(); // 4th
*
* Lazy's convention is to hold off on iterating or otherwise *doing* anything
* (aside from creating `Sequence` objects) until you call `each`:
*
* seq.each(function(x) { console.log(x); });
*
* Defining custom sequences
* -------------------------
*
* Defining your own type of sequence is relatively simple:
*
* 1. Pass a *method name* and an object containing *function overrides* to
* {@link Sequence.define}. If the object includes a function called `init`,
* this function will be called upon initialization.
* 2. The object should include at least either a `getIterator` method or an
* `each` method. The former supports both asynchronous and synchronous
* iteration, but is slightly more cumbersome to implement. The latter
* supports synchronous iteration and can be automatically implemented in
* terms of the former. You can also implement both if you want, e.g. to
* optimize performance. For more info, see {@link Iterator} and
* {@link AsyncSequence}.
*
* As a trivial example, the following code defines a new method, `sample`,
* which randomly may or may not include each element from its parent.
*
* Lazy.Sequence.define("sample", {
* each: function(fn) {
* return this.parent.each(function(e) {
* // 50/50 chance of including this element.
* if (Math.random() > 0.5) {
* return fn(e);
* }
* });
* }
* });
*
* (Of course, the above could also easily have been implemented using
* {@link #filter} instead of creating a custom sequence. But I *did* say this
* was a trivial example, to be fair.)
*
* Now it will be possible to create this type of sequence from any parent
* sequence by calling the method name you specified. In other words, you can
* now do this:
*
* Lazy(arr).sample();
* Lazy(arr).map(func).sample();
* Lazy(arr).map(func).filter(pred).sample();
*
* Etc., etc.
*
* @public
* @constructor
*/
function Sequence() {}
/**
* Create a new constructor function for a type inheriting from `Sequence`.
*
* @public
* @param {string|Array.<string>} methodName The name(s) of the method(s) to be
* used for constructing the new sequence. The method will be attached to
* the `Sequence` prototype so that it can be chained with any other
* sequence methods, like {@link #map}, {@link #filter}, etc.
* @param {Object} overrides An object containing function overrides for this
* new sequence type. **Must** include either `getIterator` or `each` (or
* both). *May* include an `init` method as well. For these overrides,
* `this` will be the new sequence, and `this.parent` will be the base
* sequence from which the new sequence was constructed.
* @returns {Function} A constructor for a new type inheriting from `Sequence`.
*
* @examples
* // This sequence type logs every element to the specified logger as it
* // iterates over it.
* Lazy.Sequence.define("verbose", {
* init: function(logger) {
* this.logger = logger;
* },
*
* each: function(fn) {
* var logger = this.logger;
* return this.parent.each(function(e, i) {
* logger(e);
* return fn(e, i);
* });
* }
* });
*
* Lazy([1, 2, 3]).verbose(logger).each(Lazy.noop) // calls logger 3 times
*/
Sequence.define = function define(methodName, overrides) {
if (!overrides || (!overrides.getIterator && !overrides.each)) {
throw new Error("A custom sequence must implement *at least* getIterator or each!");
}
return defineSequenceType(Sequence, methodName, overrides);
};
/**
* Gets the number of elements in the sequence. In some cases, this may
* require eagerly evaluating the sequence.
*
* @public
* @returns {number} The number of elements in the sequence.
*
* @examples
* Lazy([1, 2, 3]).size(); // => 3
* Lazy([1, 2]).map(Lazy.identity).size(); // => 2
* Lazy([1, 2, 3]).reject(isEven).size(); // => 2
* Lazy([1, 2, 3]).take(1).size(); // => 1
* Lazy({ foo: 1, bar: 2 }).size(); // => 2
* Lazy('hello').size(); // => 5
*/
Sequence.prototype.size = function size() {
return this.getIndex().length();
};
/**
* Creates an {@link Iterator} object with two methods, `moveNext` -- returning
* true or false -- and `current` -- returning the current value.
*
* This method is used when asynchronously iterating over sequences. Any type
* inheriting from `Sequence` must implement this method or it can't support
* asynchronous iteration.
*
* Note that **this method is not intended to be used directly by application
* code.** Rather, it is intended as a means for implementors to potentially
* define custom sequence types that support either synchronous or
* asynchronous iteration.
*
* @public
* @returns {Iterator} An iterator object.
*
* @examples
* var iterator = Lazy([1, 2]).getIterator();
*
* iterator.moveNext(); // => true
* iterator.current(); // => 1
* iterator.moveNext(); // => true
* iterator.current(); // => 2
* iterator.moveNext(); // => false
*/
Sequence.prototype.getIterator = function getIterator() {
return new Iterator(this);
};
/**
* Gets the root sequence underlying the current chain of sequences.
*/
Sequence.prototype.root = function root() {
return this.parent.root();
};
/**
* Whether or not the current sequence is an asynchronous one. This is more
* accurate than checking `instanceof {@link AsyncSequence}` because, for
* example, `Lazy([1, 2, 3]).async().map(Lazy.identity)` returns a sequence
* that iterates asynchronously even though it's not an instance of
* `AsyncSequence`.
*/
Sequence.prototype.isAsync = function isAsync() {
return this.parent ? this.parent.isAsync() : false;
};
/**
* Evaluates the sequence and produces an appropriate value (an array in most
* cases, an object for {@link ObjectLikeSequence}s or a string for
* {@link StringLikeSequence}s).
*/
Sequence.prototype.value = function value() {
return this.toArray();
};
/**
* Applies the current transformation chain to a given source.
*
* @examples
* var sequence = Lazy([])
* .map(function(x) { return x * -1; })
* .filter(function(x) { return x % 2 === 0; });
*
* sequence.apply([1, 2, 3, 4]); // => [-2, -4]
*/
Sequence.prototype.apply = function apply(source) {
var root = this.root(),
previousSource = root.source,
result;
try {
root.source = source;
result = this.value();
} finally {
root.source = previousSource;
}
return result;
};
/**
* The Iterator object provides an API for iterating over a sequence.
*
* The purpose of the `Iterator` type is mainly to offer an agnostic way of
* iterating over a sequence -- either synchronous (i.e. with a `while` loop)
* or asynchronously (with recursive calls to either `setTimeout` or --- if
* available --- `setImmediate`). It is not intended to be used directly by
* application code.
*
* @public
* @constructor
* @param {Sequence} sequence The sequence to iterate over.
*/
function Iterator(sequence) {
this.sequence = sequence;
this.index = -1;
}
/**
* Gets the current item this iterator is pointing to.
*
* @public
* @returns {*} The current item.
*/
Iterator.prototype.current = function current() {
return this.cachedIndex && this.cachedIndex.get(this.index);
};
/**
* Moves the iterator to the next item in a sequence, if possible.
*
* @public
* @returns {boolean} True if the iterator is able to move to a new item, or else
* false.
*/
Iterator.prototype.moveNext = function moveNext() {
var cachedIndex = this.cachedIndex;
if (!cachedIndex) {
cachedIndex = this.cachedIndex = this.sequence.getIndex();
}
if (this.index >= cachedIndex.length() - 1) {
return false;
}
++this.index;
return true;
};
/**
* Creates an array snapshot of a sequence.
*
* Note that for indefinite sequences, this method may raise an exception or
* (worse) cause the environment to hang.
*
* @public
* @returns {Array} An array containing the current contents of the sequence.
*
* @examples
* Lazy([1, 2, 3]).toArray() // => [1, 2, 3]
*/
Sequence.prototype.toArray = function toArray() {
return this.reduce(function(arr, element) {
arr.push(element);
return arr;
}, []);
};
/**
* Provides an indexed view into the sequence.
*
* For sequences that are already indexed, this will simply return the
* sequence. For non-indexed sequences, this will eagerly evaluate the
* sequence and cache the result (so subsequent calls will not create
* additional arrays).
*
* @returns {ArrayLikeSequence} A sequence containing the current contents of
* the sequence.
*
* @examples
* Lazy([1, 2, 3]).filter(isEven) // instanceof Lazy.Sequence
* Lazy([1, 2, 3]).filter(isEven).getIndex() // instanceof Lazy.ArrayLikeSequence
*/
Sequence.prototype.getIndex = function getIndex() {
if (!this.cachedIndex) {
this.cachedIndex = new ArrayWrapper(this.toArray());
}
return this.cachedIndex;
};
/**
* Provides an indexed, memoized view into the sequence. This will cache the
* result whenever the sequence is first iterated, so that subsequent
* iterations will access the same element objects.
*
* @public
* @returns {ArrayLikeSequence} An indexed, memoized sequence containing this
* sequence's elements, cached after the first iteration.
*
* @example
* function createObject() { return new Object(); }
*
* var plain = Lazy.generate(createObject, 10),
* memoized = Lazy.generate(createObject, 10).memoize();
*
* plain.toArray()[0] === plain.toArray()[0]; // => false
* memoized.toArray()[0] === memoized.toArray()[0]; // => true
*/
Sequence.prototype.memoize = function memoize() {
return new MemoizedSequence(this);
};
/**
* @constructor
*/
function MemoizedSequence(parent) {
this.parent = parent;
}
// MemoizedSequence needs to have its prototype set up after ArrayLikeSequence
/**
* Creates an object from a sequence of key/value pairs.
*
* @public
* @returns {Object} An object with keys and values corresponding to the pairs
* of elements in the sequence.
*
* @examples
* var details = [
* ["first", "Dan"],
* ["last", "Tao"],
* ["age", 29]
* ];
*
* Lazy(details).toObject() // => { first: "Dan", last: "Tao", age: 29 }
*/
Sequence.prototype.toObject = function toObject() {
return this.reduce(function(object, pair) {
object[pair[0]] = pair[1];
return object;
}, {});
};
/**
* Iterates over this sequence and executes a function for every element.
*
* @public
* @aka forEach
* @param {Function} fn The function to call on each element in the sequence.
* Return false from the function to end the iteration.
*
* @examples
* Lazy([1, 2, 3, 4]).each(fn) // calls fn 4 times
*/
Sequence.prototype.each = function each(fn) {
var iterator = this.getIterator(),
i = -1;
while (iterator.moveNext()) {
if (fn(iterator.current(), ++i) === false) {
return false;
}
}
return true;
};
Sequence.prototype.forEach = function forEach(fn) {
return this.each(fn);
};
/**
* Creates a new sequence whose values are calculated by passing this sequence's
* elements through some mapping function.
*
* @public
* @aka collect
* @param {Function} mapFn The mapping function used to project this sequence's
* elements onto a new sequence.
* @returns {Sequence} The new sequence.
*
* @examples
* Lazy([]).map(increment) // sequence: []
* Lazy([1, 2, 3]).map(increment) // sequence: [2, 3, 4]
*
* @benchmarks
* function increment(x) { return x + 1; }
*
* var smArr = Lazy.range(10).toArray(),
* lgArr = Lazy.range(100).toArray();
*
* Lazy(smArr).map(increment).each(Lazy.noop) // lazy - 10 elements
* Lazy(lgArr).map(increment).each(Lazy.noop) // lazy - 100 elements
* _.each(_.map(smArr, increment), _.noop) // lodash - 10 elements
* _.each(_.map(lgArr, increment), _.noop) // lodash - 100 elements
*/
Sequence.prototype.map = function map(mapFn) {
return new MappedSequence(this, createCallback(mapFn));
};
Sequence.prototype.collect = function collect(mapFn) {
return this.map(mapFn);
};
/**
* @constructor
*/
function MappedSequence(parent, mapFn) {
this.parent = parent;
this.mapFn = mapFn;
}
MappedSequence.prototype = new Sequence();
MappedSequence.prototype.getIterator = function getIterator() {
return new MappingIterator(this.parent, this.mapFn);
};
MappedSequence.prototype.each = function each(fn) {
var mapFn = this.mapFn;
return this.parent.each(function(e, i) {
return fn(mapFn(e, i), i);
});
};
/**
* @constructor
*/
function MappingIterator(sequence, mapFn) {
this.iterator = sequence.getIterator();
this.mapFn = mapFn;
this.index = -1;
}
MappingIterator.prototype.current = function current() {
return this.mapFn(this.iterator.current(), this.index);
};
MappingIterator.prototype.moveNext = function moveNext() {
if (this.iterator.moveNext()) {
++this.index;
return true;
}
return false;
};
/**
* Creates a new sequence whose values are calculated by accessing the specified
* property from each element in this sequence.
*
* @public
* @param {string} propertyName The name of the property to access for every
* element in this sequence.
* @returns {Sequence} The new sequence.
*
* @examples
* var people = [
* { first: "Dan", last: "Tao" },
* { first: "Bob", last: "Smith" }
* ];
*
* Lazy(people).pluck("last") // sequence: ["Tao", "Smith"]
*/
Sequence.prototype.pluck = function pluck(property) {
return this.map(property);
};
/**
* Creates a new sequence whose values are calculated by invoking the specified
* function on each element in this sequence.
*
* @public
* @param {string} methodName The name of the method to invoke for every element
* in this sequence.
* @returns {Sequence} The new sequence.
*
* @examples
* function Person(first, last) {
* this.fullName = function fullName() {
* return first + " " + last;
* };
* }
*
* var people = [
* new Person("Dan", "Tao"),
* new Person("Bob", "Smith")
* ];
*
* Lazy(people).invoke("fullName") // sequence: ["Dan Tao", "Bob Smith"]
*/
Sequence.prototype.invoke = function invoke(methodName) {
return this.map(function(e) {
return e[methodName]();
});
};
/**
* Creates a new sequence whose values are the elements of this sequence which
* satisfy the specified predicate.
*
* @public
* @aka select
* @param {Function} filterFn The predicate to call on each element in this
* sequence, which returns true if the element should be included.
* @returns {Sequence} The new sequence.
*
* @examples
* var numbers = [1, 2, 3, 4, 5, 6];
*
* Lazy(numbers).filter(isEven) // sequence: [2, 4, 6]
*
* @benchmarks
* function isEven(x) { return x % 2 === 0; }
*
* var smArr = Lazy.range(10).toArray(),
* lgArr = Lazy.range(100).toArray();
*
* Lazy(smArr).filter(isEven).each(Lazy.noop) // lazy - 10 elements
* Lazy(lgArr).filter(isEven).each(Lazy.noop) // lazy - 100 elements
* _.each(_.filter(smArr, isEven), _.noop) // lodash - 10 elements
* _.each(_.filter(lgArr, isEven), _.noop) // lodash - 100 elements
*/
Sequence.prototype.filter = function filter(filterFn) {
return new FilteredSequence(this, createCallback(filterFn));
};
Sequence.prototype.select = function select(filterFn) {
return this.filter(filterFn);
};
/**
* @constructor
*/
function FilteredSequence(parent, filterFn) {
this.parent = parent;
this.filterFn = filterFn;
}
FilteredSequence.prototype = new Sequence();
FilteredSequence.prototype.getIterator = function getIterator() {
return new FilteringIterator(this.parent, this.filterFn);
};
FilteredSequence.prototype.each = function each(fn) {
var filterFn = this.filterFn;
// I'm not proud of this, but it'll get the job done for now.
if (this.parent instanceof ObjectLikeSequence) {
return this.parent.each(function(v, k) {
if (filterFn(v, k)) {
return fn(v, k);
}
});
} else {
var j = 0;
return this.parent.each(function(e, i) {
if (filterFn(e, i)) {
return fn(e, j++);
}
});
}
};
FilteredSequence.prototype.reverse = function reverse() {
return this.parent.reverse().filter(this.filterFn);
};
/**
* @constructor
*/
function FilteringIterator(sequence, filterFn) {
this.iterator = sequence.getIterator();
this.filterFn = filterFn;
this.index = 0;
}
FilteringIterator.prototype.current = function current() {
return this.value;
};
FilteringIterator.prototype.moveNext = function moveNext() {
var iterator = this.iterator,
filterFn = this.filterFn,
value;
while (iterator.moveNext()) {
value = iterator.current();
if (filterFn(value, this.index++)) {
this.value = value;
return true;
}
}
this.value = undefined;
return false;
};
/**
* Creates a new sequence whose values exclude the elements of this sequence
* identified by the specified predicate.
*
* @public
* @param {Function} rejectFn The predicate to call on each element in this
* sequence, which returns true if the element should be omitted.
* @returns {Sequence} The new sequence.
*
* @examples
* Lazy([1, 2, 3, 4, 5]).reject(isEven) // sequence: [1, 3, 5]
* Lazy([{ foo: 1 }, { bar: 2 }]).reject('foo') // sequence: [{ bar: 2 }]
* Lazy([{ foo: 1 }, { foo: 2 }]).reject({ foo: 2 }) // sequence: [{ foo: 1 }]
*/
Sequence.prototype.reject = function reject(rejectFn) {
rejectFn = createCallback(rejectFn);
return this.filter(function(e) { return !rejectFn(e); });
};
/**
* Creates a new sequence whose values have the specified type, as determined
* by the `typeof` operator.
*
* @public
* @param {string} type The type of elements to include from the underlying
* sequence, i.e. where `typeof [element] === [type]`.
* @returns {Sequence} The new sequence, comprising elements of the specified
* type.
*
* @examples
* Lazy([1, 2, 'foo', 'bar']).ofType('number') // sequence: [1, 2]
* Lazy([1, 2, 'foo', 'bar']).ofType('string') // sequence: ['foo', 'bar']
* Lazy([1, 2, 'foo', 'bar']).ofType('boolean') // sequence: []
*/
Sequence.prototype.ofType = function ofType(type) {
return this.filter(function(e) { return typeof e === type; });
};
/**
* Creates a new sequence whose values are the elements of this sequence with
* property names and values matching those of the specified object.
*
* @public
* @param {Object} properties The properties that should be found on every
* element that is to be included in this sequence.
* @returns {Sequence} The new sequence.
*
* @examples
* var people = [
* { first: "Dan", last: "Tao" },
* { first: "Bob", last: "Smith" }
* ];
*
* Lazy(people).where({ first: "Dan" }) // sequence: [{ first: "Dan", last: "Tao" }]
*
* @benchmarks
* var animals = ["dog", "cat", "mouse", "horse", "pig", "snake"];
*
* Lazy(animals).where({ length: 3 }).each(Lazy.noop) // lazy
* _.each(_.where(animals, { length: 3 }), _.noop) // lodash
*/
Sequence.prototype.where = function where(properties) {
return this.filter(properties);
};
/**
* Creates a new sequence with the same elements as this one, but to be iterated
* in the opposite order.
*
* Note that in some (but not all) cases, the only way to create such a sequence
* may require iterating the entire underlying source when `each` is called.
*
* @public
* @returns {Sequence} The new sequence.
*
* @examples
* Lazy([1, 2, 3]).reverse() // sequence: [3, 2, 1]
* Lazy([]).reverse() // sequence: []
*/
Sequence.prototype.reverse = function reverse() {
return new ReversedSequence(this);
};
/**
* @constructor
*/
function ReversedSequence(parent) {
this.parent = parent;
}
ReversedSequence.prototype = new Sequence();
ReversedSequence.prototype.getIterator = function getIterator() {
return new ReversedIterator(this.parent);
};
/**
* @constuctor
*/
function ReversedIterator(sequence) {
this.sequence = sequence;
}
ReversedIterator.prototype.current = function current() {
return this.sequence.getIndex().get(this.index);
};
ReversedIterator.prototype.moveNext = function moveNext() {
var indexed = this.sequence.getIndex(),
length = indexed.length();
if (typeof this.index === "undefined") {
this.index = length;
}
return (--this.index >= 0);
};
/**
* Creates a new sequence with all of the elements of this one, plus those of
* the given array(s).
*
* @public
* @param {...*} var_args One or more values (or arrays of values) to use for
* additional items after this sequence.
* @returns {Sequence} The new sequence.
*
* @examples
* var left = [1, 2, 3];
* var right = [4, 5, 6];
*
* Lazy(left).concat(right) // sequence: [1, 2, 3, 4, 5, 6]
* Lazy(left).concat(Lazy(right)) // sequence: [1, 2, 3, 4, 5, 6]
* Lazy(left).concat(right, [7, 8]) // sequence: [1, 2, 3, 4, 5, 6, 7, 8]
*/
Sequence.prototype.concat = function concat(var_args) {
return new ConcatenatedSequence(this, arraySlice.call(arguments, 0));
};
/**
* @constructor
*/
function ConcatenatedSequence(parent, arrays) {
this.parent = parent;
this.arrays = arrays;
}
ConcatenatedSequence.prototype = new Sequence();
ConcatenatedSequence.prototype.each = function each(fn) {
var done = false,
i = 0;
this.parent.each(function(e) {
if (fn(e, i++) === false) {
done = true;
return false;
}
});
if (!done) {
Lazy(this.arrays).flatten().each(function(e) {
if (fn(e, i++) === false) {
return false;
}
});
}
};
/**
* Creates a new sequence comprising the first N elements from this sequence, OR
* (if N is `undefined`) simply returns the first element of this sequence.
*
* @public
* @aka head, take
* @param {number=} count The number of elements to take from this sequence. If
* this value exceeds the length of the sequence, the resulting sequence
* will be essentially the same as this one.
* @returns {*} The new sequence (or the first element from this sequence if
* no count was given).
*
* @examples
* function powerOfTwo(exp) {
* return Math.pow(2, exp);
* }
*
* Lazy.generate(powerOfTwo).first() // => 1
* Lazy.generate(powerOfTwo).first(5) // sequence: [1, 2, 4, 8, 16]
* Lazy.generate(powerOfTwo).skip(2).first() // => 4
* Lazy.generate(powerOfTwo).skip(2).first(2) // sequence: [4, 8]
*/
Sequence.prototype.first = function first(count) {
if (typeof count === "undefined") {
return getFirst(this);
}
return new TakeSequence(this, count);
};
Sequence.prototype.head =
Sequence.prototype.take = function (count) {
return this.first(count);
};
/**
* @constructor
*/
function TakeSequence(parent, count) {
this.parent = parent;
this.count = count;
}
TakeSequence.prototype = new Sequence();
TakeSequence.prototype.getIterator = function getIterator() {
return new TakeIterator(this.parent, this.count);