/
lamb.js
6982 lines (6541 loc) · 235 KB
/
lamb.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
/**
* @overview lamb - A lightweight, and docile, JavaScript library to help embracing functional programming.
* @author Andrea Scartabelli <andrea.scartabelli@gmail.com>
* @version 0.58.0-alpha.2
* @module lamb
* @license MIT
* @preserve
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.lamb = {}));
}(this, function (exports) { 'use strict';
/**
* The placeholder object used in partial application.
* @memberof module:lamb
* @alias module:lamb.__
* @category Special properties
* @see {@link module:lamb.partial|partial}, {@link module:lamb.partialRight|partialRight}
* @see {@link module:lamb.asPartial|asPartial}
* @since 0.57.0
* @type {Object}
*/
var __ = {};
/**
* Builds a function that returns a constant value.
* It's actually the simplest form of the K combinator or Kestrel.
* @example
* var truth = _.always(true);
*
* truth() // => true
* truth(false) // => true
* truth(1, 2) // => true
*
* // the value being returned is actually the
* // very same value passed to the function
* var foo = {bar: "baz"};
* var alwaysFoo = _.always(foo);
*
* alwaysFoo() === foo // => true
*
* @memberof module:lamb
* @category Function
* @see [SKI combinator calculus]{@link https://en.wikipedia.org/wiki/SKI_combinator_calculus}
* @since 0.1.0
* @param {*} value
* @returns {Function}
*/
function always (value) {
return function () {
return value;
};
}
/**
* Verifies that the two supplied values are the same value using the "SameValueZero" comparison.<br/>
* With this comparison <code>NaN</code> is equal to itself, but <code>0</code> and <code>-0</code> are
* considered the same value.<br/>
* See also {@link module:lamb.isSVZ|isSVZ} for a curried version building a predicate and
* {@link module:lamb.areSame|areSame} and {@link module:lamb.is|is} to perform a "SameValue" comparison.
* @example
* var testObject = {};
*
* _.areSVZ({}, testObject) // => false
* _.areSVZ(testObject, testObject) // => true
* _.areSVZ("foo", "foo") // => true
* _.areSVZ(0, -0) // => true
* _.areSVZ(0 / 0, NaN) // => true
*
* @memberof module:lamb
* @category Logic
* @see {@link module:lamb.isSVZ|isSVZ}
* @see {@link module:lamb.areSame|areSame}, {@link module:lamb.is|is}
* @see [SameValue comparison]{@link https://www.ecma-international.org/ecma-262/7.0/#sec-samevalue}
* @see [SameValueZero comparison]{@link https://www.ecma-international.org/ecma-262/7.0/#sec-samevaluezero}
* @since 0.50.0
* @param {*} a
* @param {*} b
* @returns {Boolean}
*/
function areSVZ (a, b) {
return a !== a ? b !== b : a === b; // eslint-disable-line no-self-compare
}
/**
* Builds a function that passes only two arguments to the given function.<br/>
* It's simply a shortcut for a common use case of {@link module:lamb.aritize|aritize},
* exposed for convenience.
* @example
* _.list(1, 2, 3, 4, 5) // => [1, 2, 3, 4, 5]
* _.binary(_.list)(1, 2, 3, 4, 5) // => [1, 2]
*
* @memberof module:lamb
* @category Function
* @see {@link module:lamb.aritize|aritize}
* @see {@link module:lamb.unary|unary}
* @since 0.10.0
* @param {Function} fn
* @returns {Function}
*/
function binary (fn) {
return function (a, b) {
return fn.call(this, a, b);
};
}
/**
* "Clamps" a number within the given limits, both included.<br/>
* The function will convert to number all its parameters before starting any
* evaluation, and will return <code>NaN</code> if <code>min</code> is greater
* than <code>max</code>.
* @example
* _.clamp(-5, 0, 10) // => 0
* _.clamp(5, 0, 10) // => 5
* _.clamp(15, 0, 10) // => 10
* _.clamp(0, 0, 10) // => 0
* _.clamp(10, 0, 10) // => 10
* _.is(_.clamp(-0, 0, 10), -0) // => true
* _.clamp(10, 20, 15) // => NaN
*
* @memberof module:lamb
* @category Math
* @see {@link module:lamb.clampWithin|clampWithin}
* @since 0.13.0
* @param {Number} n
* @param {Number} min
* @param {Number} max
* @returns {Number}
*/
function clamp (n, min, max) {
n = +n;
min = +min;
max = +max;
if (min > max) {
return NaN;
} else {
return n < min ? min : n > max ? max : n;
}
}
/**
* Builds a partially applied function.<br/>
* The {@link module:lamb.__|__} object can be used as a placeholder for arguments.<br/>
* @example
* var __ = _.__;
* var users = [
* {id: 1, name: "John", active: true, confirmedMail: true},
* {id: 2, name: "Jane", active: true, confirmedMail: false},
* {id: 3, name: "Mario", active: false, confirmedMail: false}
* ];
* var isKeyTrue = _.partial(_.hasKeyValue, [__, true]);
* var isActive = isKeyTrue("active");
* var hasConfirmedMail = isKeyTrue("confirmedMail");
*
* _.map(users, isActive) // => [true, true, false]
* _.map(users, hasConfirmedMail) // => [true, false, false]
*
* @memberof module:lamb
* @category Function
* @see {@link module:lamb.partialRight|partialRight}
* @see {@link module:lamb.asPartial|asPartial}
* @see {@link module:lamb.curry|curry}, {@link module:lamb.curryRight|curryRight}
* @see {@link module:lamb.curryable|curryable}, {@link module:lamb.curryableRight|curryableRight}
* @see {@link module:lamb.__|__} The placeholder object.
* @since 0.1.0
* @param {Function} fn
* @param {Array} args
* @returns {Function}
*/
function partial (fn, args) {
return function () {
if (!Array.isArray(args)) {
return fn.apply(this, arguments);
}
var lastIdx = 0;
var newArgs = [];
var argsLen = args.length;
for (var i = 0, boundArg; i < argsLen; i++) {
boundArg = args[i];
newArgs[i] = boundArg === __ ? arguments[lastIdx++] : boundArg;
}
for (var len = arguments.length; lastIdx < len; lastIdx++) {
newArgs[i++] = arguments[lastIdx];
}
return fn.apply(this, newArgs);
};
}
/**
* Builds a partial application of a ternary function so that its first parameter
* is expected as the last one.<br/>
* The <code>shouldAritize</code> parameter is for the "reduce" functions, where
* the absence of the <code>initialValue</code> transforms a "fold" operation into a
* "reduce" one.
* @private
* @param {Function} fn
* @param {Boolean} shouldAritize
* @returns {Function}
*/
function _makePartial3 (fn, shouldAritize) {
return function (a, b) {
var f = shouldAritize && arguments.length !== 2 ? binary(fn) : fn;
return partial(f, [__, a, b]);
};
}
/**
* A curried version of {@link module:lamb.clamp|clamp}, expecting a <code>min</code>
* and a <code>max</code> value, that builds a function waiting for the number to clamp.
* @example
* _.clampWithin(0, 10)(-5) // => 0
* _.clampWithin(0, 10)(5) // => 5
* _.clampWithin(0, 10)(15) // => 10
* _.clampWithin(0, 10)(0) // => 0
* _.clampWithin(0, 10)(10) // => 10
* _.is(_.clampWithin(0, 10)(-0), -0) // => true
* _.clampWithin(20, 15)(10) // => NaN
*
* @memberof module:lamb
* @category Math
* @function
* @see {@link module:lamb.clamp|clamp}
* @since 0.47.0
* @param {Number} min
* @param {Number} max
* @returns {Function}
*/
var clampWithin = _makePartial3(clamp);
/**
* The I combinator. Any value passed to the function is simply returned as it is.
* @example
* var foo = {bar: "baz"};
*
* _.identity(foo) === foo // true
*
* @memberof module:lamb
* @category Function
* @see [SKI combinator calculus]{@link https://en.wikipedia.org/wiki/SKI_combinator_calculus}
* @since 0.1.0
* @param {*} value
* @returns {*} The value passed as parameter.
*/
function identity (value) {
return value;
}
/**
* Returns a function that is the composition of the functions given as parameters.
* The first function consumes the result of the function that follows.
* @example
* var sayHi = function (name) { return "Hi, " + name; };
* var capitalize = function (s) {
* return s[0].toUpperCase() + s.substr(1).toLowerCase();
* };
* var fixNameAndSayHi = _.compose(sayHi, capitalize);
*
* sayHi("bOb") // => "Hi, bOb"
* fixNameAndSayHi("bOb") // "Hi, Bob"
*
* var users = [{name: "fred"}, {name: "bOb"}];
* var sayHiToUser = _.compose(fixNameAndSayHi, _.getKey("name"));
*
* _.map(users, sayHiToUser) // ["Hi, Fred", "Hi, Bob"]
*
* @memberof module:lamb
* @category Function
* @see {@link module:lamb.pipe|pipe}
* @since 0.1.0
* @param {Function} a
* @param {Function} b
* @returns {Function}
*/
function compose (a, b) {
return arguments.length ? function () {
return a.call(this, b.apply(this, arguments));
} : identity;
}
var MAX_ARRAY_LENGTH = 4294967295;
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Converts a value to a valid array length, thus an integer within
* <code>0</code> and <code>2<sup>32</sup> - 1</code> (both included).
* @private
* @param {*} value
* @returns {Number}
*/
function _toArrayLength (value) {
return clamp(value, 0, MAX_ARRAY_LENGTH) >>> 0;
}
/**
* Executes the provided <code>iteratee</code> for each element of the given array-like object.<br/>
* Note that unlike the native array method this function doesn't skip unassigned or deleted indexes.
* @example <caption>Adding a CSS class to all elements of a NodeList in a browser environment:</caption>
* var addClass = _.curry(function (className, element) {
* element.classList.add(className);
* });
* var paragraphs = document.querySelectorAll("#some-container p");
*
* _.forEach(paragraphs, addClass("main"));
* // each "p" element in the container will have the "main" class now
*
* @memberof module:lamb
* @category Array
* @since 0.1.0
* @param {ArrayLike} arrayLike
* @param {ListIteratorCallback} iteratee
* @returns {Undefined}
*/
function forEach (arrayLike, iteratee) {
for (var i = 0, len = _toArrayLength(arrayLike.length); i < len; i++) {
iteratee(arrayLike[i], i, arrayLike);
}
}
/**
* Creates generic functions out of methods.
* @author A very little change on a great idea by [Irakli Gozalishvili]{@link https://github.com/Gozala/}.
* Thanks for this *beautiful* one-liner (never liked your "unbind" naming choice, though).
* @memberof module:lamb
* @category Function
* @function
* @example
* var join = _.generic(Array.prototype.join);
*
* join([1, 2, 3, 4, 5], "-") // => "1-2-3-4-5"
*
* // the function will work with any array-like object
* join("hello", "-") // => "h-e-l-l-o"
*
* @since 0.1.0
* @param {Function} method
* @returns {Function}
*/
var generic = Function.bind.bind(Function.call);
/**
* Verifies if a value is <code>null</code>.
* @example
* _.isNull(null) // => true
* _.isNull(void 0) // => false
* _.isNull(false) // => false
*
* @memberof module:lamb
* @category Type
* @see {@link module:lamb.isNil|isNil} if you want to check for <code>undefined</code> too.
* @since 0.1.0
* @param {*} value
* @returns {Boolean}
*/
function isNull (value) {
return value === null;
}
/**
* Verifies if a value is <code>undefined</code>.
* @example
* _.isUndefined(null) // => false
* _.isUndefined(void 0) // => true
* _.isUndefined(false) // => false
*
* @memberof module:lamb
* @category Type
* @see {@link module:lamb.isNil|isNil} if you want to check for <code>null</code> too.
* @since 0.1.0
* @param {*} value
* @returns {Boolean}
*/
function isUndefined (value) {
return value === void 0;
}
/**
* Verifies if a value is <code>null</code> or <code>undefined</code>.
* @example
* _.isNil(NaN) // => false
* _.isNil({}) // => false
* _.isNil(null) // => true
* _.isNil(void 0) // => true
* _.isNil() // => true
*
* @memberof module:lamb
* @category Type
* @see {@link module:lamb.isNull|isNull}
* @see {@link module:lamb.isUndefined|isUndefined}
* @since 0.1.0
* @param {*} value
* @returns {Boolean}
*/
function isNil (value) {
return isNull(value) || isUndefined(value);
}
/**
* Curries a function of arity 2.
* @private
* @param {Function} fn
* @param {Boolean} [isRightCurry=false]
* @returns {Function}
*/
function _curry2 (fn, isRightCurry) {
return function (a) {
return function (b) {
return isRightCurry ? fn.call(this, b, a) : fn.call(this, a, b);
};
};
}
/**
* A curried version of {@link module:lamb.areSVZ|areSVZ}.<br/>
* Accepts a value and builds a predicate that checks whether the value
* and the one received by the predicate are the same using the "SameValueZero"
* comparison.<br/>
* See also {@link module:lamb.areSame|areSame} and {@link module:lamb.is|is}
* to perform a "SameValue" comparison.
* @example
* var john = {name: "John", surname: "Doe"};
* var isJohn = _.isSVZ(john);
* var isZero = _.isSVZ(0);
* var isReallyNaN = _.isSVZ(NaN);
*
* isJohn(john) // => true
* isJohn({name: "John", surname: "Doe"}) // => false
*
* isZero(0) // => true
* isZero(-0) // => true
*
* isNaN(NaN) // => true
* isNaN("foo") // => true
*
* isReallyNaN(NaN) // => true
* isReallyNaN("foo") // => false
*
* @memberof module:lamb
* @category Logic
* @function
* @see {@link module:lamb.areSVZ|areSVZ}
* @see {@link module:lamb.areSame|areSame}, {@link module:lamb.is|is}
* @see [SameValue comparison]{@link https://www.ecma-international.org/ecma-262/7.0/#sec-samevalue}
* @see [SameValueZero comparison]{@link https://www.ecma-international.org/ecma-262/7.0/#sec-samevaluezero}
* @since 0.1.0
* @param {*} value
* @returns {Function}
*/
var isSVZ = _curry2(areSVZ);
/**
* Builds a new array by applying the iteratee function to each element of the
* received array-like object.<br/>
* Note that unlike the native array method this function doesn't skip unassigned or deleted indexes.
* @example
* _.map(["Joe", "Mario", "Jane"], _.invoker("toUpperCase")) // => ["JOE", "MARIO", "JANE"]
*
* _.map([4, 9, 16], Math.sqrt); // => [2, 3, 4]
*
* @memberof module:lamb
* @category Array
* @see {@link module:lamb.mapWith|mapWith}
* @see {@link module:lamb.flatMap|flatMap}, {@link module:lamb.flatMapWith|flatMapWith}
* @since 0.1.0
* @param {ArrayLike} arrayLike
* @param {ListIteratorCallback} iteratee
* @returns {Array}
*/
function map (arrayLike, iteratee) {
var len = _toArrayLength(arrayLike.length);
var result = Array(len);
for (var i = 0; i < len; i++) {
result[i] = iteratee(arrayLike[i], i, arrayLike);
}
return result;
}
/**
* A curried version of {@link module:lamb.map|map} that uses the provided iteratee to
* build a function expecting the array-like object to act upon.
* @example
* var square = function (n) { return n * n; };
* var getSquares = _.mapWith(square);
*
* getSquares([1, 2, 3, 4, 5]) // => [1, 4, 9, 16, 25]
*
* @memberof module:lamb
* @category Array
* @function
* @see {@link module:lamb.map|map}
* @see {@link module:lamb.flatMap|flatMap}, {@link module:lamb.flatMapWith|flatMapWith}
* @since 0.1.0
* @param {ListIteratorCallback} iteratee
* @returns {function}
*/
var mapWith = _curry2(map, true);
/**
* Like {@link module:lamb.partial|partial} will build a partially applied function and
* it will accept placeholders.<br/>
* The difference is that the bound arguments will be appended to the ones received by
* the resulting function.
* @example
* <caption>Explaining the difference with <code>partial</code>:</caption>
* var f1 = _.partial(_.list, ["a", "b", "c"]);
* var f2 = _.partialRight(_.list, ["a", "b", "c"]);
*
* f1("d", "e") // => ["a", "b", "c", "d", "e"]
* f2("d", "e") // => ["d", "e", "a", "b", "c"]
*
* @example
* <caption>Explaining placeholder substitutions:</caption>
* var __ = _.__;
* var f1 = _.partial(_.list, ["a", __, __, "d"]);
* var f2 = _.partialRight(_.list, ["a", __, __, "d"]);
*
* f1("b", "c", "e") // => ["a", "b", "c", "d", "e"]
* f2("b", "c", "e") // => ["b", "a", "c", "e", "d"]
*
* @memberof module:lamb
* @category Function
* @see {@link module:lamb.partial|partial}
* @see {@link module:lamb.asPartial|asPartial}
* @see {@link module:lamb.curry|curry}, {@link module:lamb.curryRight|curryRight}
* @see {@link module:lamb.curryable|curryable}, {@link module:lamb.curryableRight|curryableRight}
* @see {@link module:lamb.__|__} The placeholder object.
* @param {Function} fn
* @param {Array} args
* @since 0.52.0
* @returns {Function}
*/
function partialRight (fn, args) {
return function () {
if (!Array.isArray(args)) {
return fn.apply(this, arguments);
}
var lastIdx = arguments.length - 1;
var argsLen = args.length;
var boundArgs = Array(argsLen);
var newArgs = [];
for (var i = argsLen - 1, boundArg; i > -1; i--) {
boundArg = args[i];
boundArgs[i] = boundArg === __ ? arguments[lastIdx--] : boundArg;
}
for (i = 0; i <= lastIdx; i++) {
newArgs[i] = arguments[i];
}
for (var j = 0; j < argsLen; j++) {
newArgs[i++] = boundArgs[j];
}
return fn.apply(this, newArgs);
};
}
/**
* Builds a reduce function. The <code>step</code> parameter must be <code>1</code>
* to build {@link module:lamb.reduce|reduce} and <code>-1</code> to build
* {@link module:lamb.reduceRight|reduceRight}.
* @private
* @param {Number} step
* @returns {Function}
*/
function _makeReducer (step) {
return function (arrayLike, accumulator, initialValue) {
var len = _toArrayLength(arrayLike.length);
var idx = step === 1 ? 0 : len - 1;
var nCalls;
var result;
if (arguments.length === 3) {
nCalls = len;
result = initialValue;
} else {
if (len === 0) {
throw new TypeError("Reduce of empty array-like with no initial value");
}
result = arrayLike[idx];
idx += step;
nCalls = len - 1;
}
for (; nCalls--; idx += step) {
result = accumulator(result, arrayLike[idx], idx, arrayLike);
}
return result;
};
}
/**
* Reduces (or folds) the values of an array-like object, starting from the first, to a new
* value using the provided <code>accumulator</code> function.<br/>
* Note that unlike the native array method this function doesn't skip unassigned or deleted indexes.
* @example
* _.reduce([1, 2, 3, 4], _.sum) // => 10
*
* @memberof module:lamb
* @category Array
* @function
* @see {@link module:lamb.reduceRight|reduceRight}
* @see {@link module:lamb.reduceWith|reduceWith}, {@link module:lamb.reduceRightWith|reduceRightWith}
* @since 0.1.0
* @param {ArrayLike} arrayLike
* @param {AccumulatorCallback} accumulator
* @param {*} [initialValue]
* @returns {*}
*/
var reduce = _makeReducer(1);
/**
* A partial application of {@link module:lamb.reduce|reduce} that uses the
* provided <code>accumulator</code> and the optional <code>initialValue</code> to
* build a function expecting the array-like object to act upon.
* @example
* var arr = [1, 2, 3, 4, 5];
*
* _.reduceWith(_.sum)(arr) // => 15
* _.reduceWith(_.subtract)(arr) // => -13
* _.reduceWith(_.subtract, 0)(arr) // => -15
*
* @memberof module:lamb
* @category Array
* @function
* @see {@link module:lamb.reduceRightWith|reduceRightWith}
* @see {@link module:lamb.reduce|reduce}, {@link module:lamb.reduce|reduceRight}
* @since 0.27.0
* @param {AccumulatorCallback} accumulator
* @param {*} [initialValue]
* @returns {Function}
*/
var reduceWith = _makePartial3(reduce, true);
/**
* Converts a value to an integer.
* @private
* @param {*} value
* @returns {Number}
*/
function _toInteger (value) {
var n = +value;
if (n !== n) { // eslint-disable-line no-self-compare
return 0;
} else if (n % 1 === 0) {
return n;
} else {
return Math.floor(Math.abs(n)) * (n < 0 ? -1 : 1);
}
}
/**
* Builds an array by extracting a portion of an array-like object.<br/>
* Note that unlike the native array method this function ensures that dense
* arrays are returned.<br/>
* Also, unlike the native method, the <code>start</code> and <code>end</code>
* parameters aren't optional and will be simply converted to integer.<br/>
* See {@link module:lamb.dropFrom|dropFrom} and {@link module:lamb.drop|drop} if you want a
* slice to the end of the array-like.
* @example
* var arr = [1, 2, 3, 4, 5];
*
* _.slice(arr, 0, 2) // => [1, 2]
* _.slice(arr, 2, -1) // => [3, 4]
* _.slice(arr, -3, 5) // => [3, 4, 5]
*
* @memberof module:lamb
* @category Array
* @see {@link module:lamb.sliceAt|sliceAt}
* @see {@link module:lamb.dropFrom|dropFrom}, {@link module:lamb.drop|drop}
* @since 0.1.0
* @param {ArrayLike} arrayLike - Any array like object.
* @param {Number} start - Index at which to begin extraction.
* @param {Number} end - Index at which to end extraction. Extracts up to but not including end.
* @returns {Array}
*/
function slice (arrayLike, start, end) {
var len = _toArrayLength(arrayLike.length);
var begin = _toInteger(start);
var upTo = _toInteger(end);
if (begin < 0) {
begin = begin < -len ? 0 : begin + len;
}
if (upTo < 0) {
upTo = upTo < -len ? 0 : upTo + len;
} else if (upTo > len) {
upTo = len;
}
var resultLen = upTo - begin;
var result = resultLen > 0 ? Array(resultLen) : [];
for (var i = 0; i < resultLen; i++) {
result[i] = arrayLike[begin + i];
}
return result;
}
/**
* Given the <code>start</code> and <code>end</code> bounds, builds a partial application
* of {@link module:lamb.slice|slice} expecting the array-like object to slice.<br/>
* See also {@link module:lamb.dropFrom|dropFrom} and {@link module:lamb.drop|drop} if you want a
* slice to the end of the array-like.
* @example
* var arr = [1, 2, 3, 4, 5];
* var s = "hello";
* var dropFirstAndLast = _.sliceAt(1, -1);
*
* dropFirstAndLast(arr) // => [2, 3, 4]
* dropFirstAndLast(s) // => ["e", "l", "l"]
*
* @memberof module:lamb
* @category Array
* @function
* @see {@link module:lamb.slice|slice}
* @see {@link module:lamb.dropFrom|dropFrom}, {@link module:lamb.drop|drop}
* @since 0.48.0
* @param {Number} start - Index at which to begin extraction.
* @param {Number} end - Index at which to end extraction. Extracts up to but not including end.
* @returns {Function}
*/
var sliceAt = _makePartial3(slice);
var objectProtoToString = Object.prototype.toString;
/**
* Retrieves the "type tag" from the given value.
* @example
* var x = 5;
* var y = new Number(5);
*
* typeof x // => "number"
* typeof y // => "object"
* _.type(x) // => "Number"
* _.type(y) // => "Number"
*
* _.type(Object.prototype.toString) // => "Function"
* _.type(/a/) // => "RegExp"
*
* @memberof module:lamb
* @category Type
* @see {@link module:lamb.isType|isType}
* @since 0.9.0
* @param {*} value
* @returns {String}
*/
function type (value) {
return objectProtoToString.call(value).slice(8, -1);
}
/**
* Appends the given value at the end of a copy of the provided array-like object.
* @example
* var arr = [1, 2, 3, 4];
*
* _.appendTo(arr, 5) // => [1, 2, 3, 4, 5]
* _.appendTo(arr, [5]) // => [1, 2, 3, 4, [5]]
*
* @memberof module:lamb
* @category Array
* @see {@link module:lamb.append|append}
* @see {@link module:lamb.insert|insert}, {@link module:lamb.insertAt|insertAt}
* @since 0.44.0
* @param {ArrayLike} arrayLike
* @param {*} value
* @returns {Array}
*/
function appendTo (arrayLike, value) {
return slice(arrayLike, 0, arrayLike.length).concat([value]);
}
/**
* A curried version of {@link module:lamb.appendTo|appendTo} that uses the value to append
* to build a function expecting the array-like object to act upon.
* @example
* var arr = [1, 2, 3, 4];
*
* _.append(5)(arr) // => [1, 2, 3, 4, 5]
* _.append([5])(arr) // => [1, 2, 3, 4, [5]]
*
* @memberof module:lamb
* @category Array
* @function
* @see {@link module:lamb.appendTo|appendTo}
* @see {@link module:lamb.insert|insert}, {@link module:lamb.insertAt|insertAt}
* @since 0.44.0
* @param {*} value
* @returns {Function}
*/
var append = _curry2(appendTo, true);
/**
* Checks if an array-like object contains the given value.<br/>
* Please note that the equality test is made with {@link module:lamb.areSVZ|areSVZ}; so you can
* check for <code>NaN</code>, but <code>0</code> and <code>-0</code> are the same value.<br/>
* See also {@link module:lamb.contains|contains} for a curried version building a predicate.
* @example
* var numbers = [0, 1, 2, 3, NaN];
*
* _.isIn(numbers, 1) // => true
* _.isIn(numbers, 0) // => true
* _.isIn(numbers, -0) // => true
* _.isIn(numbers, NaN) // => true
* _.isIn(numbers, 5) // => false
*
* @memberof module:lamb
* @category Array
* @see {@link module:lamb.contains|contains}
* @since 0.13.0
* @param {ArrayLike} arrayLike
* @param {*} value
* @returns {Boolean}
*/
function isIn (arrayLike, value) {
var result = false;
for (var i = 0, len = arrayLike.length; i < len; i++) {
if (areSVZ(value, arrayLike[i])) {
result = true;
break;
}
}
return result;
}
/**
* Builds a predicate to check if an array-like object contains the given value.<br/>
* Please note that the equality test is made with {@link module:lamb.areSVZ|areSVZ}; so you can
* check for <code>NaN</code>, but <code>0</code> and <code>-0</code> are the same value.<br/>
* See also {@link module:lamb.isIn|isIn} for an uncurried version.
* @example
* var containsNaN = _.contains(NaN);
*
* containsNaN([0, 1, 2, 3, NaN]) // => true
*
* @memberof module:lamb
* @category Array
* @function
* @see {@link module:lamb.isIn|isIn}
* @since 0.13.0
* @param {*} value
* @returns {Function}
*/
var contains = _curry2(isIn, true);
/**
* Builds a "grouping function" for an array-like object.
* @private
* @param {Function} makeValue
* @returns {Function}
*/
function _groupWith (makeValue) {
return function (arrayLike, iteratee) {
var result = {};
var len = arrayLike.length;
for (var i = 0, element, key; i < len; i++) {
element = arrayLike[i];
key = iteratee(element, i, arrayLike);
result[key] = makeValue(result[key], element);
}
return result;
};
}
/**
* Transforms an array-like object in a lookup table with the keys generated by the provided
* <code>iteratee</code>, having as values the count of matches for the key.
* @example
* var persons = [
* {"name": "Jane", "age": 12},
* {"name": "John", "age": 40},
* {"name": "Mario", "age": 17},
* {"name": "Paolo", "age": 15}
* ];
* var getAgeStatus = function (person) { return person.age >= 18 ? "adult" : "minor"; };
*
* _.count(persons, getAgeStatus) // => {"adult": 1, "minor": 3}
*
* @memberof module:lamb
* @category Array
* @function
* @see {@link module:lamb.countBy|countBy}
* @see {@link module:lamb.group|group}, {@link module:lamb.groupBy|groupBy}
* @see {@link module:lamb.index|index}, {@link module:lamb.indexBy|indexBy}
* @since 0.21.0
* @param {ArrayLike} arrayLike
* @param {ListIteratorCallback} iteratee
* @returns {Object}
*/
var count = _groupWith(function (a) {
return a ? ++a : 1;
});
/**
* A curried version of {@link module:lamb.count|count} that uses the provided iteratee to
* build a function expecting the array-like object to act upon.
* @example
* var persons = [
* {"name": "Jane", "city": "New York"},
* {"name": "John", "city": "New York"},
* {"name": "Mario", "city": "Rome"},
* {"name": "Paolo"}
* ];
* var getCityOrUnknown = _.adapter([_.getKey("city"), _.always("Unknown")]);
* var countByCity = _.countBy(getCityOrUnknown);
*
* countByCity(persons) // => {"New York": 2, "Rome": 1, "Unknown": 1}
*
* @memberof module:lamb
* @category Array
* @function
* @see {@link module:lamb.count|count}
* @see {@link module:lamb.group|group}, {@link module:lamb.groupBy|groupBy}
* @see {@link module:lamb.index|index}, {@link module:lamb.indexBy|indexBy}
* @since 0.21.0
* @param {ListIteratorCallback} iteratee
* @returns {Function}
*/
var countBy = _curry2(count, true);
/**
* Builds an array comprised of all values of the array-like object passing the <code>predicate</code>
* test.<br/>
* Note that unlike the native array method this function doesn't skip unassigned or deleted indexes.
* @example
* var isLowerCase = function (s) { return s.toLowerCase() === s; };
*
* _.filter(["Foo", "bar", "baZ"], isLowerCase) // => ["bar"]
*
* // the function will work with any array-like object
* _.filter("fooBAR", isLowerCase) // => ["f", "o", "o"]
*
* @memberof module:lamb
* @category Array
* @see {@link module:lamb.filterWith|filterWith}
* @param {ArrayLike} arrayLike
* @param {ListIteratorCallback} predicate
* @since 0.1.0
* @returns {Array}
*/
function filter (arrayLike, predicate) {
var len = arrayLike.length;
var result = [];
for (var i = 0; i < len; i++) {
predicate(arrayLike[i], i, arrayLike) && result.push(arrayLike[i]);
}
return result;
}
/**
* Returns a predicate that negates the given one.
* @example
* var isEven = function (n) { return n % 2 === 0; };
* var isOdd = _.not(isEven);
*
* isOdd(5) // => true
* isOdd(4) // => false
*
* @memberof module:lamb
* @category Logic
* @since 0.1.0
* @param {Function} predicate
* @returns {Function}
*/
function not (predicate) {
return function () {
return !predicate.apply(this, arguments);
};
}
/**
* Using the provided iteratee, builds a function that will return an array comprised of the
* unique elements of an array-like object. The values being compared are the ones returned by
* the iteratee.<br/>
* The equality test is made with the ["SameValueZero" comparison]{@link module:lamb.areSVZ|areSVZ}.<br/>
* When two values are considered equal, the first occurence will be the one included
* in the result array.<br/>
* See also {@link module:lamb.uniques|uniques} if you don't need to transform your values before the