forked from ramda/ramda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathramda.js
3803 lines (3569 loc) · 142 KB
/
ramda.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
// ramda.js 0.2.4
// https://github.com/CrossEye/ramda
// (c) 2013-2014 Scott Sauyet and Michael Hurley
// Ramda may be freely distributed under the MIT license.
// Ramda
// -----
// A practical functional library for Javascript programmers. Ramda is a collection of tools to make it easier to
// use Javascript as a functional programming language. (The name is just a silly play on `lambda`.)
// Basic Setup
// -----------
// Uses a technique from the [Universal Module Definition][umd] to wrap this up for use in Node.js or in the browser,
// with or without an AMD-style loader.
//
// [umd]: https://github.com/umdjs/umd/blob/master/returnExports.js
(function (root, factory) {if (typeof exports === 'object') {module.exports = factory(root);} else if (typeof define === 'function' && define.amd) {define(factory);} else {root.ramda = factory(root);}}(this, function (global) {
"use strict";
return (function() {
// This object is what is actually returned, with all the exposed functions attached as properties.
/**
* TODO: JSDoc-style documentation for this function
*/
var R = {};
// Internal Functions and Properties
// ---------------------------------
/**
* A reference to the `undefined` value.
*
* Note that this is defined as the result of calling an empty function because JSHint
* complains about these constructs:
*
* var undef = void 0;
* var undef = undefined;
*/
var undef = (function () {})();
/**
* Creates an alias for a public function.
*
* @private
* @category Internal
* @param {string} oldName The name of the public function to alias.
* @return {Function} A function decorated with the `is`, `are`, and `and` methods. Create
* an alias for the `oldName function by invoking any of these methods an passing it a
* string with the `newName` parameter.
* @example
*
* // Create an alias for `each` named `forEach`
* aliasFor('each').is('forEach');
*/
var aliasFor = function (oldName) {
var fn = function (newName) {
R[newName] = R[oldName];
return fn;
};
fn.is = fn.are = fn.and = fn;
return fn;
};
/**
* An optimized, private array `slice` implementation.
*
* @private
* @category Internal
* @param {Arguments|Array} args The array or arguments object to consider.
* @param {number} [from=0] The array index to slice from, inclusive.
* @param {number} [to=args.length] The array index to slice to, exclusive.
* @return {Array} A new, sliced array.
* @example
*
* _slice([1, 2, 3, 4, 5], 1, 3); //=> [2, 3]
*
* var firstThreeArgs = function(a, b, c, d) {
* return _slice(arguments, 0, 3);
* };
* firstThreeArgs(1, 2, 3, 4); //=> [1, 2, 3]
*/
var _slice = function _slice(args, from, to) {
from = (typeof from === "number" ) ? from : 0;
to = (typeof to === "number" ) ? to : args.length;
var length = to - from,
arr = new Array(length),
i = -1;
while (++i < length) {
arr[i] = args[from + i];
}
return arr;
};
/**
* Private `concat` function to merge two array-like objects.
*
* @private
* @category Internal
* @param {Array|Arguments} [set1=[]] An array-like object.
* @param {Array|Arguments} [set2=[]] An array-like object.
* @return {Array} A new, merged array.
* @example
*
* concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]
*/
var concat = function _concat(set1, set2) {
set1 = set1 || [];
set2 = set2 || [];
var length1 = set1.length,
length2 = set2.length,
result = new Array(length1 + length2);
for (var i = 0; i < length1; i++) {
result[i] = set1[i];
}
for (i = 0; i < length2; i++) {
result[i + length1] = set2[i];
}
return result;
};
// Private reference to toString function.
var toString = Object.prototype.toString;
/**
* Tests whether or not an object is an array.
*
* @private
* @category Internal
* @param {*} val The object to test.
* @return {boolean} `true` if `val` is an array, `false` otherwise.
* @example
*
* isArray([]); //=> true
* isArray(true); //=> false
* isArray({}); //=> false
*/
var isArray = Array.isArray || function _isArray(val) {
return val && val.length >= 0 && toString.call(val) === "[object Array]";
};
/**
* Creates a new version of `fn` that, when invoked, will return either:
* - A new function ready to accept one or more of `fn`'s remaining arguments, if all of
* `fn`'s expected arguments have not yet been provided
* - `fn`'s result if all of its expected arguments have been provided
*
* Optionally, you may provide an arity for the returned function.
*
* @static
* @memberOf R
* @category Function
* @param {Function} fn The function to curry.
* @param {number} [fnArity=fn.length] An optional arity for the returned function.
* @return {Function} A new, curried function.
* @example
*
* var addFourNumbers = function(a, b, c, d) {
* return a + b + c + d;
* };
*
* var curriedAddFourNumbers = curry(addFourNumbers);
* var f = curriedAddFourNumbers(1, 2);
* var g = f(3);
* g(4);//=> 10
*/
var curry = R.curry = function _curry(fn, fnArity) {
fnArity = typeof fnArity === "number" ? fnArity : fn.length;
function recurry(args) {
return arity(Math.max(fnArity - (args && args.length || 0), 0), function () {
if (arguments.length === 0) { throw NO_ARGS_EXCEPTION; }
var newArgs = concat(args, arguments);
if (newArgs.length >= fnArity) {
return fn.apply(this, newArgs);
}
else {
return recurry(newArgs);
}
});
}
return recurry([]);
};
var NO_ARGS_EXCEPTION = new TypeError('Function called with no arguments');
/**
* Optimized internal two-arity curry function.
*
* @private
* @category Function
* @param {Function} fn The function to curry.
* @return {boolean} `true` if `val` is an array, `false` otherwise.
* @example
*
* var addTwo = function(a, b) {
* return a + b;
* };
* var curriedAddTwo = curry2(addTwo);
*/
function curry2(fn) {
return function(a, b) {
switch (arguments.length) {
case 0: throw NO_ARGS_EXCEPTION;
case 1: return function(b) {
return fn(a, b);
};
}
return fn(a, b);
};
}
/**
* Optimized internal three-arity curry function.
*
* @private
* @category Function
* @param {Function} fn The function to curry.
* @return {boolean} `true` if `val` is an array, `false` otherwise.
* @example
*
* var addThree = function(a, b, c) {
* return a + b + c;
* };
* var curriedAddThree = curry2(addThree);
*/
function curry3(fn) {
return function(a, b, c) {
switch (arguments.length) {
case 0: throw NO_ARGS_EXCEPTION;
case 1: return curry2(function(b, c) {
return fn(a, b, c);
});
case 2: return function(c) {
return fn(a, b, c);
};
}
return fn(a, b, c);
};
}
/**
* Private function that determines whether or not a provided object has a given method.
* Does not ignore methods stored on the object's prototype chain. Used for dynamically
* dispatching Ramda methods to non-Array objects.
*
* @private
* @category Internal
* @param {Function} methodName The name of the method to check for.
* @param {Function} obj The object to test.
* @return {boolean} `true` has a given method, `false` otherwise.
* @example
*
* var person = { name: 'John' };
* person.shout = function() { alert(this.name); };
*
* hasMethod('shout', person); //=> true
* hasMethod('foo', person); //=> false
*/
var hasMethod = function _hasMethod(methodName, obj) {
return obj && !isArray(obj) && typeof obj[methodName] === 'function';
};
/**
* Private function that generates a parameter list based on the paremeter count passed in.
*
* @private
* @category Internal
* @param {number} n The number of parameters
* @return {string} The parameter list
* @example
*
* mkArgStr(1); //= "arg1"
* mkArgStr(2); //= "arg1, arg2"
* mkArgStr(3); //= "arg1, arg2, arg3"
*/
var mkArgStr = function _makeArgStr(n) {
var arr = [], idx = -1;
while (++idx < n) {
arr[idx] = "arg" + idx;
}
return arr.join(", ");
};
/**
* Wraps a function of any arity (including nullary) in a function that accepts exactly `n`
* parameters. Any extraneous parameters will not be passed to the supplied function.
*
* @static
* @memberOf R
* @category Function
* @param {number} n The desired arity of the new function.
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
* arity `n`.
* @example
*
* var takesTwoArgs = function(a, b) {
* return [a, b];
* };
* takesTwoArgs.length; //=> 2
* takesTwoArgs(1, 2); //=> [1, 2]
*
* var takesOneArg = ramda.nAry(1, takesTwoArgs);
* takesOneArg.length; //=> 1
* // Only `n` arguments are passed to the wrapped function
* takesOneArg(1, 2); //=> [1, undefined]
*/
var nAry = R.nAry = (function () {
var cache = {
0: function (func) {
return function () {
return func.call(this);
};
},
1: function (func) {
return function (arg0) {
return func.call(this, arg0);
};
},
2: function (func) {
return function (arg0, arg1) {
return func.call(this, arg0, arg1);
};
},
3: function (func) {
return function (arg0, arg1, arg2) {
return func.call(this, arg0, arg1, arg2);
};
}
};
// For example:
// cache[5] = function(func) {
// return function(arg0, arg1, arg2, arg3, arg4) {
// return func.call(this, arg0, arg1, arg2, arg3, arg4);
// }
// };
var makeN = function (n) {
var fnArgs = mkArgStr(n);
var body = [
" return function(" + fnArgs + ") {",
" return func.call(this" + (fnArgs ? ", " + fnArgs : "") + ");",
" }"
].join("\n");
return new Function("func", body);
};
return function _nAry(n, fn) {
return (cache[n] || (cache[n] = makeN(n)))(fn);
};
}());
/**
* Wraps a function of any arity (including nullary) in a function that accepts exactly 1
* parameter. Any extraneous parameters will not be passed to the supplied function.
*
* @static
* @memberOf R
* @category Function
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
* arity 1.
* @example
*
* var takesTwoArgs = function(a, b) {
* return [a, b];
* };
* takesTwoArgs.length; //=> 2
* takesTwoArgs(1, 2); //=> [1, 2]
*
* var takesOneArg = ramda.unary(1, takesTwoArgs);
* takesOneArg.length; //=> 1
* // Only 1 argument is passed to the wrapped function
* takesOneArg(1, 2); //=> [1, undefined]
*/
R.unary = function _unary(fn) {
return nAry(1, fn);
};
/**
* Wraps a function of any arity (including nullary) in a function that accepts exactly 2
* parameters. Any extraneous parameters will not be passed to the supplied function.
*
* @static
* @memberOf R
* @category Function
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
* arity 2.
* @example
*
* var takesThreeArgs = function(a, b, c) {
* return [a, b, c];
* };
* takesThreeArgs.length; //=> 3
* takesThreeArgs(1, 2, 3); //=> [1, 2, 3]
*
* var takesTwoArgs = ramda.binary(1, takesThreeArgs);
* takesTwoArgs.length; //=> 2
* // Only 2 arguments are passed to the wrapped function
* takesTwoArgs(1, 2, 3); //=> [1, 2, undefined]
*/
var binary = R.binary = function _binary(fn) {
return nAry(2, fn);
};
/**
* Wraps a function of any arity (including nullary) in a function that accepts exactly `n`
* parameters. Unlike `nAry`, which passes only `n` arguments to the wrapped function,
* functions produced by `arity` will pass all provided arguments to the wrapped function.
*
* @static
* @memberOf R
* @category Function
* @param {number} n The desired arity of the returned function.
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
* arity `n`.
* @example
*
* var takesTwoArgs = function(a, b) {
* return [a, b];
* };
* takesTwoArgs.length; //=> 2
* takesTwoArgs(1, 2); //=> [1, 2]
*
* var takesOneArg = ramda.unary(1, takesTwoArgs);
* takesOneArg.length; //=> 1
* // All arguments are passed through to the wrapped function
* takesOneArg(1, 2); //=> [1, 2]
*/
var arity = R.arity = (function () {
var cache = {
0: function (func) {
return function () {
return func.apply(this, arguments);
};
},
1: function (func) {
return function (arg0) {
return func.apply(this, arguments);
};
},
2: function (func) {
return function (arg0, arg1) {
return func.apply(this, arguments);
};
},
3: function (func) {
return function (arg0, arg1, arg2) {
return func.apply(this, arguments);
};
}
};
// For example:
// cache[5] = function(func) {
// return function(arg0, arg1, arg2, arg3, arg4) {
// return func.apply(this, arguments);
// }
// };
var makeN = function (n) {
var fnArgs = mkArgStr(n);
var body = [
" return function(" + fnArgs + ") {",
" return func.apply(this, arguments);",
" }"
].join("\n");
return new Function("func", body);
};
return function _arity(n, fn) {
return (cache[n] || (cache[n] = makeN(n)))(fn);
};
}());
/**
* Turns a named method of an object (or object prototype) into a function that can be
* called directly. Passing the optional `len` parameter restricts the returned function to
* the initial `len` parameters of the method.
*
* The returned function is curried and accepts `len + 1` parameters (or `method.length + 1`
* when `len` is not specified), and the final parameter is the target object.
*
* @static
* @memberOf R
* @category Function
* @param {string} name The name of the method to wrap.
* @param {Object} obj The object to search for the `name` method.
* @param [len] The desired arity of the wrapped method.
* @return {Function} A new function or `undefined` if the specified method is not found.
* @example
*
*
* var charAt = ramda.invoker('charAt', String.prototype);
* charAt(6, 'abcdefghijklm'); //=> 'g'
*
* var join = ramda.invoker('join', Array.prototype);
* var firstChar = charAt(0);
* join('', ramda.map(firstChar, ["light", "ampliifed", "stimulated", "emission", "radiation"]));
* //=> 'laser'
*/
var invoker = R.invoker = function _invoker(name, obj, len) {
var method = obj[name];
var length = len === undef ? method.length : len;
return method && curry(function () {
if (arguments.length) {
var target = Array.prototype.pop.call(arguments);
var targetMethod = target[name];
if (targetMethod == method) {
return targetMethod.apply(target, arguments);
}
}
return undef;
}, length + 1);
};
/**
* Accepts a function `fn` and any number of transformer functions and returns a new
* function. When the new function is invoked, it calls the function `fn` with parameters
* consisting of the result of calling each supplied handler on successive arguments to the
* new function. For example:
*
* ```javascript
* var useWithExample = invoke(someFn, transformerFn1, transformerFn2);
*
* // This invocation:
* useWithExample('x', 'y');
* // Is functionally equivalent to:
* someFn(transformerFn1('x'), transformerFn2('y'))
* ```
*
* If more arguments are passed to the returned function than transformer functions, those
* arguments are passed directly to `fn` as additional parameters. If you expect additional
* arguments that don't need to be transformed, although you can ignore them, it's best to
* pass an identity function so that the new function reports the correct arity.
*
* @static
* @memberOf R
* @category Function
* @param {Function} fn The function to wrap.
* @param {...Function} transformers A variable number of transformer functions
* @return {Function} The wrapped function.
* @example
*
* var double = function(y) { return y * 2; };
* var square = function(x) { return x * x; };
* var add = function(a, b) { return a + b; };
* // Adds any number of arguments together
* var addAll = function() {
* return ramda.reduce(add, 0, arguments);
* };
*
* // Basic example
* var addDoubleAndSquare = ramda.useWith(addAll, double, square);
*
* addDoubleAndSquare(10, 5); //≅ addAll(double(10), square(5));
* //=> 125
*
* // Example of passing more arguments than transformers
* addDoubleAndSquare(10, 5, 100); //≅ addAll(double(10), square(5), 100);
* //=> 225
*
* // But if you're expecting additional arguments that don't need transformation, it's best
* // to pass transformer functions so the resulting function has the correct arity
* var addDoubleAndSquareWithExtraParams = ramda.useWith(addAll, double, square, ramda.identity);
* addDoubleAndSquare(10, 5, 100); //≅ addAll(double(10), square(5), ramda.identity(100));
* //=> 225
*/
var useWith = R.useWith = function _useWith(fn /*, transformers */) {
var transformers = _slice(arguments, 1);
var tlen = transformers.length;
return curry(arity(tlen, function () {
var args = [], idx = -1;
while (++idx < tlen) {
args.push(transformers[idx](arguments[idx]));
}
return fn.apply(this, args.concat(_slice(arguments, tlen)));
}));
};
/**
* TODO: JSDoc-style documentation for this function
*/
// A two-step version of the `useWith` function. This would allow us to write `project`, currently written
// as `useWith(map, pickAll, identity)`, as, instead, `use(map).over(pickAll, identity)`, which is a bit
// more explicit.
// TODO: One of these versions should be eliminated eventually. So not worrying about the duplication for now.
R.use = function _use(fn) {
return {
over: function (/*transformers*/) {
var transformers = _slice(arguments, 0);
var tlen = transformers.length;
return curry(arity(tlen, function () {
var args = [], idx = -1;
while (++idx < tlen) {
args.push(transformers[idx](arguments[idx]));
}
return fn.apply(this, args.concat(_slice(arguments, tlen)));
}));
}
};
};
/**
* Iterate over an input `list`, calling a provided function `fn` for each element in the
* list.
*
* `fn` receives one argument: *(value)*.
*
* Note: `ramda.each` does not skip deleted or unassigned indices (sparse arrays), unlike
* the native `Array.prototype.forEach` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description
*
* Also note that, unlike `Array.prototype.forEach`, Ramda's `each` returns the original
* array.
*
* @static
* @memberOf R
* @category List
* @param {Function} fn The function to invoke. Receives one argument, `value`.
* @param {Array} list The list to iterate over.
* @return {Array} The original list.
* @example
*
* ramda.each(function(num) {
* console.log(num + 100);
* }, [1, 2, 3]); //=> [1, 2, 3]
* //-> 101
* //-> 102
* //-> 103
*/
function each(fn, list) {
var idx = -1, len = list.length;
while (++idx < len) {
fn(list[idx]);
}
// i can't bear not to return *something*
return list;
}
R.each = curry2(each);
/**
* Like `each`, but but passes additional parameters to the predicate function.
*
* `fn` receives three arguments: *(value, index, list)*.
*
* Note: `ramda.each.idx` does not skip deleted or unassigned indices (sparse arrays),
* unlike the native `Array.prototype.forEach` method. For more details on this behavior,
* see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description
*
* Also note that, unlike `Array.prototype.forEach`, Ramda's `each` returns the original
* array.
*
* @static
* @memberOf R
* @category List
* @alias forEach
* @param {Function} fn The function to invoke. Receives three arguments: (`value`, `index`,
* `list`).
* @param {Array} list The list to iterate over.
* @return {Array} The original list.
* @example
*
* // Note that having access to the original `list` allows for mutation. While you *can* do
* // this, it's very un-functional behavior:
* ramda.each.idx(function(num, idx, list) {
* list[idx] = num + 100;
* }, [1, 2, 3]); //=> [101, 102, 103]
*/
R.each.idx = curry2(function eachIdx(fn, list) {
var idx = -1, len = list.length;
while (++idx < len) {
fn(list[idx], idx, list);
}
// i can't bear not to return *something*
return list;
});
aliasFor("each").is("forEach");
/**
* Creates a shallow copy of an array.
*
* @static
* @memberOf R
* @category Array
* @param {Array} list The list to clone.
* @return {Array} A new copy of the original list.
* @example
*
* var numbers = [1, 2, 3];
* var numbersClone = ramda.clone(numbers); //=> [1, 2, 3]
* numbers === numbersClone; //=> false
*
* // Note that this is a shallow clone--it does not clone complex values:
* var objects = [{}, {}, {}];
* var objectsClone = ramda.clone(objects);
* objects[0] === objectsClone[0]; //=> true
*/
var clone = R.clone = function _clone(list) {
return _slice(list);
};
// Core Functions
// --------------
//
/**
* Reports whether an array is empty.
*
* @static
* @memberOf R
* @category Array
* @param {Array} arr The array to consider.
* @return {boolean} `true` if the `arr` argument has a length of 0 or if `arr` is a falsy
* value (e.g. undefined).
* @example
*
* ramda.isEmpty([1, 2, 3]); //=> false
* ramda.isEmpty([]); //=> true
* ramda.isEmpty(); //=> true
* ramda.isEmpty(null); //=> true
*/
function isEmpty(arr) {
return !arr || !arr.length;
}
R.isEmpty = isEmpty;
/**
* Returns a new list with the given element at the front, followed by the contents of the
* list.
*
* @static
* @memberOf R
* @category Array
* @alias cons
* @param {*} el The item to add to the head of the output list.
* @param {Array} arr The array to add to the tail of the output list.
* @return {Array} A new array.
* @example
*
* ramda.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum']
*/
function prepend(el, arr) {
return concat([el], arr);
}
R.prepend = prepend;
aliasFor("prepend").is("cons");
/**
* Returns the first element in a list.
*
* @static
* @memberOf R
* @category Array
* @alias car, first
* @param {Array} [arr=[]] The array to consider.
* @return {*} The first element of the list, or `undefined` if the list is empty.
* @example
*
* ramda.head(['fi', 'fo', 'fum']); //=> 'fi'
*/
var head = R.head = function _car(arr) {
arr = arr || [];
return arr[0];
};
aliasFor("head").is("car").and("first");
/**
* Returns the last element from a list.
*
* @static
* @memberOf R
* @category Array
* @param {Array} [arr=[]] The array to consider.
* @return {*} The last element of the list, or `undefined` if the list is empty.
* @example
*
* ramda.last(['fi', 'fo', 'fum']); //=> 'fum'
*/
R.last = function _last(arr) {
arr = arr || [];
return arr[arr.length - 1];
};
/**
* Returns all but the first element of a list. If the list provided has the `tail` method,
* it will instead return `list.tail()`.
*
* @static
* @memberOf R
* @category Array
* @alias cdr
* @param {Array} [arr=[]] The array to consider.
* @return {Array} A new array containing all but the first element of the input list, or an
* empty list if the input list is a falsy value (e.g. `undefined`).
* @example
*
* ramda.tail(['fi', 'fo', 'fum']); //=> ['fo', 'fum']
*/
var tail = R.tail = function _cdr(arr) {
arr = arr || [];
if (hasMethod('tail', arr)) {
return arr.tail();
}
return (arr.length > 1) ? _slice(arr, 1) : [];
};
aliasFor("tail").is("cdr");
/**
* Returns `true` if the argument is an atom; `false` otherwise. An atom is defined as any
* value that is not an array, `undefined`, or `null`.
*
* @static
* @memberOf R
* @category Array
* @param {*} x The element to consider.
* @return {boolean} `true` if `x` is an atom, and `false` otherwise.
* @example
*
* ramda.isAtom([]); //=> false
* ramda.isAtom(null); //=> false
* ramda.isAtom(undefined); //=> false
*
* ramda.isAtom(0); //=> true
* ramda.isAtom(''); //=> true
* ramda.isAtom('test'); //=> true
* ramda.isAtom({}); //=> true
*/
R.isAtom = function _isAtom(x) {
return x != null && !isArray(x);
};
/**
* Returns a new list containing the contents of the given list, followed by the given
* element.
*
* @static
* @memberOf R
* @category Array
* @alias push
* @param {*} el The element to add to the end of the new list.
* @param {Array} list The list whose contents will be added to the beginning of the output
* list.
* @return {Array} A new list containing the contents of the old list followed by `el`.
* @example
*
* ramda.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests']
* ramda.append('tests', []); //=> ['tests']
* ramda.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']]
*/
var append = R.append = function _append(el, list) {
return concat(list, [el]);
};
aliasFor("append").is("push");
/**
* Returns a new list consisting of the elements of the first list followed by the elements
* of the second.
*
* @static
* @memberOf R
* @category Array
* @param {Array} list1 The first list to merge.
* @param {Array} list2 The second set to merge.
* @return {Array} A new array consisting of the contents of `list1` followed by the
* contents of `list2`. If, instead of an {Array} for `list1`, you pass an object with a `concat`
* method on it, `concat` will call `list1.concat` and it the value of `list2`.
* @example
*
* ramda.concat([], []); //=> []
* ramda.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]
* ramda.concat("ABC", "DEF"); // "ABCDEF"
*/
R.concat = curry2(function(set1, set2) {
return (hasMethod('concat', set1)) ? set1.concat(set2) : concat(set1, set2);
});
/**
* A function that does nothing but return the parameter supplied to it. Good as a default
* or placeholder function.
*
* @static
* @memberOf R
* @category Core
* @alias I
* @param {*} x The value to return.
* @return {*} The input value, `x`.
* @example
*
* ramda.identity(1); //=> 1
*
* var obj = {};
* ramda.identity(obj) === obj; //=> true
*/
var identity = R.identity = function _I(x) {
return x;
};
aliasFor("identity").is("I");
/**
* Calls an input function `n` times, returning an array containing the results of those
* function calls.
*
* `fn` is passed one argument: The current value of `n`, which begins at `0` and is
* gradually incremented to `n - 1`.
*
* @static
* @memberOf R
* @category List
* @param {Function} fn The function to invoke. Passed one argument, the current value of `n`.
* @param {number} n A value between `0` and `n - 1`. Increments after each function call.
* @return {Array} An array containing the return values of all calls to `fn`.
* @example
*
* ramda.times(function(n) { return n; }, 5); //=> [0, 1, 2, 3, 4]
*/
R.times = curry2(function _times(fn, n) {
var arr = new Array(n);
var i = -1;
while (++i < n) {
arr[i] = fn(i);
}
return arr;
});
/**
* Returns a fixed list of size `n` containing a specified identical value.
*
* @static
* @memberOf R
* @category Array
* @param {*} value The value to repeat.
* @param {number} n The desired size of the output list.
* @return {Array} A new array containing `n` `value`s.
* @example
*
* ramda.repeatN('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi']
*
* var obj = {};
* var repeatedObjs = ramda.repeatN(obj, 5); //=> [{}, {}, {}, {}, {}]
* repeatedObjs[0] === repeatedObjs[1]; //=> true
*/
R.repeatN = curry2(function _repeatN(value, n) {
return R.times(R.always(value), n);
});
// Function functions :-)
// ----------------------
//
// These functions make new functions out of old ones.
/**
* Returns a new function which partially applies a value to a given function, where the
* function is a variadic function that cannot be curried.
*
* @private
* @category Function
* @param {Function} f The function to partially apply `a` onto.
* @param {*} a The argument to partially apply onto `f`.
* @return {Function} A new function.
* @example
*
* var addThree = function(a, b, c) {
* return a + b + c;
* };
* var partialAdd = partially(add, 1);
* partialAdd(2, 3); //=> 6
*
* // partialAdd is invoked immediately, even though it expects three arguments. This is
* // because, unlike many functions here, the result of `partially` is not a curried
* // function.
* partialAdd(2); //≅ addThree(1, 2, undefined) => NaN
*/
function partially(f, a){
return function() {
return f.apply(this, concat([a], arguments));
};
}
// --------
/**
* Basic, right-associative composition function. Accepts two functions and returns the
* composite function; this composite function represents the operation `var h = f(g(x))`,
* where `f` is the first argument, `g` is the second argument, and `x` is whatever