diff --git a/dist/ramda.js b/dist/ramda.js index f43abc26c..44e416957 100644 --- a/dist/ramda.js +++ b/dist/ramda.js @@ -1,4 +1,4 @@ -// Ramda v0.27.2 +// Ramda v0.28.0 // https://github.com/ramda/ramda // (c) 2013-2022 Scott Sauyet, Michael Hurley, and David Chambers // Ramda may be freely distributed under the MIT license. @@ -7,7 +7,7 @@ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.R = {})); -}(this, function (exports) { 'use strict'; +}(this, (function (exports) { 'use strict'; /** * A function that always returns `false`. Any passed in parameters are ignored. @@ -24,7 +24,9 @@ * * R.F(); //=> false */ - var F = function() {return false;}; + var F = function F() { + return false; + }; /** * A function that always returns `true`. Any passed in parameters are ignored. @@ -41,7 +43,9 @@ * * R.T(); //=> true */ - var T = function() {return true;}; + var T = function T() { + return true; + }; /** * A special placeholder value used to specify "gaps" within curried functions, @@ -70,12 +74,26 @@ * const greet = R.replace('{name}', R.__, 'Hello, {name}!'); * greet('Alice'); //=> 'Hello, Alice!' */ - var __ = {'@@functional/placeholder': true}; + var __ = { + '@@functional/placeholder': true + }; + + function _typeof(obj) { + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); + } function _isPlaceholder(a) { - return a != null && - typeof a === 'object' && - a['@@functional/placeholder'] === true; + return a != null && _typeof(a) === 'object' && a['@@functional/placeholder'] === true; } /** @@ -86,6 +104,7 @@ * @param {Function} fn The function to curry. * @return {Function} The curried function. */ + function _curry1(fn) { return function f1(a) { if (arguments.length === 0 || _isPlaceholder(a)) { @@ -104,23 +123,24 @@ * @param {Function} fn The function to curry. * @return {Function} The curried function. */ + function _curry2(fn) { return function f2(a, b) { switch (arguments.length) { case 0: return f2; + case 1: - return _isPlaceholder(a) - ? f2 - : _curry1(function(_b) { return fn(a, _b); }); + return _isPlaceholder(a) ? f2 : _curry1(function (_b) { + return fn(a, _b); + }); + default: - return _isPlaceholder(a) && _isPlaceholder(b) - ? f2 - : _isPlaceholder(a) - ? _curry1(function(_a) { return fn(_a, b); }) - : _isPlaceholder(b) - ? _curry1(function(_b) { return fn(a, _b); }) - : fn(a, b); + return _isPlaceholder(a) && _isPlaceholder(b) ? f2 : _isPlaceholder(a) ? _curry1(function (_a) { + return fn(_a, b); + }) : _isPlaceholder(b) ? _curry1(function (_b) { + return fn(a, _b); + }) : fn(a, b); } }; } @@ -142,6 +162,7 @@ * R.add(2, 3); //=> 5 * R.add(7)(10); //=> 17 */ + var add = _curry2(function add(a, b) { return Number(a) + Number(b); }); @@ -164,35 +185,83 @@ var len1 = set1.length; var len2 = set2.length; var result = []; - idx = 0; + while (idx < len1) { result[result.length] = set1[idx]; idx += 1; } + idx = 0; + while (idx < len2) { result[result.length] = set2[idx]; idx += 1; } + return result; } function _arity(n, fn) { /* eslint-disable no-unused-vars */ switch (n) { - case 0: return function() { return fn.apply(this, arguments); }; - case 1: return function(a0) { return fn.apply(this, arguments); }; - case 2: return function(a0, a1) { return fn.apply(this, arguments); }; - case 3: return function(a0, a1, a2) { return fn.apply(this, arguments); }; - case 4: return function(a0, a1, a2, a3) { return fn.apply(this, arguments); }; - case 5: return function(a0, a1, a2, a3, a4) { return fn.apply(this, arguments); }; - case 6: return function(a0, a1, a2, a3, a4, a5) { return fn.apply(this, arguments); }; - case 7: return function(a0, a1, a2, a3, a4, a5, a6) { return fn.apply(this, arguments); }; - case 8: return function(a0, a1, a2, a3, a4, a5, a6, a7) { return fn.apply(this, arguments); }; - case 9: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8) { return fn.apply(this, arguments); }; - case 10: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { return fn.apply(this, arguments); }; - default: throw new Error('First argument to _arity must be a non-negative integer no greater than ten'); + case 0: + return function () { + return fn.apply(this, arguments); + }; + + case 1: + return function (a0) { + return fn.apply(this, arguments); + }; + + case 2: + return function (a0, a1) { + return fn.apply(this, arguments); + }; + + case 3: + return function (a0, a1, a2) { + return fn.apply(this, arguments); + }; + + case 4: + return function (a0, a1, a2, a3) { + return fn.apply(this, arguments); + }; + + case 5: + return function (a0, a1, a2, a3, a4) { + return fn.apply(this, arguments); + }; + + case 6: + return function (a0, a1, a2, a3, a4, a5) { + return fn.apply(this, arguments); + }; + + case 7: + return function (a0, a1, a2, a3, a4, a5, a6) { + return fn.apply(this, arguments); + }; + + case 8: + return function (a0, a1, a2, a3, a4, a5, a6, a7) { + return fn.apply(this, arguments); + }; + + case 9: + return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) { + return fn.apply(this, arguments); + }; + + case 10: + return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { + return fn.apply(this, arguments); + }; + + default: + throw new Error('First argument to _arity must be a non-negative integer no greater than ten'); } } @@ -206,31 +275,34 @@ * @param {Function} fn The function to curry. * @return {Function} The curried function. */ + function _curryN(length, received, fn) { - return function() { + return function () { var combined = []; var argsIdx = 0; var left = length; var combinedIdx = 0; + while (combinedIdx < received.length || argsIdx < arguments.length) { var result; - if (combinedIdx < received.length && - (!_isPlaceholder(received[combinedIdx]) || - argsIdx >= arguments.length)) { + + if (combinedIdx < received.length && (!_isPlaceholder(received[combinedIdx]) || argsIdx >= arguments.length)) { result = received[combinedIdx]; } else { result = arguments[argsIdx]; argsIdx += 1; } + combined[combinedIdx] = result; + if (!_isPlaceholder(result)) { left -= 1; } + combinedIdx += 1; } - return left <= 0 - ? fn.apply(this, combined) - : _arity(left, _curryN(length, combined, fn)); + + return left <= 0 ? fn.apply(this, combined) : _arity(left, _curryN(length, combined, fn)); }; } @@ -276,10 +348,12 @@ * const g = f(3); * g(4); //=> 10 */ + var curryN = _curry2(function curryN(length, fn) { if (length === 1) { return _curry1(fn); } + return _arity(length, _curryN(length, [], fn)); }); @@ -298,7 +372,7 @@ * @since v0.15.0 * @category Function * @category List - * @sig ((a ... -> b) ... -> [a] -> *) -> ((a ..., Int, [a] -> b) ... -> [a] -> *) + * @sig (((a ...) -> b) ... -> [a] -> *) -> (((a ..., Int, [a]) -> b) ... -> [a] -> *) * @param {Function} fn A list iteration function that does not pass index or list to its callback * @return {Function} An altered list iteration function that passes (item, index, list) to its callback * @example @@ -307,17 +381,20 @@ * mapIndexed((val, idx) => idx + '-' + val, ['f', 'o', 'o', 'b', 'a', 'r']); * //=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r'] */ + var addIndex = _curry1(function addIndex(fn) { - return curryN(fn.length, function() { + return curryN(fn.length, function () { var idx = 0; var origFn = arguments[0]; var list = arguments[arguments.length - 1]; var args = Array.prototype.slice.call(arguments, 0); - args[0] = function() { + + args[0] = function () { var result = origFn.apply(this, _concat(arguments, [idx, list])); idx += 1; return result; }; + return fn.apply(this, args); }); }); @@ -330,39 +407,41 @@ * @param {Function} fn The function to curry. * @return {Function} The curried function. */ + function _curry3(fn) { return function f3(a, b, c) { switch (arguments.length) { case 0: return f3; + case 1: - return _isPlaceholder(a) - ? f3 - : _curry2(function(_b, _c) { return fn(a, _b, _c); }); + return _isPlaceholder(a) ? f3 : _curry2(function (_b, _c) { + return fn(a, _b, _c); + }); + case 2: - return _isPlaceholder(a) && _isPlaceholder(b) - ? f3 - : _isPlaceholder(a) - ? _curry2(function(_a, _c) { return fn(_a, b, _c); }) - : _isPlaceholder(b) - ? _curry2(function(_b, _c) { return fn(a, _b, _c); }) - : _curry1(function(_c) { return fn(a, b, _c); }); + return _isPlaceholder(a) && _isPlaceholder(b) ? f3 : _isPlaceholder(a) ? _curry2(function (_a, _c) { + return fn(_a, b, _c); + }) : _isPlaceholder(b) ? _curry2(function (_b, _c) { + return fn(a, _b, _c); + }) : _curry1(function (_c) { + return fn(a, b, _c); + }); + default: - return _isPlaceholder(a) && _isPlaceholder(b) && _isPlaceholder(c) - ? f3 - : _isPlaceholder(a) && _isPlaceholder(b) - ? _curry2(function(_a, _b) { return fn(_a, _b, c); }) - : _isPlaceholder(a) && _isPlaceholder(c) - ? _curry2(function(_a, _c) { return fn(_a, b, _c); }) - : _isPlaceholder(b) && _isPlaceholder(c) - ? _curry2(function(_b, _c) { return fn(a, _b, _c); }) - : _isPlaceholder(a) - ? _curry1(function(_a) { return fn(_a, b, c); }) - : _isPlaceholder(b) - ? _curry1(function(_b) { return fn(a, _b, c); }) - : _isPlaceholder(c) - ? _curry1(function(_c) { return fn(a, b, _c); }) - : fn(a, b, c); + return _isPlaceholder(a) && _isPlaceholder(b) && _isPlaceholder(c) ? f3 : _isPlaceholder(a) && _isPlaceholder(b) ? _curry2(function (_a, _b) { + return fn(_a, _b, c); + }) : _isPlaceholder(a) && _isPlaceholder(c) ? _curry2(function (_a, _c) { + return fn(_a, b, _c); + }) : _isPlaceholder(b) && _isPlaceholder(c) ? _curry2(function (_b, _c) { + return fn(a, _b, _c); + }) : _isPlaceholder(a) ? _curry1(function (_a) { + return fn(_a, b, c); + }) : _isPlaceholder(b) ? _curry1(function (_b) { + return fn(a, _b, c); + }) : _isPlaceholder(c) ? _curry1(function (_c) { + return fn(a, b, _c); + }) : fn(a, b, c); } }; } @@ -392,13 +471,18 @@ * @symb R.adjust(-1, f, [a, b]) = [a, f(b)] * @symb R.adjust(0, f, [a, b]) = [f(a), b] */ + var adjust = _curry3(function adjust(idx, fn, list) { - if (idx >= list.length || idx < -list.length) { + var len = list.length; + + if (idx >= len || idx < -len) { return list; } - var start = idx < 0 ? list.length : 0; - var _idx = start + idx; + + var _idx = (len + idx) % len; + var _list = _concat(list); + _list[_idx] = fn(list[_idx]); return _list; }); @@ -416,9 +500,7 @@ * _isArray({}); //=> false */ var _isArray = Array.isArray || function _isArray(val) { - return (val != null && - val.length >= 0 && - Object.prototype.toString.call(val) === '[object Array]'); + return val != null && val.length >= 0 && Object.prototype.toString.call(val) === '[object Array]'; }; function _isTransformer(obj) { @@ -430,53 +512,59 @@ * object in list position (last argument). If it is an array, executes [fn]. * Otherwise, if it has a function with one of the given method names, it will * execute that function (functor case). Otherwise, if it is a transformer, - * uses transducer [xf] to return a new transformer (transducer case). + * uses transducer created by [transducerCreator] to return a new transformer + * (transducer case). * Otherwise, it will default to executing [fn]. * * @private * @param {Array} methodNames properties to check for a custom implementation - * @param {Function} xf transducer to initialize if object is transformer + * @param {Function} transducerCreator transducer factory if object is transformer * @param {Function} fn default ramda implementation * @return {Function} A function that dispatches on object in list position */ - function _dispatchable(methodNames, xf, fn) { - return function() { + + function _dispatchable(methodNames, transducerCreator, fn) { + return function () { if (arguments.length === 0) { return fn(); } - var args = Array.prototype.slice.call(arguments, 0); - var obj = args.pop(); + + var obj = arguments[arguments.length - 1]; + if (!_isArray(obj)) { var idx = 0; + while (idx < methodNames.length) { if (typeof obj[methodNames[idx]] === 'function') { - return obj[methodNames[idx]].apply(obj, args); + return obj[methodNames[idx]].apply(obj, Array.prototype.slice.call(arguments, 0, -1)); } + idx += 1; } + if (_isTransformer(obj)) { - var transducer = xf.apply(null, args); + var transducer = transducerCreator.apply(null, Array.prototype.slice.call(arguments, 0, -1)); return transducer(obj); } } + return fn.apply(this, arguments); }; } function _reduced(x) { - return x && x['@@transducer/reduced'] ? x : - { - '@@transducer/value': x, - '@@transducer/reduced': true - }; + return x && x['@@transducer/reduced'] ? x : { + '@@transducer/value': x, + '@@transducer/reduced': true + }; } var _xfBase = { - init: function() { + init: function init() { return this.xf['@@transducer/init'](); }, - result: function(result) { - return this.xf['@@transducer/result'](result); + result: function result(_result) { + return this.xf['@@transducer/result'](_result); } }; @@ -485,22 +573,29 @@ this.f = f; this.all = true; } + XAll.prototype['@@transducer/init'] = _xfBase.init; - XAll.prototype['@@transducer/result'] = function(result) { + + XAll.prototype['@@transducer/result'] = function (result) { if (this.all) { result = this.xf['@@transducer/step'](result, true); } + return this.xf['@@transducer/result'](result); }; - XAll.prototype['@@transducer/step'] = function(result, input) { + + XAll.prototype['@@transducer/step'] = function (result, input) { if (!this.f(input)) { this.all = false; result = _reduced(this.xf['@@transducer/step'](result, false)); } + return result; }; - var _xall = _curry2(function _xall(f, xf) { return new XAll(f, xf); }); + var _xall = _curry2(function _xall(f, xf) { + return new XAll(f, xf); + }); /** * Returns `true` if all elements of the list match the predicate, `false` if @@ -526,14 +621,18 @@ * R.all(equals3)([3, 3, 3, 3]); //=> true * R.all(equals3)([3, 3, 1, 3]); //=> false */ + var all = _curry2(_dispatchable(['all'], _xall, function all(fn, list) { var idx = 0; + while (idx < list.length) { if (!fn(list[idx])) { return false; } + idx += 1; } + return true; })); @@ -554,16 +653,21 @@ * R.max(789, 123); //=> 789 * R.max('a', 'b'); //=> 'b' */ - var max = _curry2(function max(a, b) { return b > a ? b : a; }); + + var max = _curry2(function max(a, b) { + return b > a ? b : a; + }); function _map(fn, functor) { var idx = 0; var len = functor.length; var result = Array(len); + while (idx < len) { result[idx] = fn(functor[idx]); idx += 1; } + return result; } @@ -587,32 +691,56 @@ * _isArrayLike({}); //=> false * _isArrayLike({length: 10}); //=> false * _isArrayLike({0: 'zero', 9: 'nine', length: 10}); //=> true + * _isArrayLike({nodeType: 1, length: 1}) // => false */ + var _isArrayLike = _curry1(function isArrayLike(x) { - if (_isArray(x)) { return true; } - if (!x) { return false; } - if (typeof x !== 'object') { return false; } - if (_isString(x)) { return false; } - if (x.nodeType === 1) { return !!x.length; } - if (x.length === 0) { return true; } + if (_isArray(x)) { + return true; + } + + if (!x) { + return false; + } + + if (_typeof(x) !== 'object') { + return false; + } + + if (_isString(x)) { + return false; + } + + if (x.length === 0) { + return true; + } + if (x.length > 0) { return x.hasOwnProperty(0) && x.hasOwnProperty(x.length - 1); } + return false; }); function XWrap(fn) { this.f = fn; } - XWrap.prototype['@@transducer/init'] = function() { + + XWrap.prototype['@@transducer/init'] = function () { throw new Error('init not implemented on XWrap'); }; - XWrap.prototype['@@transducer/result'] = function(acc) { return acc; }; - XWrap.prototype['@@transducer/step'] = function(acc, x) { + + XWrap.prototype['@@transducer/result'] = function (acc) { + return acc; + }; + + XWrap.prototype['@@transducer/step'] = function (acc, x) { return this.f(acc, x); }; - function _xwrap(fn) { return new XWrap(fn); } + function _xwrap(fn) { + return new XWrap(fn); + } /** * Creates a function that is bound to a context. @@ -636,8 +764,9 @@ * // logs {a: 2} * @symb R.bind(f, o)(a, b) = f.call(o, a, b) */ + var bind = _curry2(function bind(fn, thisObj) { - return _arity(fn.length, function() { + return _arity(fn.length, function () { return fn.apply(thisObj, arguments); }); }); @@ -645,27 +774,35 @@ function _arrayReduce(xf, acc, list) { var idx = 0; var len = list.length; + while (idx < len) { acc = xf['@@transducer/step'](acc, list[idx]); + if (acc && acc['@@transducer/reduced']) { acc = acc['@@transducer/value']; break; } + idx += 1; } + return xf['@@transducer/result'](acc); } function _iterableReduce(xf, acc, iter) { var step = iter.next(); + while (!step.done) { acc = xf['@@transducer/step'](acc, step.value); + if (acc && acc['@@transducer/reduced']) { acc = acc['@@transducer/value']; break; } + step = iter.next(); } + return xf['@@transducer/result'](acc); } @@ -673,24 +810,28 @@ return xf['@@transducer/result'](obj[methodName](bind(xf['@@transducer/step'], xf), acc)); } - var symIterator = (typeof Symbol !== 'undefined') ? Symbol.iterator : '@@iterator'; - + var symIterator = typeof Symbol !== 'undefined' ? Symbol.iterator : '@@iterator'; function _reduce(fn, acc, list) { if (typeof fn === 'function') { fn = _xwrap(fn); } + if (_isArrayLike(list)) { return _arrayReduce(fn, acc, list); } + if (typeof list['fantasy-land/reduce'] === 'function') { return _methodReduce(fn, acc, list, 'fantasy-land/reduce'); } + if (list[symIterator] != null) { return _iterableReduce(fn, acc, list[symIterator]()); } + if (typeof list.next === 'function') { return _iterableReduce(fn, acc, list); } + if (typeof list.reduce === 'function') { return _methodReduce(fn, acc, list, 'reduce'); } @@ -702,47 +843,55 @@ this.xf = xf; this.f = f; } + XMap.prototype['@@transducer/init'] = _xfBase.init; XMap.prototype['@@transducer/result'] = _xfBase.result; - XMap.prototype['@@transducer/step'] = function(result, input) { + + XMap.prototype['@@transducer/step'] = function (result, input) { return this.xf['@@transducer/step'](result, this.f(input)); }; - var _xmap = _curry2(function _xmap(f, xf) { return new XMap(f, xf); }); + var _xmap = _curry2(function _xmap(f, xf) { + return new XMap(f, xf); + }); function _has(prop, obj) { return Object.prototype.hasOwnProperty.call(obj, prop); } var toString = Object.prototype.toString; - var _isArguments = (function() { - return toString.call(arguments) === '[object Arguments]' ? - function _isArguments(x) { return toString.call(x) === '[object Arguments]'; } : - function _isArguments(x) { return _has('callee', x); }; - }()); - - // cover IE < 9 keys issues - var hasEnumBug = !({toString: null}).propertyIsEnumerable('toString'); - var nonEnumerableProps = [ - 'constructor', 'valueOf', 'isPrototypeOf', 'toString', - 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString' - ]; - // Safari bug - var hasArgsEnumBug = (function() { + + var _isArguments = function () { + return toString.call(arguments) === '[object Arguments]' ? function _isArguments(x) { + return toString.call(x) === '[object Arguments]'; + } : function _isArguments(x) { + return _has('callee', x); + }; + }(); + + var hasEnumBug = !{ + toString: null + }.propertyIsEnumerable('toString'); + var nonEnumerableProps = ['constructor', 'valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; // Safari bug + + var hasArgsEnumBug = function () { + return arguments.propertyIsEnumerable('length'); - }()); + }(); var contains = function contains(list, item) { var idx = 0; + while (idx < list.length) { if (list[idx] === item) { return true; } + idx += 1; } + return false; }; - /** * Returns a list containing the names of all the enumerable own properties of * the supplied object. @@ -756,39 +905,47 @@ * @sig {k: v} -> [k] * @param {Object} obj The object to extract properties from * @return {Array} An array of the object's own properties. - * @see R.keysIn, R.values + * @see R.keysIn, R.values, R.toPairs * @example * * R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] */ - var keys = typeof Object.keys === 'function' && !hasArgsEnumBug ? - _curry1(function keys(obj) { - return Object(obj) !== obj ? [] : Object.keys(obj); - }) : - _curry1(function keys(obj) { - if (Object(obj) !== obj) { - return []; + + + var keys = typeof Object.keys === 'function' && !hasArgsEnumBug ? _curry1(function keys(obj) { + return Object(obj) !== obj ? [] : Object.keys(obj); + }) : _curry1(function keys(obj) { + if (Object(obj) !== obj) { + return []; + } + + var prop, nIdx; + var ks = []; + + var checkArgsLength = hasArgsEnumBug && _isArguments(obj); + + for (prop in obj) { + if (_has(prop, obj) && (!checkArgsLength || prop !== 'length')) { + ks[ks.length] = prop; } - var prop, nIdx; - var ks = []; - var checkArgsLength = hasArgsEnumBug && _isArguments(obj); - for (prop in obj) { - if (_has(prop, obj) && (!checkArgsLength || prop !== 'length')) { + } + + if (hasEnumBug) { + nIdx = nonEnumerableProps.length - 1; + + while (nIdx >= 0) { + prop = nonEnumerableProps[nIdx]; + + if (_has(prop, obj) && !contains(ks, prop)) { ks[ks.length] = prop; } + + nIdx -= 1; } - if (hasEnumBug) { - nIdx = nonEnumerableProps.length - 1; - while (nIdx >= 0) { - prop = nonEnumerableProps[nIdx]; - if (_has(prop, obj) && !contains(ks, prop)) { - ks[ks.length] = prop; - } - nIdx -= 1; - } - } - return ks; - }); + } + + return ks; + }); /** * Takes a function and @@ -813,7 +970,7 @@ * @param {Function} fn The function to be called on every element of the input `list`. * @param {Array} list The list to be iterated over. * @return {Array} The new list. - * @see R.transduce, R.addIndex + * @see R.transduce, R.addIndex, R.pluck, R.project * @example * * const double = x => x * 2; @@ -825,17 +982,20 @@ * @symb R.map(f, { x: a, y: b }) = { x: f(a), y: f(b) } * @symb R.map(f, functor_o) = functor_o.map(f) */ + var map = _curry2(_dispatchable(['fantasy-land/map', 'map'], _xmap, function map(fn, functor) { switch (Object.prototype.toString.call(functor)) { case '[object Function]': - return curryN(functor.length, function() { + return curryN(functor.length, function () { return fn.call(this, functor.apply(this, arguments)); }); + case '[object Object]': - return _reduce(function(acc, key) { + return _reduce(function (acc, key) { acc[key] = fn(functor[key]); return acc; }, {}, keys(functor)); + default: return _map(fn, functor); } @@ -850,7 +1010,7 @@ * @return {Boolean} */ var _isInteger = Number.isInteger || function _isInteger(n) { - return (n << 0) === n; + return n << 0 === n; }; /** @@ -879,71 +1039,12 @@ * @symb R.nth(0, [a, b, c]) = a * @symb R.nth(1, [a, b, c]) = b */ + var nth = _curry2(function nth(offset, list) { var idx = offset < 0 ? list.length + offset : offset; return _isString(list) ? list.charAt(idx) : list[idx]; }); - /** - * Retrieves the values at given paths of an object. - * - * @func - * @memberOf R - * @since v0.27.1 - * @category Object - * @typedefn Idx = [String | Int] - * @sig [Idx] -> {a} -> [a | Undefined] - * @param {Array} pathsArray The array of paths to be fetched. - * @param {Object} obj The object to retrieve the nested properties from. - * @return {Array} A list consisting of values at paths specified by "pathsArray". - * @see R.path - * @example - * - * R.paths([['a', 'b'], ['p', 0, 'q']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, 3] - * R.paths([['a', 'b'], ['p', 'r']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, undefined] - */ - var paths = _curry2(function paths(pathsArray, obj) { - return pathsArray.map(function(paths) { - var val = obj; - var idx = 0; - var p; - while (idx < paths.length) { - if (val == null) { - return; - } - p = paths[idx]; - val = _isInteger(p) ? nth(p, val) : val[p]; - idx += 1; - } - return val; - }); - }); - - /** - * Retrieve the value at a given path. - * - * @func - * @memberOf R - * @since v0.2.0 - * @category Object - * @typedefn Idx = String | Int - * @sig [Idx] -> {a} -> a | Undefined - * @param {Array} path The path to use. - * @param {Object} obj The object to retrieve the nested property from. - * @return {*} The data at `path`. - * @see R.prop, R.nth - * @example - * - * R.path(['a', 'b'], {a: {b: 2}}); //=> 2 - * R.path(['a', 'b'], {c: {b: 2}}); //=> undefined - * R.path(['a', 'b', 0], {a: {b: [1, 2, 3]}}); //=> 1 - * R.path(['a', 'b', -2], {a: {b: [1, 2, 3]}}); //=> 2 - */ - - var path = _curry2(function path(pathAr, obj) { - return paths([pathAr], obj)[0]; - }); - /** * Returns a function that when supplied an object returns the indicated * property of that object, if it exists. @@ -952,12 +1053,12 @@ * @memberOf R * @since v0.1.0 * @category Object - * @typedefn Idx = String | Int + * @typedefn Idx = String | Int | Symbol * @sig Idx -> {s: a} -> a | Undefined * @param {String|Number} p The property name or array index * @param {Object} obj The object to query * @return {*} The value at `obj.p`. - * @see R.path, R.nth + * @see R.path, R.props, R.pluck, R.project, R.nth * @example * * R.prop('x', {x: 100}); //=> 100 @@ -966,7 +1067,13 @@ * R.compose(R.inc, R.prop('x'))({ x: 3 }) //=> 4 */ - var prop = _curry2(function prop(p, obj) { return path([p], obj); }); + var prop = _curry2(function prop(p, obj) { + if (obj == null) { + return; + } + + return _isInteger(p) ? nth(p, obj) : obj[p]; + }); /** * Returns a new list by plucking the same named property off all objects in @@ -984,7 +1091,7 @@ * @param {Number|String} key The key name to pluck off of each object. * @param {Array} f The array or functor to consider. * @return {Array} The list of values for the given key. - * @see R.props + * @see R.project, R.prop, R.props * @example * * var getAges = R.pluck('age'); @@ -995,6 +1102,7 @@ * @symb R.pluck('x', [{x: 1, y: 2}, {x: 3, y: 4}, {x: 5, y: 6}]) = [1, 3, 5] * @symb R.pluck(0, [[1, 2], [3, 4], [5, 6]]) = [1, 3, 5] */ + var pluck = _curry2(function pluck(p, list) { return map(prop(p), list); }); @@ -1045,6 +1153,7 @@ * * @symb R.reduce(f, a, [b, c, d]) = f(f(f(a, b), c), d) */ + var reduce = _curry3(_reduce); /** @@ -1072,16 +1181,20 @@ * isQueenOfSpades({rank: 'Q', suit: '♣︎'}); //=> false * isQueenOfSpades({rank: 'Q', suit: '♠︎'}); //=> true */ + var allPass = _curry1(function allPass(preds) { - return curryN(reduce(max, 0, pluck('length', preds)), function() { + return curryN(reduce(max, 0, pluck('length', preds)), function () { var idx = 0; var len = preds.length; + while (idx < len) { if (!preds[idx].apply(this, arguments)) { return false; } + idx += 1; } + return true; }); }); @@ -1105,14 +1218,16 @@ * const t = R.always('Tee'); * t(); //=> 'Tee' */ + var always = _curry1(function always(val) { - return function() { + return function () { return val; }; }); /** - * Returns `true` if both arguments are `true`; `false` otherwise. + * Returns the first argument if it is falsy, otherwise the second argument. + * Acts as the boolean `and` statement if both inputs are `Boolean`s. * * @func * @memberOf R @@ -1121,8 +1236,8 @@ * @sig a -> b -> a | b * @param {Any} a * @param {Any} b - * @return {Any} the first argument if it is falsy, otherwise the second argument. - * @see R.both, R.xor + * @return {Any} + * @see R.both, R.or * @example * * R.and(true, true); //=> true @@ -1130,6 +1245,7 @@ * R.and(false, true); //=> false * R.and(false, false); //=> false */ + var and = _curry2(function and(a, b) { return a && b; }); @@ -1139,22 +1255,29 @@ this.f = f; this.any = false; } + XAny.prototype['@@transducer/init'] = _xfBase.init; - XAny.prototype['@@transducer/result'] = function(result) { + + XAny.prototype['@@transducer/result'] = function (result) { if (!this.any) { result = this.xf['@@transducer/step'](result, false); } + return this.xf['@@transducer/result'](result); }; - XAny.prototype['@@transducer/step'] = function(result, input) { + + XAny.prototype['@@transducer/step'] = function (result, input) { if (this.f(input)) { this.any = true; result = _reduced(this.xf['@@transducer/step'](result, true)); } + return result; }; - var _xany = _curry2(function _xany(f, xf) { return new XAny(f, xf); }); + var _xany = _curry2(function _xany(f, xf) { + return new XAny(f, xf); + }); /** * Returns `true` if at least one of the elements of the list match the predicate, @@ -1181,14 +1304,18 @@ * R.any(lessThan0)([1, 2]); //=> false * R.any(lessThan2)([1, 2]); //=> true */ + var any = _curry2(_dispatchable(['any'], _xany, function any(fn, list) { var idx = 0; + while (idx < list.length) { if (fn(list[idx])) { return true; } + idx += 1; } + return false; })); @@ -1218,16 +1345,20 @@ * isBlackCard({rank: 'Q', suit: '♠'}); //=> true * isBlackCard({rank: 'Q', suit: '♦'}); //=> false */ + var anyPass = _curry1(function anyPass(preds) { - return curryN(reduce(max, 0, pluck('length', preds)), function() { + return curryN(reduce(max, 0, pluck('length', preds)), function () { var idx = 0; var len = preds.length; + while (idx < len) { if (preds[idx].apply(this, arguments)) { return true; } + idx += 1; } + return false; }); }); @@ -1258,26 +1389,25 @@ * R.ap(R.concat, R.toUpper)('Ramda') //=> 'RamdaRAMDA' * @symb R.ap([f, g], [a, b]) = [f(a), f(b), g(a), g(b)] */ + var ap = _curry2(function ap(applyF, applyX) { - return ( - typeof applyX['fantasy-land/ap'] === 'function' - ? applyX['fantasy-land/ap'](applyF) - : typeof applyF.ap === 'function' - ? applyF.ap(applyX) - : typeof applyF === 'function' - ? function(x) { return applyF(x)(applyX(x)); } - : _reduce(function(acc, f) { return _concat(acc, map(f, applyX)); }, [], applyF) - ); + return typeof applyX['fantasy-land/ap'] === 'function' ? applyX['fantasy-land/ap'](applyF) : typeof applyF.ap === 'function' ? applyF.ap(applyX) : typeof applyF === 'function' ? function (x) { + return applyF(x)(applyX(x)); + } : _reduce(function (acc, f) { + return _concat(acc, map(f, applyX)); + }, [], applyF); }); function _aperture(n, list) { var idx = 0; var limit = list.length - (n - 1); var acc = new Array(limit >= 0 ? limit : 0); + while (idx < limit) { acc[idx] = Array.prototype.slice.call(list, idx, idx + n); idx += 1; } + return acc; } @@ -1287,30 +1417,36 @@ this.full = false; this.acc = new Array(n); } + XAperture.prototype['@@transducer/init'] = _xfBase.init; - XAperture.prototype['@@transducer/result'] = function(result) { + + XAperture.prototype['@@transducer/result'] = function (result) { this.acc = null; return this.xf['@@transducer/result'](result); }; - XAperture.prototype['@@transducer/step'] = function(result, input) { + + XAperture.prototype['@@transducer/step'] = function (result, input) { this.store(input); return this.full ? this.xf['@@transducer/step'](result, this.getCopy()) : result; }; - XAperture.prototype.store = function(input) { + + XAperture.prototype.store = function (input) { this.acc[this.pos] = input; this.pos += 1; + if (this.pos === this.acc.length) { this.pos = 0; this.full = true; } }; - XAperture.prototype.getCopy = function() { - return _concat(Array.prototype.slice.call(this.acc, this.pos), - Array.prototype.slice.call(this.acc, 0, this.pos) - ); + + XAperture.prototype.getCopy = function () { + return _concat(Array.prototype.slice.call(this.acc, this.pos), Array.prototype.slice.call(this.acc, 0, this.pos)); }; - var _xaperture = _curry2(function _xaperture(n, xf) { return new XAperture(n, xf); }); + var _xaperture = _curry2(function _xaperture(n, xf) { + return new XAperture(n, xf); + }); /** * Returns a new list, composed of n-tuples of consecutive elements. If `n` is @@ -1333,6 +1469,7 @@ * R.aperture(3, [1, 2, 3, 4, 5]); //=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]] * R.aperture(7, [1, 2, 3, 4, 5]); //=> [] */ + var aperture = _curry2(_dispatchable([], _xaperture, _aperture)); /** @@ -1355,6 +1492,7 @@ * R.append('tests', []); //=> ['tests'] * R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']] */ + var append = _curry2(function append(el, list) { return _concat(list, [el]); }); @@ -1379,6 +1517,7 @@ * R.apply(Math.max, nums); //=> 42 * @symb R.apply(f, [a, b, c]) = f(a, b, c) */ + var apply = _curry2(function apply(fn, args) { return fn.apply(this, args); }); @@ -1395,32 +1534,34 @@ * @sig {k: v} -> [v] * @param {Object} obj The object to extract values from * @return {Array} An array of the values of the object's own properties. - * @see R.valuesIn, R.keys + * @see R.valuesIn, R.keys, R.toPairs * @example * * R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3] */ + var values = _curry1(function values(obj) { var props = keys(obj); var len = props.length; var vals = []; var idx = 0; + while (idx < len) { vals[idx] = obj[props[idx]]; idx += 1; } + return vals; }); - // Use custom mapValues function to avoid issues with specs that include a "map" key and R.map // delegating calls to .map + function mapValues(fn, obj) { - return keys(obj).reduce(function(acc, key) { + return _isArray(obj) ? obj.map(fn) : keys(obj).reduce(function (acc, key) { acc[key] = fn(obj[key]); return acc; }, {}); } - /** * Given a spec object recursively mapping properties to functions, creates a * function producing an object of the same structure, by mapping each property @@ -1446,21 +1587,21 @@ * getMetrics(2, 4); // => { sum: 6, nested: { mul: 8 } } * @symb R.applySpec({ x: f, y: { z: g } })(a, b) = { x: f(a, b), y: { z: g(a, b) } } */ - var applySpec = _curry1(function applySpec(spec) { - spec = mapValues( - function(v) { return typeof v == 'function' ? v : applySpec(v); }, - spec - ); - - return curryN( - reduce(max, 0, pluck('length', values(spec))), - function() { - var args = arguments; - return mapValues(function(f) { return apply(f, args); }, spec); - }); - }); - /** + + var applySpec = _curry1(function applySpec(spec) { + spec = mapValues(function (v) { + return typeof v == 'function' ? v : applySpec(v); + }, spec); + return curryN(reduce(max, 0, pluck('length', values(spec))), function () { + var args = arguments; + return mapValues(function (f) { + return apply(f, args); + }, spec); + }); + }); + + /** * Takes a value and applies a function to it. * * This function is also known as the `thrush` combinator. @@ -1479,7 +1620,10 @@ * t42(R.identity); //=> 42 * t42(R.add(1)); //=> 43 */ - var applyTo = _curry2(function applyTo(x, f) { return f(x); }); + + var applyTo = _curry2(function applyTo(x, f) { + return f(x); + }); /** * Makes an ascending comparator function out of a function that returns a value @@ -1506,6 +1650,7 @@ * const peopleByYoungestFirst = R.sort(byAge, people); * //=> [{ name: 'Mikhail', age: 62 },{ name: 'Emma', age: 70 }, { name: 'Peter', age: 78 }] */ + var ascend = _curry3(function ascend(fn, a, b) { var aa = fn(a); var bb = fn(b); @@ -1518,28 +1663,29 @@ * properties onto the new object as well. All non-primitive properties are * copied by reference. * - * @func - * @memberOf R - * @since v0.8.0 - * @category Object - * @sig String -> a -> {k: v} -> {k: v} - * @param {String} prop The property name to set + * @private + * @param {String|Number} prop The property name to set * @param {*} val The new value - * @param {Object} obj The object to clone - * @return {Object} A new object equivalent to the original except for the changed property. - * @see R.dissoc, R.pick - * @example - * - * R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} + * @param {Object|Array} obj The object to clone + * @return {Object|Array} A new object equivalent to the original except for the changed property. */ - var assoc = _curry3(function assoc(prop, val, obj) { + + function _assoc(prop, val, obj) { + if (_isInteger(prop) && _isArray(obj)) { + var arr = [].concat(obj); + arr[prop] = val; + return arr; + } + var result = {}; + for (var p in obj) { result[p] = obj[p]; } + result[prop] = val; return result; - }); + } /** * Checks if the input value is `null` or `undefined`. @@ -1558,7 +1704,10 @@ * R.isNil(0); //=> false * R.isNil([]); //=> false */ - var isNil = _curry1(function isNil(x) { return x == null; }); + + var isNil = _curry1(function isNil(x) { + return x == null; + }); /** * Makes a shallow clone of an object, setting or overriding the nodes required @@ -1570,7 +1719,7 @@ * @memberOf R * @since v0.8.0 * @category Object - * @typedefn Idx = String | Int + * @typedefn Idx = String | Int | Symbol * @sig [Idx] -> a -> {a} -> {a} * @param {Array} path the path to set * @param {*} val The new value @@ -1584,22 +1733,46 @@ * // Any missing or non-object keys in path will be overridden * R.assocPath(['a', 'b', 'c'], 42, {a: 5}); //=> {a: {b: {c: 42}}} */ + var assocPath = _curry3(function assocPath(path, val, obj) { if (path.length === 0) { return val; } + var idx = path[0]; + if (path.length > 1) { - var nextObj = (!isNil(obj) && _has(idx, obj)) ? obj[idx] : _isInteger(path[1]) ? [] : {}; + var nextObj = !isNil(obj) && _has(idx, obj) ? obj[idx] : _isInteger(path[1]) ? [] : {}; val = assocPath(Array.prototype.slice.call(path, 1), val, nextObj); } - if (_isInteger(idx) && _isArray(obj)) { - var arr = [].concat(obj); - arr[idx] = val; - return arr; - } else { - return assoc(idx, val, obj); - } + + return _assoc(idx, val, obj); + }); + + /** + * Makes a shallow clone of an object, setting or overriding the specified + * property with the given value. Note that this copies and flattens prototype + * properties onto the new object as well. All non-primitive properties are + * copied by reference. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Object + * @typedefn Idx = String | Int + * @sig Idx -> a -> {k: v} -> {k: v} + * @param {String|Number} prop The property name to set + * @param {*} val The new value + * @param {Object} obj The object to clone + * @return {Object} A new object equivalent to the original except for the changed property. + * @see R.dissoc, R.pick + * @example + * + * R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} + */ + + var assoc = _curry3(function assoc(prop, val, obj) { + return assocPath([prop], val, obj); }); /** @@ -1632,20 +1805,66 @@ * @symb R.nAry(1, f)(a, b) = f(a) * @symb R.nAry(2, f)(a, b) = f(a, b) */ + var nAry = _curry2(function nAry(n, fn) { switch (n) { - case 0: return function() {return fn.call(this);}; - case 1: return function(a0) {return fn.call(this, a0);}; - case 2: return function(a0, a1) {return fn.call(this, a0, a1);}; - case 3: return function(a0, a1, a2) {return fn.call(this, a0, a1, a2);}; - case 4: return function(a0, a1, a2, a3) {return fn.call(this, a0, a1, a2, a3);}; - case 5: return function(a0, a1, a2, a3, a4) {return fn.call(this, a0, a1, a2, a3, a4);}; - case 6: return function(a0, a1, a2, a3, a4, a5) {return fn.call(this, a0, a1, a2, a3, a4, a5);}; - case 7: return function(a0, a1, a2, a3, a4, a5, a6) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6);}; - case 8: return function(a0, a1, a2, a3, a4, a5, a6, a7) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7);}; - case 9: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8);}; - case 10: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);}; - default: throw new Error('First argument to nAry must be a non-negative integer no greater than ten'); + case 0: + return function () { + return fn.call(this); + }; + + case 1: + return function (a0) { + return fn.call(this, a0); + }; + + case 2: + return function (a0, a1) { + return fn.call(this, a0, a1); + }; + + case 3: + return function (a0, a1, a2) { + return fn.call(this, a0, a1, a2); + }; + + case 4: + return function (a0, a1, a2, a3) { + return fn.call(this, a0, a1, a2, a3); + }; + + case 5: + return function (a0, a1, a2, a3, a4) { + return fn.call(this, a0, a1, a2, a3, a4); + }; + + case 6: + return function (a0, a1, a2, a3, a4, a5) { + return fn.call(this, a0, a1, a2, a3, a4, a5); + }; + + case 7: + return function (a0, a1, a2, a3, a4, a5, a6) { + return fn.call(this, a0, a1, a2, a3, a4, a5, a6); + }; + + case 8: + return function (a0, a1, a2, a3, a4, a5, a6, a7) { + return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7); + }; + + case 9: + return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) { + return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8); + }; + + case 10: + return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { + return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); + }; + + default: + throw new Error('First argument to nAry must be a non-negative integer no greater than ten'); } }); @@ -1658,7 +1877,7 @@ * @memberOf R * @since v0.2.0 * @category Function - * @sig (* -> c) -> (a, b -> c) + * @sig (a -> b -> c -> ... -> z) -> ((a, b) -> z) * @param {Function} fn The function to wrap. * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of * arity 2. @@ -1677,16 +1896,14 @@ * takesTwoArgs(1, 2, 3); //=> [1, 2, undefined] * @symb R.binary(f)(a, b, c) = f(a, b) */ + var binary = _curry1(function binary(fn) { return nAry(2, fn); }); function _isFunction(x) { var type = Object.prototype.toString.call(x); - return type === '[object Function]' || - type === '[object AsyncFunction]' || - type === '[object GeneratorFunction]' || - type === '[object AsyncGeneratorFunction]'; + return type === '[object Function]' || type === '[object AsyncFunction]' || type === '[object GeneratorFunction]' || type === '[object AsyncGeneratorFunction]'; } /** @@ -1706,15 +1923,16 @@ * const madd3 = R.liftN(3, (...args) => R.sum(args)); * madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7] */ + var liftN = _curry2(function liftN(arity, fn) { var lifted = curryN(arity, fn); - return curryN(arity, function() { + return curryN(arity, function () { return _reduce(ap, map(lifted, arguments[0]), Array.prototype.slice.call(arguments, 1)); }); }); /** - * "lifts" a function of arity > 1 so that it may "map over" a list, Function or other + * "lifts" a function of arity >= 1 so that it may "map over" a list, Function or other * object that satisfies the [FantasyLand Apply spec](https://github.com/fantasyland/fantasy-land#apply). * * @func @@ -1729,12 +1947,13 @@ * * const madd3 = R.lift((a, b, c) => a + b + c); * - * madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7] + * madd3([100, 200], [30, 40], [5, 6, 7]); //=> [135, 136, 137, 145, 146, 147, 235, 236, 237, 245, 246, 247] * * const madd5 = R.lift((a, b, c, d, e) => a + b + c + d + e); * - * madd5([1,2], [3], [4, 5], [6], [7, 8]); //=> [21, 22, 22, 23, 22, 23, 23, 24] + * madd5([10, 20], [1], [2, 3], [4], [100, 200]); //=> [117, 217, 118, 218, 127, 227, 128, 228] */ + var lift = _curry1(function lift(fn) { return liftN(fn.length, fn); }); @@ -1758,7 +1977,7 @@ * @param {Function} f A predicate * @param {Function} g Another predicate * @return {Function} a function that applies its arguments to `f` and `g` and `&&`s their outputs together. - * @see R.and + * @see R.either, R.and * @example * * const gt10 = R.gt(R.__, 10) @@ -1770,57 +1989,11 @@ * R.both(Maybe.Just(false), Maybe.Just(55)); // => Maybe.Just(false) * R.both([false, false, 'a'], [11]); //=> [false, false, 11] */ - var both = _curry2(function both(f, g) { - return _isFunction(f) ? - function _both() { - return f.apply(this, arguments) && g.apply(this, arguments); - } : - lift(and)(f, g); - }); - /** - * Returns a curried equivalent of the provided function. The curried function - * has two unusual capabilities. First, its arguments needn't be provided one - * at a time. If `f` is a ternary function and `g` is `R.curry(f)`, the - * following are equivalent: - * - * - `g(1)(2)(3)` - * - `g(1)(2, 3)` - * - `g(1, 2)(3)` - * - `g(1, 2, 3)` - * - * Secondly, the special placeholder value [`R.__`](#__) may be used to specify - * "gaps", allowing partial application of any combination of arguments, - * regardless of their positions. If `g` is as above and `_` is [`R.__`](#__), - * the following are equivalent: - * - * - `g(1, 2, 3)` - * - `g(_, 2, 3)(1)` - * - `g(_, _, 3)(1)(2)` - * - `g(_, _, 3)(1, 2)` - * - `g(_, 2)(1)(3)` - * - `g(_, 2)(1, 3)` - * - `g(_, 2)(_, 3)(1)` - * - * @func - * @memberOf R - * @since v0.1.0 - * @category Function - * @sig (* -> a) -> (* -> a) - * @param {Function} fn The function to curry. - * @return {Function} A new, curried function. - * @see R.curryN, R.partial - * @example - * - * const addFourNumbers = (a, b, c, d) => a + b + c + d; - * - * const curriedAddFourNumbers = R.curry(addFourNumbers); - * const f = curriedAddFourNumbers(1, 2); - * const g = f(3); - * g(4); //=> 10 - */ - var curry = _curry1(function curry(fn) { - return curryN(fn.length, fn); + var both = _curry2(function both(f, g) { + return _isFunction(f) ? function _both() { + return f.apply(this, arguments) && g.apply(this, arguments); + } : lift(and)(f, g); }); /** @@ -1834,7 +2007,7 @@ * @memberOf R * @since v0.9.0 * @category Function - * @sig (*... -> a),*... -> a + * @sig ((*... -> a), *...) -> a * @param {Function} fn The function to apply to the remaining arguments. * @param {...*} args Any number of positional arguments. * @return {*} @@ -1843,19 +2016,25 @@ * * R.call(R.add, 1, 2); //=> 3 * - * const indentN = R.pipe(R.repeat(' '), - * R.join(''), - * R.replace(/^(?!$)/gm)); + * const indentN = R.pipe( + * R.repeat(' '), + * R.join(''), + * R.replace(/^(?!$)/gm) + * ); * - * const format = R.converge(R.call, [ - * R.pipe(R.prop('indent'), indentN), - * R.prop('value') - * ]); + * const format = R.converge( + * R.call, + * [ + * R.pipe(R.prop('indent'), indentN), + * R.prop('value') + * ] + * ); * * format({indent: 2, value: 'foo\nbar\nbaz\n'}); //=> ' foo\n bar\n baz\n' * @symb R.call(f, a, b) = f(a, b) */ - var call = curry(function call(fn) { + + var call = _curry1(function call(fn) { return fn.apply(this, Array.prototype.slice.call(arguments, 1)); }); @@ -1865,6 +2044,7 @@ * * @private */ + function _makeFlat(recursive) { return function flatt(list) { var value, jlen, j; @@ -1877,6 +2057,7 @@ value = recursive ? flatt(list[idx]) : list[idx]; j = 0; jlen = value.length; + while (j < jlen) { result[result.length] = value[j]; j += 1; @@ -1884,8 +2065,10 @@ } else { result[result.length] = list[idx]; } + idx += 1; } + return result; }; } @@ -1897,13 +2080,13 @@ }; } - var preservingReduced = function(xf) { + var preservingReduced = function preservingReduced(xf) { return { '@@transducer/init': _xfBase.init, - '@@transducer/result': function(result) { + '@@transducer/result': function transducerResult(result) { return xf['@@transducer/result'](result); }, - '@@transducer/step': function(result, input) { + '@@transducer/step': function transducerStep(result, input) { var ret = xf['@@transducer/step'](result, input); return ret['@@transducer/reduced'] ? _forceReduced(ret) : ret; } @@ -1914,10 +2097,10 @@ var rxf = preservingReduced(xf); return { '@@transducer/init': _xfBase.init, - '@@transducer/result': function(result) { + '@@transducer/result': function transducerResult(result) { return rxf['@@transducer/result'](result); }, - '@@transducer/step': function(result, input) { + '@@transducer/step': function transducerStep(result, input) { return !_isArrayLike(input) ? _reduce(rxf, result, [input]) : _reduce(rxf, result, input); } }; @@ -1953,10 +2136,14 @@ * * R.chain(R.append, R.head)([1, 2, 3]); //=> [1, 2, 3, 1] */ + var chain = _curry2(_dispatchable(['fantasy-land/chain', 'chain'], _xchain, function chain(fn, monad) { if (typeof monad === 'function') { - return function(x) { return fn(monad(x))(x); }; + return function (x) { + return fn(monad(x))(x); + }; } + return _makeFlat(false)(map(fn, monad)); })); @@ -1980,23 +2167,17 @@ * R.clamp(1, 10, 15) // => 10 * R.clamp(1, 10, 4) // => 4 */ + var clamp = _curry3(function clamp(min, max, value) { if (min > max) { throw new Error('min must not be greater than max in clamp(min, max, value)'); } - return value < min - ? min - : value > max - ? max - : value; + + return value < min ? min : value > max ? max : value; }); function _cloneRegExp(pattern) { - return new RegExp(pattern.source, (pattern.global ? 'g' : '') + - (pattern.ignoreCase ? 'i' : '') + - (pattern.multiline ? 'm' : '') + - (pattern.sticky ? 'y' : '') + - (pattern.unicode ? 'u' : '')); + return new RegExp(pattern.source, (pattern.global ? 'g' : '') + (pattern.ignoreCase ? 'i' : '') + (pattern.multiline ? 'm' : '') + (pattern.sticky ? 'y' : '') + (pattern.unicode ? 'u' : '')); } /** @@ -2024,12 +2205,9 @@ * R.type(() => {}); //=> "Function" * R.type(undefined); //=> "Undefined" */ + var type = _curry1(function type(val) { - return val === null - ? 'Null' - : val === undefined - ? 'Undefined' - : Object.prototype.toString.call(val).slice(8, -1); + return val === null ? 'Null' : val === undefined ? 'Undefined' : Object.prototype.toString.call(val).slice(8, -1); }); /** @@ -2042,40 +2220,76 @@ * @param {Boolean} deep Whether or not to perform deep cloning. * @return {*} The copied value. */ + function _clone(value, refFrom, refTo, deep) { var copy = function copy(copiedValue) { var len = refFrom.length; var idx = 0; + while (idx < len) { if (value === refFrom[idx]) { return refTo[idx]; } + idx += 1; } - refFrom[idx + 1] = value; - refTo[idx + 1] = copiedValue; + + refFrom[idx] = value; + refTo[idx] = copiedValue; + for (var key in value) { - copiedValue[key] = deep ? - _clone(value[key], refFrom, refTo, true) : value[key]; + if (value.hasOwnProperty(key)) { + copiedValue[key] = deep ? _clone(value[key], refFrom, refTo, true) : value[key]; + } } + return copiedValue; }; + switch (type(value)) { - case 'Object': return copy({}); - case 'Array': return copy([]); - case 'Date': return new Date(value.valueOf()); - case 'RegExp': return _cloneRegExp(value); - default: return value; + case 'Object': + return copy(Object.create(Object.getPrototypeOf(value))); + + case 'Array': + return copy([]); + + case 'Date': + return new Date(value.valueOf()); + + case 'RegExp': + return _cloneRegExp(value); + + case 'Int8Array': + case 'Uint8Array': + case 'Uint8ClampedArray': + case 'Int16Array': + case 'Uint16Array': + case 'Int32Array': + case 'Uint32Array': + case 'Float32Array': + case 'Float64Array': + case 'BigInt64Array': + case 'BigUint64Array': + return value.slice(); + + default: + return value; } } /** - * Creates a deep copy of the value which may contain (nested) `Array`s and - * `Object`s, `Number`s, `String`s, `Boolean`s and `Date`s. `Function`s are - * assigned by reference rather than copied + * Creates a deep copy of the source that can be used in place of the source + * object without retaining any references to it. + * The source object may contain (nested) `Array`s and `Object`s, + * `Number`s, `String`s, `Boolean`s and `Date`s. + * `Function`s are assigned by reference rather than copied. * * Dispatches to a `clone` method if present. * + * Note that if the source object has multiple nodes that share a reference, + * the returned object will have the same structure, but the references will + * be pointed to the location within the cloned value. + * * @func * @memberOf R * @since v0.1.0 @@ -2090,10 +2304,62 @@ * objects === objectsClone; //=> false * objects[0] === objectsClone[0]; //=> false */ + var clone = _curry1(function clone(value) { - return value != null && typeof value.clone === 'function' ? - value.clone() : - _clone(value, [], [], true); + return value != null && typeof value.clone === 'function' ? value.clone() : _clone(value, [], [], true); + }); + + /** + * Splits a list into sub-lists, based on the result of calling a key-returning function on each element, + * and grouping the results according to values returned. + * + * @func + * @memberOf R + * @since v0.28.0 + * @category List + * @typedefn Idx = String | Int | Symbol + * @sig Idx a => (b -> a) -> [b] -> [[b]] + * @param {Function} fn Function :: a -> Idx + * @param {Array} list The array to group + * @return {Array} + * An array of arrays where each sub-array contains items for which + * the String-returning function has returned the same value. + * @see R.groupBy, R.partition + * @example + * R.collectBy(R.prop('type'), [ + * {type: 'breakfast', item: '☕️'}, + * {type: 'lunch', item: '🌯'}, + * {type: 'dinner', item: '🍝'}, + * {type: 'breakfast', item: '🥐'}, + * {type: 'lunch', item: '🍕'} + * ]); + * + * // [ [ {type: 'breakfast', item: '☕️'}, + * // {type: 'breakfast', item: '🥐'} ], + * // [ {type: 'lunch', item: '🌯'}, + * // {type: 'lunch', item: '🍕'} ], + * // [ {type: 'dinner', item: '🍝'} ] ] + */ + + var collectBy = _curry2(function collectBy(fn, list) { + var group = _reduce(function (o, x) { + var tag = fn(x); + + if (o[tag] === undefined) { + o[tag] = []; + } + + o[tag].push(x); + return o; + }, {}, list); + + var newList = []; + + for (var tag in group) { + newList.push(group[tag]); + } + + return newList; }); /** @@ -2119,8 +2385,9 @@ * const peopleByIncreasingAge = R.sort(byAge, people); * //=> [{ name: 'Mikhail', age: 62 },{ name: 'Emma', age: 70 }, { name: 'Peter', age: 78 }] */ + var comparator = _curry1(function comparator(pred) { - return function(a, b) { + return function (a, b) { return pred(a, b) ? -1 : pred(b, a) ? 1 : 0; }; }); @@ -2144,6 +2411,7 @@ * R.not(0); //=> true * R.not(1); //=> false */ + var not = _curry1(function not(a) { return !a; }); @@ -2165,15 +2433,16 @@ * @example * * const isNotNil = R.complement(R.isNil); - * isNil(null); //=> true + * R.isNil(null); //=> true * isNotNil(null); //=> false - * isNil(7); //=> false + * R.isNil(7); //=> false * isNotNil(7); //=> true */ + var complement = lift(not); function _pipe(f, g) { - return function() { + return function () { return g.call(this, f.apply(this, arguments)); }; } @@ -2184,20 +2453,21 @@ * implementation. * * @private - * @param {Function} fn ramda implemtation + * @param {Function} fn ramda implementation * @param {String} methodname property to check for a custom implementation * @return {Object} Whatever the return value of the method is. */ + function _checkForMethod(methodname, fn) { - return function() { + return function () { var length = arguments.length; + if (length === 0) { return fn(); } + var obj = arguments[length - 1]; - return (_isArray(obj) || typeof obj[methodname] !== 'function') ? - fn.apply(this, arguments) : - obj[methodname].apply(obj, Array.prototype.slice.call(arguments, 0, length - 1)); + return _isArray(obj) || typeof obj[methodname] !== 'function' ? fn.apply(this, arguments) : obj[methodname].apply(obj, Array.prototype.slice.call(arguments, 0, length - 1)); }; } @@ -2225,6 +2495,7 @@ * R.slice(-3, -1, ['a', 'b', 'c', 'd']); //=> ['b', 'c'] * R.slice(0, 3, 'ramda'); //=> 'ram' */ + var slice = _curry3(_checkForMethod('slice', function slice(fromIndex, toIndex, list) { return Array.prototype.slice.call(list, fromIndex, toIndex); })); @@ -2256,6 +2527,7 @@ * R.tail('a'); //=> '' * R.tail(''); //=> '' */ + var tail = _curry1(_checkForMethod('tail', slice(1, Infinity))); /** @@ -2280,15 +2552,15 @@ * * f(3, 4); // -(3^4) + 1 * @symb R.pipe(f, g, h)(a, b) = h(g(f(a, b))) + * @symb R.pipe(f, g, h)(a)(b) = h(g(f(a)))(b) */ + function pipe() { if (arguments.length === 0) { throw new Error('pipe requires at least one argument'); } - return _arity( - arguments[0].length, - reduce(_pipe, arguments[0], tail(arguments)) - ); + + return _arity(arguments[0].length, reduce(_pipe, arguments[0], tail(arguments))); } /** @@ -2315,10 +2587,9 @@ * R.reverse('a'); //=> 'a' * R.reverse(''); //=> '' */ + var reverse = _curry1(function reverse(list) { - return _isString(list) - ? list.split('').reverse().join('') - : Array.prototype.slice.call(list, 0).reverse(); + return _isString(list) ? list.split('').reverse().join('') : Array.prototype.slice.call(list, 0).reverse(); }); /** @@ -2344,132 +2615,15 @@ * R.compose(Math.abs, R.add(1), R.multiply(2))(-4) //=> 7 * * @symb R.compose(f, g, h)(a, b) = f(g(h(a, b))) + * @symb R.compose(f, g, h)(a)(b) = f(g(h(a)))(b) */ + function compose() { if (arguments.length === 0) { throw new Error('compose requires at least one argument'); } - return pipe.apply(this, reverse(arguments)); - } - - /** - * Returns the right-to-left Kleisli composition of the provided functions, - * each of which must return a value of a type supported by [`chain`](#chain). - * - * `R.composeK(h, g, f)` is equivalent to `R.compose(R.chain(h), R.chain(g), f)`. - * - * @func - * @memberOf R - * @since v0.16.0 - * @category Function - * @sig Chain m => ((y -> m z), (x -> m y), ..., (a -> m b)) -> (a -> m z) - * @param {...Function} ...functions The functions to compose - * @return {Function} - * @see R.pipeK - * @deprecated since v0.26.0 - * @example - * - * // get :: String -> Object -> Maybe * - * const get = R.curry((propName, obj) => Maybe(obj[propName])) - * - * // getStateCode :: Maybe String -> Maybe String - * const getStateCode = R.composeK( - * R.compose(Maybe.of, R.toUpper), - * get('state'), - * get('address'), - * get('user'), - * ); - * getStateCode({"user":{"address":{"state":"ny"}}}); //=> Maybe.Just("NY") - * getStateCode({}); //=> Maybe.Nothing() - * @symb R.composeK(f, g, h)(a) = R.chain(f, R.chain(g, h(a))) - */ - function composeK() { - if (arguments.length === 0) { - throw new Error('composeK requires at least one argument'); - } - var init = Array.prototype.slice.call(arguments); - var last = init.pop(); - return compose(compose.apply(this, map(chain, init)), last); - } - - function _pipeP(f, g) { - return function() { - var ctx = this; - return f.apply(ctx, arguments).then(function(x) { - return g.call(ctx, x); - }); - }; - } - /** - * Performs left-to-right composition of one or more Promise-returning - * functions. The first argument may have any arity; the remaining arguments - * must be unary. - * - * @func - * @memberOf R - * @since v0.10.0 - * @category Function - * @sig ((a -> Promise b), (b -> Promise c), ..., (y -> Promise z)) -> (a -> Promise z) - * @param {...Function} functions - * @return {Function} - * @see R.composeP - * @deprecated since v0.26.0 - * @example - * - * // followersForUser :: String -> Promise [User] - * const followersForUser = R.pipeP(db.getUserById, db.getFollowers); - */ - function pipeP() { - if (arguments.length === 0) { - throw new Error('pipeP requires at least one argument'); - } - return _arity( - arguments[0].length, - reduce(_pipeP, arguments[0], tail(arguments)) - ); - } - - /** - * Performs right-to-left composition of one or more Promise-returning - * functions. The last arguments may have any arity; the remaining - * arguments must be unary. - * - * @func - * @memberOf R - * @since v0.10.0 - * @category Function - * @sig ((y -> Promise z), (x -> Promise y), ..., (a -> Promise b)) -> (a -> Promise z) - * @param {...Function} functions The functions to compose - * @return {Function} - * @see R.pipeP - * @deprecated since v0.26.0 - * @example - * - * const db = { - * users: { - * JOE: { - * name: 'Joe', - * followers: ['STEVE', 'SUZY'] - * } - * } - * } - * - * // We'll pretend to do a db lookup which returns a promise - * const lookupUser = (userId) => Promise.resolve(db.users[userId]) - * const lookupFollowers = (user) => Promise.resolve(user.followers) - * lookupUser('JOE').then(lookupFollowers) - * - * // followersForUser :: String -> Promise [UserId] - * const followersForUser = R.composeP(lookupFollowers, lookupUser); - * followersForUser('JOE').then(followers => console.log('Followers:', followers)) - * // Followers: ["STEVE","SUZY"] - */ - function composeP() { - if (arguments.length === 0) { - throw new Error('composeP requires at least one argument'); - } - return pipeP.apply(this, reverse(arguments)); + return pipe.apply(this, reverse(arguments)); } /** @@ -2493,9 +2647,12 @@ * R.head('abc'); //=> 'a' * R.head(''); //=> '' */ + var head = nth(0); - function _identity(x) { return x; } + function _identity(x) { + return x; + } /** * A function that does nothing but return the parameter supplied to it. Good @@ -2516,11 +2673,12 @@ * R.identity(obj) === obj; //=> true * @symb R.identity(a) = a */ + var identity = _curry1(_identity); /** - * Performs left-to-right function composition using transforming function. The first argument may have - * any arity; the remaining arguments must be unary. + * Performs left-to-right function composition using transforming function. The first function may have + * any arity; the remaining functions must be unary. * * **Note:** The result of pipeWith is not automatically curried. Transforming function is not used on the * first argument. @@ -2530,7 +2688,8 @@ * @since v0.26.0 * @category Function * @sig ((* -> *), [((a, b, ..., n) -> o), (o -> p), ..., (x -> y), (y -> z)]) -> ((a, b, ..., n) -> z) - * @param {...Function} functions + * @param {Function} transformer The transforming function + * @param {Array} functions The functions to pipe * @return {Function} * @see R.composeWith, R.pipe * @example @@ -2541,6 +2700,7 @@ * f(3, 4); // -(3^4) + 1 * @symb R.pipeWith(f)([g, h, i])(...args) = f(i, f(h, g(...args))) */ + var pipeWith = _curry2(function pipeWith(xf, list) { if (list.length <= 0) { return identity; @@ -2548,31 +2708,27 @@ var headList = head(list); var tailList = tail(list); - - return _arity(headList.length, function() { - return _reduce( - function(result, f) { - return xf.call(this, f, result); - }, - headList.apply(this, arguments), - tailList - ); + return _arity(headList.length, function () { + return _reduce(function (result, f) { + return xf.call(this, f, result); + }, headList.apply(this, arguments), tailList); }); }); /** - * Performs right-to-left function composition using transforming function. The last argument may have - * any arity; the remaining arguments must be unary. + * Performs right-to-left function composition using transforming function. The last function may have + * any arity; the remaining functions must be unary. * - * **Note:** The result of compose is not automatically curried. Transforming function is not used on the - * last argument. + * **Note:** The result of composeWith is not automatically curried. Transforming function is not used + * on the last argument. * * @func * @memberOf R * @since v0.26.0 * @category Function * @sig ((* -> *), [(y -> z), (x -> y), ..., (o -> p), ((a, b, ..., n) -> o)]) -> ((a, b, ..., n) -> z) - * @param {...Function} ...functions The functions to compose + * @param {Function} transformer The transforming function + * @param {Array} functions The functions to compose * @return {Function} * @see R.compose, R.pipeWith * @example @@ -2584,6 +2740,7 @@ * * @symb R.composeWith(f)([g, h, i])(...args) = f(g, f(h, i(...args))) */ + var composeWith = _curry2(function composeWith(xf, list) { return pipeWith.apply(this, [xf, reverse(list)]); }); @@ -2591,9 +2748,11 @@ function _arrayFromIterator(iter) { var list = []; var next; + while (!(next = iter.next()).done) { list.push(next.value); } + return list; } @@ -2605,8 +2764,10 @@ if (pred(x, list[idx])) { return true; } + idx += 1; } + return false; } @@ -2619,7 +2780,8 @@ // Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is function _objectIs(a, b) { // SameValue algorithm - if (a === b) { // Steps 1-5, 7-10 + if (a === b) { + // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return a !== 0 || 1 / a === 1 / b; } else { @@ -2636,21 +2798,22 @@ * - iterators lengths are the same * - iterators values are unique * - * false-positive result will be returned for comparision of, e.g. + * false-positive result will be returned for comparison of, e.g. * - [1,2,3] and [1,2,3,4] * - [1,1,1] and [1,2,3] * */ function _uniqContentEquals(aIterator, bIterator, stackA, stackB) { var a = _arrayFromIterator(aIterator); + var b = _arrayFromIterator(bIterator); function eq(_a, _b) { return _equals(_a, _b, stackA.slice(), stackB.slice()); - } + } // if *a* array contains any element that is not included in *b* + - // if *a* array contains any element that is not included in *b* - return !_includesWith(function(b, aItem) { + return !_includesWith(function (b, aItem) { return !_includesWith(eq, aItem, b); }, b, a); } @@ -2666,60 +2829,58 @@ return false; } - if (a == null || b == null) { - return false; - } - if (typeof a['fantasy-land/equals'] === 'function' || typeof b['fantasy-land/equals'] === 'function') { - return typeof a['fantasy-land/equals'] === 'function' && a['fantasy-land/equals'](b) && - typeof b['fantasy-land/equals'] === 'function' && b['fantasy-land/equals'](a); + return typeof a['fantasy-land/equals'] === 'function' && a['fantasy-land/equals'](b) && typeof b['fantasy-land/equals'] === 'function' && b['fantasy-land/equals'](a); } if (typeof a.equals === 'function' || typeof b.equals === 'function') { - return typeof a.equals === 'function' && a.equals(b) && - typeof b.equals === 'function' && b.equals(a); + return typeof a.equals === 'function' && a.equals(b) && typeof b.equals === 'function' && b.equals(a); } switch (typeA) { case 'Arguments': case 'Array': case 'Object': - if (typeof a.constructor === 'function' && - _functionName(a.constructor) === 'Promise') { + if (typeof a.constructor === 'function' && _functionName(a.constructor) === 'Promise') { return a === b; } + break; + case 'Boolean': case 'Number': case 'String': - if (!(typeof a === typeof b && _objectIs$1(a.valueOf(), b.valueOf()))) { + if (!(_typeof(a) === _typeof(b) && _objectIs$1(a.valueOf(), b.valueOf()))) { return false; } + break; + case 'Date': if (!_objectIs$1(a.valueOf(), b.valueOf())) { return false; } + break; + case 'Error': return a.name === b.name && a.message === b.message; + case 'RegExp': - if (!(a.source === b.source && - a.global === b.global && - a.ignoreCase === b.ignoreCase && - a.multiline === b.multiline && - a.sticky === b.sticky && - a.unicode === b.unicode)) { + if (!(a.source === b.source && a.global === b.global && a.ignoreCase === b.ignoreCase && a.multiline === b.multiline && a.sticky === b.sticky && a.unicode === b.unicode)) { return false; } + break; } var idx = stackA.length - 1; + while (idx >= 0) { if (stackA[idx] === a) { return stackB[idx] === b; } + idx -= 1; } @@ -2730,12 +2891,14 @@ } return _uniqContentEquals(a.entries(), b.entries(), stackA.concat([a]), stackB.concat([b])); + case 'Set': if (a.size !== b.size) { return false; } return _uniqContentEquals(a.values(), b.values(), stackA.concat([a]), stackB.concat([b])); + case 'Arguments': case 'Array': case 'Object': @@ -2756,27 +2919,32 @@ case 'Float64Array': case 'ArrayBuffer': break; + default: // Values of other types are only equal if identical. return false; } var keysA = keys(a); + if (keysA.length !== keys(b).length) { return false; } var extendedStackA = stackA.concat([a]); var extendedStackB = stackB.concat([b]); - idx = keysA.length - 1; + while (idx >= 0) { var key = keysA[idx]; + if (!(_has(key, b) && _equals(b[key], a[key], extendedStackA, extendedStackB))) { return false; } + idx -= 1; } + return true; } @@ -2805,42 +2973,51 @@ * const b = {}; b.v = b; * R.equals(a, b); //=> true */ + var equals = _curry2(function equals(a, b) { return _equals(a, b, [], []); }); function _indexOf(list, a, idx) { - var inf, item; - // Array.prototype.indexOf doesn't exist below IE9 + var inf, item; // Array.prototype.indexOf doesn't exist below IE9 + if (typeof list.indexOf === 'function') { - switch (typeof a) { + switch (_typeof(a)) { case 'number': if (a === 0) { // manually crawl the list to distinguish between +0 and -0 inf = 1 / a; + while (idx < list.length) { item = list[idx]; + if (item === 0 && 1 / item === inf) { return idx; } + idx += 1; } + return -1; } else if (a !== a) { // NaN while (idx < list.length) { item = list[idx]; + if (typeof item === 'number' && item !== item) { return idx; } + idx += 1; } + return -1; - } - // non-zero numbers can utilise Set - return list.indexOf(a, idx); + } // non-zero numbers can utilise Set + + return list.indexOf(a, idx); // all these types can utilise Set + case 'string': case 'boolean': case 'function': @@ -2852,15 +3029,19 @@ // null can utilise Set return list.indexOf(a, idx); } + } - } - // anything else not covered above, defer to R.equals + } // anything else not covered above, defer to R.equals + + while (idx < list.length) { if (equals(list[idx], a)) { return idx; } + idx += 1; } + return -1; } @@ -2869,42 +3050,26 @@ } function _quote(s) { - var escaped = s - .replace(/\\/g, '\\\\') - .replace(/[\b]/g, '\\b') // \b matches word boundary; [\b] matches backspace - .replace(/\f/g, '\\f') - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r') - .replace(/\t/g, '\\t') - .replace(/\v/g, '\\v') - .replace(/\0/g, '\\0'); - + var escaped = s.replace(/\\/g, '\\\\').replace(/[\b]/g, '\\b') // \b matches word boundary; [\b] matches backspace + .replace(/\f/g, '\\f').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t').replace(/\v/g, '\\v').replace(/\0/g, '\\0'); return '"' + escaped.replace(/"/g, '\\"') + '"'; } /** * Polyfill from . */ - var pad = function pad(n) { return (n < 10 ? '0' : '') + n; }; - - var _toISOString = typeof Date.prototype.toISOString === 'function' ? - function _toISOString(d) { - return d.toISOString(); - } : - function _toISOString(d) { - return ( - d.getUTCFullYear() + '-' + - pad(d.getUTCMonth() + 1) + '-' + - pad(d.getUTCDate()) + 'T' + - pad(d.getUTCHours()) + ':' + - pad(d.getUTCMinutes()) + ':' + - pad(d.getUTCSeconds()) + '.' + - (d.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z' - ); - }; + var pad = function pad(n) { + return (n < 10 ? '0' : '') + n; + }; + + var _toISOString = typeof Date.prototype.toISOString === 'function' ? function _toISOString(d) { + return d.toISOString(); + } : function _toISOString(d) { + return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) + 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()) + '.' + (d.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z'; + }; function _complement(f) { - return function() { + return function () { return !f.apply(this, arguments); }; } @@ -2918,8 +3083,10 @@ if (fn(list[idx])) { result[result.length] = list[idx]; } + idx += 1; } + return result; } @@ -2931,13 +3098,17 @@ this.xf = xf; this.f = f; } + XFilter.prototype['@@transducer/init'] = _xfBase.init; XFilter.prototype['@@transducer/result'] = _xfBase.result; - XFilter.prototype['@@transducer/step'] = function(result, input) { + + XFilter.prototype['@@transducer/step'] = function (result, input) { return this.f(input) ? this.xf['@@transducer/step'](result, input) : result; }; - var _xfilter = _curry2(function _xfilter(f, xf) { return new XFilter(f, xf); }); + var _xfilter = _curry2(function _xfilter(f, xf) { + return new XFilter(f, xf); + }); /** * Takes a predicate and a `Filterable`, and returns a new filterable of the @@ -2966,18 +3137,16 @@ * * R.filter(isEven, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4} */ - var filter = _curry2(_dispatchable(['filter'], _xfilter, function(pred, filterable) { - return ( - _isObject(filterable) ? - _reduce(function(acc, key) { - if (pred(filterable[key])) { - acc[key] = filterable[key]; - } - return acc; - }, {}, keys(filterable)) : - // else - _filter(pred, filterable) - ); + + var filter = _curry2(_dispatchable(['fantasy-land/filter', 'filter'], _xfilter, function (pred, filterable) { + return _isObject(filterable) ? _reduce(function (acc, key) { + if (pred(filterable[key])) { + acc[key] = filterable[key]; + } + + return acc; + }, {}, keys(filterable)) : // else + _filter(pred, filterable); })); /** @@ -3004,6 +3173,7 @@ * * R.reject(isOdd, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4} */ + var reject = _curry2(function reject(pred, filterable) { return filter(_complement(pred), filterable); }); @@ -3012,37 +3182,51 @@ var recur = function recur(y) { var xs = seen.concat([x]); return _includes(y, xs) ? '' : _toString(y, xs); - }; + }; // mapPairs :: (Object, [String]) -> [String] + - // mapPairs :: (Object, [String]) -> [String] - var mapPairs = function(obj, keys$$1) { - return _map(function(k) { return _quote(k) + ': ' + recur(obj[k]); }, keys$$1.slice().sort()); + var mapPairs = function mapPairs(obj, keys) { + return _map(function (k) { + return _quote(k) + ': ' + recur(obj[k]); + }, keys.slice().sort()); }; switch (Object.prototype.toString.call(x)) { case '[object Arguments]': return '(function() { return arguments; }(' + _map(recur, x).join(', ') + '))'; + case '[object Array]': - return '[' + _map(recur, x).concat(mapPairs(x, reject(function(k) { return /^\d+$/.test(k); }, keys(x)))).join(', ') + ']'; + return '[' + _map(recur, x).concat(mapPairs(x, reject(function (k) { + return /^\d+$/.test(k); + }, keys(x)))).join(', ') + ']'; + case '[object Boolean]': - return typeof x === 'object' ? 'new Boolean(' + recur(x.valueOf()) + ')' : x.toString(); + return _typeof(x) === 'object' ? 'new Boolean(' + recur(x.valueOf()) + ')' : x.toString(); + case '[object Date]': return 'new Date(' + (isNaN(x.valueOf()) ? recur(NaN) : _quote(_toISOString(x))) + ')'; + case '[object Null]': return 'null'; + case '[object Number]': - return typeof x === 'object' ? 'new Number(' + recur(x.valueOf()) + ')' : 1 / x === -Infinity ? '-0' : x.toString(10); + return _typeof(x) === 'object' ? 'new Number(' + recur(x.valueOf()) + ')' : 1 / x === -Infinity ? '-0' : x.toString(10); + case '[object String]': - return typeof x === 'object' ? 'new String(' + recur(x.valueOf()) + ')' : _quote(x); + return _typeof(x) === 'object' ? 'new String(' + recur(x.valueOf()) + ')' : _quote(x); + case '[object Undefined]': return 'undefined'; + default: if (typeof x.toString === 'function') { var repr = x.toString(); + if (repr !== '[object Object]') { return repr; } } + return '{' + mapPairs(x, keys(x)).join(', ') + '}'; } } @@ -3083,7 +3267,10 @@ * R.toString({foo: 1, bar: 2, baz: 3}); //=> '{"bar": 2, "baz": 3, "foo": 1}' * R.toString(new Date('2001-02-03T04:05:06Z')); //=> 'new Date("2001-02-03T04:05:06.000Z")' */ - var toString$1 = _curry1(function toString(val) { return _toString(val, []); }); + + var toString$1 = _curry1(function toString(val) { + return _toString(val, []); + }); /** * Returns the result of concatenating the given lists or strings. @@ -3113,25 +3300,32 @@ * R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] * R.concat([], []); //=> [] */ + var concat = _curry2(function concat(a, b) { if (_isArray(a)) { if (_isArray(b)) { return a.concat(b); } + throw new TypeError(toString$1(b) + ' is not an array'); } + if (_isString(a)) { if (_isString(b)) { return a + b; } + throw new TypeError(toString$1(b) + ' is not a string'); } + if (a != null && _isFunction(a['fantasy-land/concat'])) { return a['fantasy-land/concat'](b); } + if (a != null && _isFunction(a.concat)) { return a.concat(b); } + throw new TypeError(toString$1(a) + ' does not have a method named "concat" or "fantasy-land/concat"'); }); @@ -3143,6 +3337,10 @@ * arguments to the corresponding transformer. If none of the predicates * matches, `fn` returns undefined. * + * **Please note**: This is not a direct substitute for a `switch` statement. + * Remember that both elements of every pair passed to `cond` are *functions*, + * and `cond` returns a function. + * * @func * @memberOf R * @since v0.6.0 @@ -3162,23 +3360,70 @@ * fn(50); //=> 'nothing special happens at 50°C' * fn(100); //=> 'water boils at 100°C' */ + var cond = _curry1(function cond(pairs) { - var arity = reduce( - max, - 0, - map(function(pair) { return pair[0].length; }, pairs) - ); - return _arity(arity, function() { + var arity = reduce(max, 0, map(function (pair) { + return pair[0].length; + }, pairs)); + return _arity(arity, function () { var idx = 0; + while (idx < pairs.length) { if (pairs[idx][0].apply(this, arguments)) { return pairs[idx][1].apply(this, arguments); } + idx += 1; } }); }); + /** + * Returns a curried equivalent of the provided function. The curried function + * has two unusual capabilities. First, its arguments needn't be provided one + * at a time. If `f` is a ternary function and `g` is `R.curry(f)`, the + * following are equivalent: + * + * - `g(1)(2)(3)` + * - `g(1)(2, 3)` + * - `g(1, 2)(3)` + * - `g(1, 2, 3)` + * + * Secondly, the special placeholder value [`R.__`](#__) may be used to specify + * "gaps", allowing partial application of any combination of arguments, + * regardless of their positions. If `g` is as above and `_` is [`R.__`](#__), + * the following are equivalent: + * + * - `g(1, 2, 3)` + * - `g(_, 2, 3)(1)` + * - `g(_, _, 3)(1)(2)` + * - `g(_, _, 3)(1, 2)` + * - `g(_, 2)(1)(3)` + * - `g(_, 2)(1, 3)` + * - `g(_, 2)(_, 3)(1)` + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (* -> a) -> (* -> a) + * @param {Function} fn The function to curry. + * @return {Function} A new, curried function. + * @see R.curryN, R.partial + * @example + * + * const addFourNumbers = (a, b, c, d) => a + b + c + d; + * + * const curriedAddFourNumbers = R.curry(addFourNumbers); + * const f = curriedAddFourNumbers(1, 2); + * const g = f(3); + * g(4); //=> 10 + */ + + var curry = _curry1(function curry(fn) { + return curryN(fn.length, fn); + }); + /** * Wraps a constructor function inside a curried function that can be called * with the same arguments and returns the same type. The arity of the function @@ -3214,25 +3459,49 @@ * // Add a dollop of Potato Chips * // Add a dollop of Ketchup */ + var constructN = _curry2(function constructN(n, Fn) { if (n > 10) { throw new Error('Constructor with greater than ten arguments'); } + if (n === 0) { - return function() { return new Fn(); }; + return function () { + return new Fn(); + }; } - return curry(nAry(n, function($0, $1, $2, $3, $4, $5, $6, $7, $8, $9) { + + return curry(nAry(n, function ($0, $1, $2, $3, $4, $5, $6, $7, $8, $9) { switch (arguments.length) { - case 1: return new Fn($0); - case 2: return new Fn($0, $1); - case 3: return new Fn($0, $1, $2); - case 4: return new Fn($0, $1, $2, $3); - case 5: return new Fn($0, $1, $2, $3, $4); - case 6: return new Fn($0, $1, $2, $3, $4, $5); - case 7: return new Fn($0, $1, $2, $3, $4, $5, $6); - case 8: return new Fn($0, $1, $2, $3, $4, $5, $6, $7); - case 9: return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8); - case 10: return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8, $9); + case 1: + return new Fn($0); + + case 2: + return new Fn($0, $1); + + case 3: + return new Fn($0, $1, $2); + + case 4: + return new Fn($0, $1, $2, $3); + + case 5: + return new Fn($0, $1, $2, $3, $4); + + case 6: + return new Fn($0, $1, $2, $3, $4, $5); + + case 7: + return new Fn($0, $1, $2, $3, $4, $5, $6); + + case 8: + return new Fn($0, $1, $2, $3, $4, $5, $6, $7); + + case 9: + return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8); + + case 10: + return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8, $9); } })); }); @@ -3269,35 +3538,11 @@ * const sightNewAnimal = R.compose(animalSighting, AnimalConstructor); * R.map(sightNewAnimal, animalTypes); //=> ["It's a Lion!", "It's a Tiger!", "It's a Bear!"] */ + var construct = _curry1(function construct(Fn) { return constructN(Fn.length, Fn); }); - /** - * Returns `true` if the specified value is equal, in [`R.equals`](#equals) - * terms, to at least one element of the given list; `false` otherwise. - * Works also with strings. - * - * @func - * @memberOf R - * @since v0.1.0 - * @category List - * @sig a -> [a] -> Boolean - * @param {Object} a The item to compare against. - * @param {Array} list The array to consider. - * @return {Boolean} `true` if an equivalent item is in the list, `false` otherwise. - * @see R.includes - * @deprecated since v0.26.0 - * @example - * - * R.contains(3, [1, 2, 3]); //=> true - * R.contains(4, [1, 2, 3]); //=> false - * R.contains({ name: 'Fred' }, [{ name: 'Fred' }]); //=> true - * R.contains([42], [[42]]); //=> true - * R.contains('ba', 'banana'); //=>true - */ - var contains$1 = _curry2(_includes); - /** * Accepts a converging function and a list of branching functions and returns * a new function. The arity of the new function is the same as the arity of @@ -3326,16 +3571,41 @@ * * @symb R.converge(f, [g, h])(a, b) = f(g(a, b), h(a, b)) */ + var converge = _curry2(function converge(after, fns) { - return curryN(reduce(max, 0, pluck('length', fns)), function() { + return curryN(reduce(max, 0, pluck('length', fns)), function () { var args = arguments; var context = this; - return after.apply(context, _map(function(fn) { + return after.apply(context, _map(function (fn) { return fn.apply(context, args); }, fns)); }); }); + /** + * Returns the number of items in a given `list` matching the predicate `f` + * + * @func + * @memberOf R + * @since v0.28.0 + * @category List + * @sig (a -> Boolean) -> [a] -> Number + * @param {Function} predicate to match items against + * @return {Array} list of items to count in + * @example + * + * const even = x => x % 2 == 0; + * + * R.count(even, [1, 2, 3, 4, 5]); // => 2 + * R.map(R.count(even), [[1, 1, 1], [2, 3, 4, 5], [6]]); // => [0, 2, 1] + */ + + var count = curry(function (pred, list) { + return _reduce(function (a, e) { + return pred(e) ? a + 1 : a; + }, 0, list); + }); + function XReduceBy(valueFn, valueAcc, keyFn, xf) { this.valueFn = valueFn; this.valueAcc = valueAcc; @@ -3343,39 +3613,46 @@ this.xf = xf; this.inputs = {}; } + XReduceBy.prototype['@@transducer/init'] = _xfBase.init; - XReduceBy.prototype['@@transducer/result'] = function(result) { + + XReduceBy.prototype['@@transducer/result'] = function (result) { var key; + for (key in this.inputs) { if (_has(key, this.inputs)) { result = this.xf['@@transducer/step'](result, this.inputs[key]); + if (result['@@transducer/reduced']) { result = result['@@transducer/value']; break; } } } + this.inputs = null; return this.xf['@@transducer/result'](result); }; - XReduceBy.prototype['@@transducer/step'] = function(result, input) { + + XReduceBy.prototype['@@transducer/step'] = function (result, input) { var key = this.keyFn(input); this.inputs[key] = this.inputs[key] || [key, this.valueAcc]; this.inputs[key][1] = this.valueFn(this.inputs[key][1], input); return result; }; - var _xreduceBy = _curryN(4, [], - function _xreduceBy(valueFn, valueAcc, keyFn, xf) { - return new XReduceBy(valueFn, valueAcc, keyFn, xf); - } - ); + var _xreduceBy = _curryN(4, [], function _xreduceBy(valueFn, valueAcc, keyFn, xf) { + return new XReduceBy(valueFn, valueAcc, keyFn, xf); + }); /** * Groups the elements of the list according to the result of calling * the String-returning function `keyFn` on each element and reduces the elements * of each group to a single value via the reducer function `valueFn`. * + * The value function receives two values: *(acc, value)*. It may use + * [`R.reduced`](#reduced) to short circuit the iteration. + * * This function is basically a more general [`groupBy`](#groupBy) function. * * Acts as a transducer if a transformer is given in list position. @@ -3392,7 +3669,7 @@ * @param {Array} list The array to group. * @return {Object} An object with the output of `keyFn` for keys, mapped to the output of * `valueFn` for elements which produced that key when passed to `keyFn`. - * @see R.groupBy, R.reduce + * @see R.groupBy, R.reduce, R.reduced * @example * * const groupNames = (acc, {name}) => acc.concat(name) @@ -3412,14 +3689,20 @@ * reduceBy(groupNames, [], toGrade, students) * //=> {"A": ["Dora"], "B": ["Abby", "Curt"], "F": ["Bart"]} */ - var reduceBy = _curryN(4, [], _dispatchable([], _xreduceBy, - function reduceBy(valueFn, valueAcc, keyFn, list) { - return _reduce(function(acc, elt) { - var key = keyFn(elt); - acc[key] = valueFn(_has(key, acc) ? acc[key] : _clone(valueAcc, [], [], false), elt); - return acc; - }, {}, list); - })); + + var reduceBy = _curryN(4, [], _dispatchable([], _xreduceBy, function reduceBy(valueFn, valueAcc, keyFn, list) { + return _reduce(function (acc, elt) { + var key = keyFn(elt); + var value = valueFn(_has(key, acc) ? acc[key] : _clone(valueAcc, [], [], false), elt); + + if (value && value['@@transducer/reduced']) { + return _reduced(acc); + } + + acc[key] = value; + return acc; + }, {}, list); + })); /** * Counts the elements of a list according to how many match each value of a @@ -3445,7 +3728,10 @@ * const letters = ['a', 'b', 'A', 'a', 'B', 'c']; * R.countBy(R.toLower)(letters); //=> {'a': 3, 'b': 2, 'c': 1} */ - var countBy = reduceBy(function(acc, elem) { return acc + 1; }, 0); + + var countBy = reduceBy(function (acc, elem) { + return acc + 1; + }, 0); /** * Decrements its argument. @@ -3462,6 +3748,7 @@ * * R.dec(42); //=> 41 */ + var dec = add(-1); /** @@ -3487,6 +3774,7 @@ * // parseInt('string') results in NaN * defaultTo42(parseInt('string')); //=> 42 */ + var defaultTo = _curry2(function defaultTo(d, v) { return v == null || v !== v ? d : v; }); @@ -3516,6 +3804,7 @@ * const peopleByOldestFirst = R.sort(byAge, people); * //=> [{ name: 'Peter', age: 78 }, { name: 'Emma', age: 70 }, { name: 'Mikhail', age: 62 }] */ + var descend = _curry3(function descend(fn, a, b) { var aa = fn(a); var bb = fn(b); @@ -3526,25 +3815,23 @@ /* globals Set */ this._nativeSet = typeof Set === 'function' ? new Set() : null; this._items = {}; - } - - // until we figure out why jsdoc chokes on this + } // until we figure out why jsdoc chokes on this // @param item The item to add to the Set // @returns {boolean} true if the item did not exist prior, otherwise false // - _Set.prototype.add = function(item) { - return !hasOrAdd(item, true, this); - }; - // + + _Set.prototype.add = function (item) { + return !hasOrAdd(item, true, this); + }; // // @param item The item to check for existence in the Set // @returns {boolean} true if the item exists in the Set, otherwise false // - _Set.prototype.has = function(item) { - return hasOrAdd(item, false, this); - }; - // + + _Set.prototype.has = function (item) { + return hasOrAdd(item, false, this); + }; // // Combines the logic for checking whether an item is a member of the set and // for adding a new item to the set. // @@ -3554,9 +3841,13 @@ // @param set The set instance to check or add to. // @return {boolean} true if the item already existed, otherwise false. // + + function hasOrAdd(item, shouldAdd, set) { - var type = typeof item; + var type = _typeof(item); + var prevSize, newSize; + switch (type) { case 'string': case 'number': @@ -3568,14 +3859,18 @@ if (shouldAdd) { set._items['-0'] = true; } + return false; } - } - // these types can all utilise the native Set + } // these types can all utilise the native Set + + if (set._nativeSet !== null) { if (shouldAdd) { prevSize = set._nativeSet.size; + set._nativeSet.add(item); + newSize = set._nativeSet.size; return newSize === prevSize; } else { @@ -3587,6 +3882,7 @@ set._items[type] = {}; set._items[type][item] = true; } + return false; } else if (item in set._items[type]) { return true; @@ -3594,6 +3890,7 @@ if (shouldAdd) { set._items[type][item] = true; } + return false; } } @@ -3603,18 +3900,21 @@ // representing [ falseExists, trueExists ] if (type in set._items) { var bIdx = item ? 1 : 0; + if (set._items[type][bIdx]) { return true; } else { if (shouldAdd) { set._items[type][bIdx] = true; } + return false; } } else { if (shouldAdd) { set._items[type] = item ? [false, true] : [true, false]; } + return false; } @@ -3623,7 +3923,9 @@ if (set._nativeSet !== null) { if (shouldAdd) { prevSize = set._nativeSet.size; + set._nativeSet.add(item); + newSize = set._nativeSet.size; return newSize === prevSize; } else { @@ -3634,14 +3936,18 @@ if (shouldAdd) { set._items[type] = [item]; } + return false; } + if (!_includes(item, set._items[type])) { if (shouldAdd) { set._items[type].push(item); } + return false; } + return true; } @@ -3652,6 +3958,7 @@ if (shouldAdd) { set._items[type] = true; } + return false; } @@ -3661,31 +3968,40 @@ if (shouldAdd) { set._items['null'] = true; } + return false; } + return true; } + /* falls through */ + default: // reduce the search size of heterogeneous sets by creating buckets // for each type. type = Object.prototype.toString.call(item); + if (!(type in set._items)) { if (shouldAdd) { set._items[type] = [item]; } + return false; - } - // scan through all previously applied items + } // scan through all previously applied items + + if (!_includes(item, set._items[type])) { if (shouldAdd) { set._items[type].push(item); } + return false; } + return true; } - } + } // A simple Set type that honours R.equals semantics /** * Finds the set (i.e. no duplicates) of all elements in the first list not @@ -3707,6 +4023,7 @@ * R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5] * R.difference([{a: 1}, {b: 2}], [{a: 1}, {c: 3}]) //=> [{b: 2}] */ + var difference = _curry2(function difference(first, second) { var out = []; var idx = 0; @@ -3722,8 +4039,10 @@ if (toFilterOut.add(first[idx])) { out[out.length] = first[idx]; } + idx += 1; } + return out; }); @@ -3749,43 +4068,21 @@ * const l2 = [{a: 3}, {a: 4}]; * R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}] */ + var differenceWith = _curry3(function differenceWith(pred, first, second) { var out = []; var idx = 0; var firstLen = first.length; + while (idx < firstLen) { - if (!_includesWith(pred, first[idx], second) && - !_includesWith(pred, first[idx], out)) { + if (!_includesWith(pred, first[idx], second) && !_includesWith(pred, first[idx], out)) { out.push(first[idx]); } + idx += 1; } - return out; - }); - /** - * Returns a new object that does not contain a `prop` property. - * - * @func - * @memberOf R - * @since v0.10.0 - * @category Object - * @sig String -> {k: v} -> {k: v} - * @param {String} prop The name of the property to dissociate - * @param {Object} obj The object to clone - * @return {Object} A new object equivalent to the original but without the specified property - * @see R.assoc, R.omit - * @example - * - * R.dissoc('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} - */ - var dissoc = _curry2(function dissoc(prop, obj) { - var result = {}; - for (var p in obj) { - result[p] = obj[p]; - } - delete result[prop]; - return result; + return out; }); /** @@ -3808,6 +4105,7 @@ * * R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] */ + var remove = _curry3(function remove(start, count, list) { var result = Array.prototype.slice.call(list, 0); result.splice(start, count); @@ -3815,31 +4113,57 @@ }); /** - * Returns a new copy of the array with the element at the provided index - * replaced with the given value. + * Returns a new object that does not contain a `prop` property. * - * @func - * @memberOf R - * @since v0.14.0 - * @category List - * @sig Number -> a -> [a] -> [a] - * @param {Number} idx The index to update. - * @param {*} x The value to exist at the given index of the returned array. - * @param {Array|Arguments} list The source array-like object to be updated. - * @return {Array} A copy of `list` with the value at index `idx` replaced with `x`. - * @see R.adjust - * @example + * @private + * @param {String|Number} prop The name of the property to dissociate + * @param {Object|Array} obj The object to clone + * @return {Object} A new object equivalent to the original but without the specified property + */ + + function _dissoc(prop, obj) { + if (obj == null) { + return obj; + } + + if (_isInteger(prop) && _isArray(obj)) { + return remove(prop, 1, obj); + } + + var result = {}; + + for (var p in obj) { + result[p] = obj[p]; + } + + delete result[prop]; + return result; + } + + /** + * Makes a shallow clone of an object. Note that this copies and flattens + * prototype properties onto the new object as well. All non-primitive + * properties are copied by reference. * - * R.update(1, '_', ['a', 'b', 'c']); //=> ['a', '_', 'c'] - * R.update(-1, '_', ['a', 'b', 'c']); //=> ['a', 'b', '_'] - * @symb R.update(-1, a, [b, c]) = [b, a] - * @symb R.update(0, a, [b, c]) = [a, c] - * @symb R.update(1, a, [b, c]) = [b, a] + * @private + * @param {String|Integer} prop The prop operating + * @param {Object|Array} obj The object to clone + * @return {Object|Array} A new object equivalent to the original. */ - var update = _curry3(function update(idx, x, list) { - return adjust(idx, always(x), list); - }); + function _shallowCloneObject(prop, obj) { + if (_isInteger(prop) && _isArray(obj)) { + return [].concat(obj); + } + + var result = {}; + + for (var p in obj) { + result[p] = obj[p]; + } + + return result; + } /** * Makes a shallow clone of an object, omitting the property at the given path. * Note that this copies and flattens prototype properties onto the new object @@ -3849,7 +4173,7 @@ * @memberOf R * @since v0.11.0 * @category Object - * @typedefn Idx = String | Int + * @typedefn Idx = String | Int | Symbol * @sig [Idx] -> {k: v} -> {k: v} * @param {Array} path The path to the value to omit * @param {Object} obj The object to clone @@ -3859,25 +4183,54 @@ * * R.dissocPath(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}} */ + + var dissocPath = _curry2(function dissocPath(path, obj) { + if (obj == null) { + return obj; + } + switch (path.length) { case 0: return obj; + case 1: - return _isInteger(path[0]) && _isArray(obj) ? remove(path[0], 1, obj) : dissoc(path[0], obj); + return _dissoc(path[0], obj); + default: var head = path[0]; var tail = Array.prototype.slice.call(path, 1); + if (obj[head] == null) { - return obj; - } else if (_isInteger(head) && _isArray(obj)) { - return update(head, dissocPath(tail, obj[head]), obj); + return _shallowCloneObject(head, obj); } else { return assoc(head, dissocPath(tail, obj[head]), obj); } + } }); + /** + * Returns a new object that does not contain a `prop` property. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category Object + * @sig String -> {k: v} -> {k: v} + * @param {String} prop The name of the property to dissociate + * @param {Object} obj The object to clone + * @return {Object} A new object equivalent to the original but without the specified property + * @see R.assoc, R.omit + * @example + * + * R.dissoc('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} + */ + + var dissoc = _curry2(function dissoc(prop, obj) { + return dissocPath([prop], obj); + }); + /** * Divides two numbers. Equivalent to `a / b`. * @@ -3900,23 +4253,31 @@ * const reciprocal = R.divide(1); * reciprocal(4); //=> 0.25 */ - var divide = _curry2(function divide(a, b) { return a / b; }); + + var divide = _curry2(function divide(a, b) { + return a / b; + }); function XDrop(n, xf) { this.xf = xf; this.n = n; } + XDrop.prototype['@@transducer/init'] = _xfBase.init; XDrop.prototype['@@transducer/result'] = _xfBase.result; - XDrop.prototype['@@transducer/step'] = function(result, input) { + + XDrop.prototype['@@transducer/step'] = function (result, input) { if (this.n > 0) { this.n -= 1; return result; } + return this.xf['@@transducer/step'](result, input); }; - var _xdrop = _curry2(function _xdrop(n, xf) { return new XDrop(n, xf); }); + var _xdrop = _curry2(function _xdrop(n, xf) { + return new XDrop(n, xf); + }); /** * Returns all but the first `n` elements of the given list, string, or @@ -3942,6 +4303,7 @@ * R.drop(4, ['foo', 'bar', 'baz']); //=> [] * R.drop(3, 'ramda'); //=> 'da' */ + var drop = _curry2(_dispatchable(['drop'], _xdrop, function drop(n, xs) { return slice(Math.max(0, n), Infinity, xs); })); @@ -3951,15 +4313,19 @@ this.n = n; this.i = 0; } + XTake.prototype['@@transducer/init'] = _xfBase.init; XTake.prototype['@@transducer/result'] = _xfBase.result; - XTake.prototype['@@transducer/step'] = function(result, input) { + + XTake.prototype['@@transducer/step'] = function (result, input) { this.i += 1; var ret = this.n === 0 ? result : this.xf['@@transducer/step'](result, input); return this.n >= 0 && this.i >= this.n ? _reduced(ret) : ret; }; - var _xtake = _curry2(function _xtake(n, xf) { return new XTake(n, xf); }); + var _xtake = _curry2(function _xtake(n, xf) { + return new XTake(n, xf); + }); /** * Returns the first `n` elements of the given list, string, or @@ -4004,6 +4370,7 @@ * @symb R.take(1, [a, b]) = [a] * @symb R.take(2, [a, b]) = [a, b] */ + var take = _curry2(_dispatchable(['take'], _xtake, function take(n, xs) { return slice(0, n < 0 ? Infinity : n, xs); })); @@ -4018,28 +4385,36 @@ this.full = false; this.acc = new Array(n); } + XDropLast.prototype['@@transducer/init'] = _xfBase.init; - XDropLast.prototype['@@transducer/result'] = function(result) { + + XDropLast.prototype['@@transducer/result'] = function (result) { this.acc = null; return this.xf['@@transducer/result'](result); }; - XDropLast.prototype['@@transducer/step'] = function(result, input) { + + XDropLast.prototype['@@transducer/step'] = function (result, input) { if (this.full) { result = this.xf['@@transducer/step'](result, this.acc[this.pos]); } + this.store(input); return result; }; - XDropLast.prototype.store = function(input) { + + XDropLast.prototype.store = function (input) { this.acc[this.pos] = input; this.pos += 1; + if (this.pos === this.acc.length) { this.pos = 0; this.full = true; } }; - var _xdropLast = _curry2(function _xdropLast(n, xf) { return new XDropLast(n, xf); }); + var _xdropLast = _curry2(function _xdropLast(n, xf) { + return new XDropLast(n, xf); + }); /** * Returns a list containing all but the last `n` elements of the given `list`. @@ -4064,13 +4439,16 @@ * R.dropLast(4, ['foo', 'bar', 'baz']); //=> [] * R.dropLast(3, 'ramda'); //=> 'ra' */ + var dropLast$1 = _curry2(_dispatchable([], _xdropLast, dropLast)); function dropLastWhile(pred, xs) { var idx = xs.length - 1; + while (idx >= 0 && pred(xs[idx])) { idx -= 1; } + return slice(0, idx + 1, xs); } @@ -4079,31 +4457,32 @@ this.retained = []; this.xf = xf; } + XDropLastWhile.prototype['@@transducer/init'] = _xfBase.init; - XDropLastWhile.prototype['@@transducer/result'] = function(result) { + + XDropLastWhile.prototype['@@transducer/result'] = function (result) { this.retained = null; return this.xf['@@transducer/result'](result); }; - XDropLastWhile.prototype['@@transducer/step'] = function(result, input) { - return this.f(input) - ? this.retain(result, input) - : this.flush(result, input); + + XDropLastWhile.prototype['@@transducer/step'] = function (result, input) { + return this.f(input) ? this.retain(result, input) : this.flush(result, input); }; - XDropLastWhile.prototype.flush = function(result, input) { - result = _reduce( - this.xf['@@transducer/step'], - result, - this.retained - ); + + XDropLastWhile.prototype.flush = function (result, input) { + result = _reduce(this.xf['@@transducer/step'], result, this.retained); this.retained = []; return this.xf['@@transducer/step'](result, input); }; - XDropLastWhile.prototype.retain = function(result, input) { + + XDropLastWhile.prototype.retain = function (result, input) { this.retained.push(input); return result; }; - var _xdropLastWhile = _curry2(function _xdropLastWhile(fn, xf) { return new XDropLastWhile(fn, xf); }); + var _xdropLastWhile = _curry2(function _xdropLastWhile(fn, xf) { + return new XDropLastWhile(fn, xf); + }); /** * Returns a new list excluding all the tailing elements of a given list which @@ -4132,6 +4511,7 @@ * * R.dropLastWhile(x => x !== 'd' , 'Ramda'); //=> 'Ramd' */ + var dropLastWhile$1 = _curry2(_dispatchable([], _xdropLastWhile, dropLastWhile)); function XDropRepeatsWith(pred, xf) { @@ -4143,18 +4523,23 @@ XDropRepeatsWith.prototype['@@transducer/init'] = _xfBase.init; XDropRepeatsWith.prototype['@@transducer/result'] = _xfBase.result; - XDropRepeatsWith.prototype['@@transducer/step'] = function(result, input) { + + XDropRepeatsWith.prototype['@@transducer/step'] = function (result, input) { var sameAsLast = false; + if (!this.seenFirstValue) { this.seenFirstValue = true; } else if (this.pred(this.lastValue, input)) { sameAsLast = true; } + this.lastValue = input; return sameAsLast ? result : this.xf['@@transducer/step'](result, input); }; - var _xdropRepeatsWith = _curry2(function _xdropRepeatsWith(pred, xf) { return new XDropRepeatsWith(pred, xf); }); + var _xdropRepeatsWith = _curry2(function _xdropRepeatsWith(pred, xf) { + return new XDropRepeatsWith(pred, xf); + }); /** * Returns the last element of the given list or string. @@ -4176,6 +4561,7 @@ * R.last('abc'); //=> 'c' * R.last(''); //=> '' */ + var last = nth(-1); /** @@ -4199,19 +4585,24 @@ * const l = [1, -1, 1, 3, 4, -4, -4, -5, 5, 3, 3]; * R.dropRepeatsWith(R.eqBy(Math.abs), l); //=> [1, 3, 4, -5, 3] */ + var dropRepeatsWith = _curry2(_dispatchable([], _xdropRepeatsWith, function dropRepeatsWith(pred, list) { var result = []; var idx = 1; var len = list.length; + if (len !== 0) { result[0] = list[0]; + while (idx < len) { if (!pred(last(result), list[idx])) { result[result.length] = list[idx]; } + idx += 1; } } + return result; })); @@ -4233,27 +4624,32 @@ * * R.dropRepeats([1, 1, 1, 2, 3, 4, 4, 2, 2]); //=> [1, 2, 3, 4, 2] */ - var dropRepeats = _curry1( - _dispatchable([], _xdropRepeatsWith(equals), dropRepeatsWith(equals)) - ); + + var dropRepeats = _curry1(_dispatchable([], _xdropRepeatsWith(equals), dropRepeatsWith(equals))); function XDropWhile(f, xf) { this.xf = xf; this.f = f; } + XDropWhile.prototype['@@transducer/init'] = _xfBase.init; XDropWhile.prototype['@@transducer/result'] = _xfBase.result; - XDropWhile.prototype['@@transducer/step'] = function(result, input) { + + XDropWhile.prototype['@@transducer/step'] = function (result, input) { if (this.f) { if (this.f(input)) { return result; } + this.f = null; } + return this.xf['@@transducer/step'](result, input); }; - var _xdropWhile = _curry2(function _xdropWhile(f, xf) { return new XDropWhile(f, xf); }); + var _xdropWhile = _curry2(function _xdropWhile(f, xf) { + return new XDropWhile(f, xf); + }); /** * Returns a new list excluding the leading elements of a given list which @@ -4283,18 +4679,21 @@ * * R.dropWhile(x => x !== 'd' , 'Ramda'); //=> 'da' */ + var dropWhile = _curry2(_dispatchable(['dropWhile'], _xdropWhile, function dropWhile(pred, xs) { var idx = 0; var len = xs.length; + while (idx < len && pred(xs[idx])) { idx += 1; } + return slice(idx, Infinity, xs); })); /** - * Returns `true` if one or both of its arguments are `true`. Returns `false` - * if both arguments are `false`. + * Returns the first argument if it is truthy, otherwise the second argument. + * Acts as the boolean `or` statement if both inputs are `Boolean`s. * * @func * @memberOf R @@ -4303,8 +4702,8 @@ * @sig a -> b -> a | b * @param {Any} a * @param {Any} b - * @return {Any} the first argument if truthy, otherwise the second argument. - * @see R.either, R.xor + * @return {Any} + * @see R.either, R.and * @example * * R.or(true, true); //=> true @@ -4312,6 +4711,7 @@ * R.or(false, true); //=> true * R.or(false, false); //=> false */ + var or = _curry2(function or(a, b) { return a || b; }); @@ -4334,7 +4734,7 @@ * @param {Function} f a predicate * @param {Function} g another predicate * @return {Function} a function that applies its arguments to `f` and `g` and `||`s their outputs together. - * @see R.or + * @see R.both, R.or * @example * * const gt10 = x => x > 10; @@ -4346,17 +4746,36 @@ * R.either(Maybe.Just(false), Maybe.Just(55)); // => Maybe.Just(55) * R.either([false, false, 'a'], [11]) // => [11, 11, "a"] */ + var either = _curry2(function either(f, g) { - return _isFunction(f) ? - function _either() { - return f.apply(this, arguments) || g.apply(this, arguments); - } : - lift(or)(f, g); + return _isFunction(f) ? function _either() { + return f.apply(this, arguments) || g.apply(this, arguments); + } : lift(or)(f, g); }); + /** + * Tests whether or not an object is a typed array. + * + * @private + * @param {*} val The object to test. + * @return {Boolean} `true` if `val` is a typed array, `false` otherwise. + * @example + * + * _isTypedArray(new Uint8Array([])); //=> true + * _isTypedArray(new Float32Array([])); //=> true + * _isTypedArray([]); //=> false + * _isTypedArray(null); //=> false + * _isTypedArray({}); //=> false + */ + function _isTypedArray(val) { + var type = Object.prototype.toString.call(val); + return type === '[object Uint8ClampedArray]' || type === '[object Int8Array]' || type === '[object Uint8Array]' || type === '[object Int16Array]' || type === '[object Uint16Array]' || type === '[object Int32Array]' || type === '[object Uint32Array]' || type === '[object Float32Array]' || type === '[object Float64Array]' || type === '[object BigInt64Array]' || type === '[object BigUint64Array]'; + } + /** * Returns the empty value of its argument's type. Ramda defines the empty - * value of Array (`[]`), Object (`{}`), String (`''`), and Arguments. Other + * value of Array (`[]`), Object (`{}`), String (`''`), + * TypedArray (`Uint8Array []`, `Float32Array []`, etc), and Arguments. Other * types are supported if they define `.empty`, * `.prototype.empty` or implement the * [FantasyLand Monoid spec](https://github.com/fantasyland/fantasy-land#monoid). @@ -4372,31 +4791,18 @@ * @return {*} * @example * - * R.empty(Just(42)); //=> Nothing() - * R.empty([1, 2, 3]); //=> [] - * R.empty('unicorns'); //=> '' - * R.empty({x: 1, y: 2}); //=> {} + * R.empty(Just(42)); //=> Nothing() + * R.empty([1, 2, 3]); //=> [] + * R.empty('unicorns'); //=> '' + * R.empty({x: 1, y: 2}); //=> {} + * R.empty(Uint8Array.from('123')); //=> Uint8Array [] */ + var empty = _curry1(function empty(x) { - return ( - (x != null && typeof x['fantasy-land/empty'] === 'function') - ? x['fantasy-land/empty']() - : (x != null && x.constructor != null && typeof x.constructor['fantasy-land/empty'] === 'function') - ? x.constructor['fantasy-land/empty']() - : (x != null && typeof x.empty === 'function') - ? x.empty() - : (x != null && x.constructor != null && typeof x.constructor.empty === 'function') - ? x.constructor.empty() - : _isArray(x) - ? [] - : _isString(x) - ? '' - : _isObject(x) - ? {} - : _isArguments(x) - ? (function() { return arguments; }()) - : void 0 // else - ); + return x != null && typeof x['fantasy-land/empty'] === 'function' ? x['fantasy-land/empty']() : x != null && x.constructor != null && typeof x.constructor['fantasy-land/empty'] === 'function' ? x.constructor['fantasy-land/empty']() : x != null && typeof x.empty === 'function' ? x.empty() : x != null && x.constructor != null && typeof x.constructor.empty === 'function' ? x.constructor.empty() : _isArray(x) ? [] : _isString(x) ? '' : _isObject(x) ? {} : _isArguments(x) ? function () { + return arguments; + }() : _isTypedArray(x) ? x.constructor.from('') : void 0 // else + ; }); /** @@ -4421,6 +4827,7 @@ * R.takeLast(4, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz'] * R.takeLast(3, 'ramda'); //=> 'mda' */ + var takeLast = _curry2(function takeLast(n, xs) { return drop(n >= 0 ? xs.length - n : 0, xs); }); @@ -4447,7 +4854,8 @@ * R.endsWith(['c'], ['a', 'b', 'c']) //=> true * R.endsWith(['b'], ['a', 'b', 'c']) //=> false */ - var endsWith = _curry2(function(suffix, list) { + + var endsWith = _curry2(function (suffix, list) { return equals(takeLast(suffix.length, list), suffix); }); @@ -4468,6 +4876,7 @@ * * R.eqBy(Math.abs, 5, -5); //=> true */ + var eqBy = _curry3(function eqBy(f, x, y) { return equals(f(x), f(y)); }); @@ -4493,6 +4902,7 @@ * R.eqProps('a', o1, o2); //=> false * R.eqProps('c', o1, o2); //=> true */ + var eqProps = _curry3(function eqProps(prop, obj1, obj2) { return equals(obj1[prop], obj2[prop]); }); @@ -4524,18 +4934,21 @@ * }; * R.evolve(transformations, tomato); //=> {firstName: 'Tomato', data: {elapsed: 101, remaining: 1399}, id:123} */ + var evolve = _curry2(function evolve(transformations, object) { + if (!_isObject(object) && !_isArray(object)) { + return object; + } + var result = object instanceof Array ? [] : {}; var transformation, key, type; + for (key in object) { transformation = transformations[key]; - type = typeof transformation; - result[key] = type === 'function' - ? transformation(object[key]) - : transformation && type === 'object' - ? evolve(transformation, object[key]) - : object[key]; + type = _typeof(transformation); + result[key] = type === 'function' ? transformation(object[key]) : transformation && type === 'object' ? evolve(transformation, object[key]) : object[key]; } + return result; }); @@ -4544,22 +4957,29 @@ this.f = f; this.found = false; } + XFind.prototype['@@transducer/init'] = _xfBase.init; - XFind.prototype['@@transducer/result'] = function(result) { + + XFind.prototype['@@transducer/result'] = function (result) { if (!this.found) { result = this.xf['@@transducer/step'](result, void 0); } + return this.xf['@@transducer/result'](result); }; - XFind.prototype['@@transducer/step'] = function(result, input) { + + XFind.prototype['@@transducer/step'] = function (result, input) { if (this.f(input)) { this.found = true; result = _reduced(this.xf['@@transducer/step'](result, input)); } + return result; }; - var _xfind = _curry2(function _xfind(f, xf) { return new XFind(f, xf); }); + var _xfind = _curry2(function _xfind(f, xf) { + return new XFind(f, xf); + }); /** * Returns the first element of the list which matches the predicate, or @@ -4585,13 +5005,16 @@ * R.find(R.propEq('a', 2))(xs); //=> {a: 2} * R.find(R.propEq('a', 4))(xs); //=> undefined */ + var find = _curry2(_dispatchable(['find'], _xfind, function find(fn, list) { var idx = 0; var len = list.length; + while (idx < len) { if (fn(list[idx])) { return list[idx]; } + idx += 1; } })); @@ -4602,23 +5025,31 @@ this.idx = -1; this.found = false; } + XFindIndex.prototype['@@transducer/init'] = _xfBase.init; - XFindIndex.prototype['@@transducer/result'] = function(result) { + + XFindIndex.prototype['@@transducer/result'] = function (result) { if (!this.found) { result = this.xf['@@transducer/step'](result, -1); } + return this.xf['@@transducer/result'](result); }; - XFindIndex.prototype['@@transducer/step'] = function(result, input) { + + XFindIndex.prototype['@@transducer/step'] = function (result, input) { this.idx += 1; + if (this.f(input)) { this.found = true; result = _reduced(this.xf['@@transducer/step'](result, this.idx)); } + return result; }; - var _xfindIndex = _curry2(function _xfindIndex(f, xf) { return new XFindIndex(f, xf); }); + var _xfindIndex = _curry2(function _xfindIndex(f, xf) { + return new XFindIndex(f, xf); + }); /** * Returns the index of the first element of the list which matches the @@ -4635,22 +5066,26 @@ * desired one. * @param {Array} list The array to consider. * @return {Number} The index of the element found, or `-1`. - * @see R.transduce + * @see R.transduce, R.indexOf * @example * * const xs = [{a: 1}, {a: 2}, {a: 3}]; * R.findIndex(R.propEq('a', 2))(xs); //=> 1 * R.findIndex(R.propEq('a', 4))(xs); //=> -1 */ + var findIndex = _curry2(_dispatchable([], _xfindIndex, function findIndex(fn, list) { var idx = 0; var len = list.length; + while (idx < len) { if (fn(list[idx])) { return idx; } + idx += 1; } + return -1; })); @@ -4658,18 +5093,24 @@ this.xf = xf; this.f = f; } + XFindLast.prototype['@@transducer/init'] = _xfBase.init; - XFindLast.prototype['@@transducer/result'] = function(result) { + + XFindLast.prototype['@@transducer/result'] = function (result) { return this.xf['@@transducer/result'](this.xf['@@transducer/step'](result, this.last)); }; - XFindLast.prototype['@@transducer/step'] = function(result, input) { + + XFindLast.prototype['@@transducer/step'] = function (result, input) { if (this.f(input)) { this.last = input; } + return result; }; - var _xfindLast = _curry2(function _xfindLast(f, xf) { return new XFindLast(f, xf); }); + var _xfindLast = _curry2(function _xfindLast(f, xf) { + return new XFindLast(f, xf); + }); /** * Returns the last element of the list which matches the predicate, or @@ -4693,12 +5134,15 @@ * R.findLast(R.propEq('a', 1))(xs); //=> {a: 1, b: 1} * R.findLast(R.propEq('a', 4))(xs); //=> undefined */ + var findLast = _curry2(_dispatchable([], _xfindLast, function findLast(fn, list) { var idx = list.length - 1; + while (idx >= 0) { if (fn(list[idx])) { return list[idx]; } + idx -= 1; } })); @@ -4709,19 +5153,26 @@ this.idx = -1; this.lastIdx = -1; } + XFindLastIndex.prototype['@@transducer/init'] = _xfBase.init; - XFindLastIndex.prototype['@@transducer/result'] = function(result) { + + XFindLastIndex.prototype['@@transducer/result'] = function (result) { return this.xf['@@transducer/result'](this.xf['@@transducer/step'](result, this.lastIdx)); }; - XFindLastIndex.prototype['@@transducer/step'] = function(result, input) { + + XFindLastIndex.prototype['@@transducer/step'] = function (result, input) { this.idx += 1; + if (this.f(input)) { this.lastIdx = this.idx; } + return result; }; - var _xfindLastIndex = _curry2(function _xfindLastIndex(f, xf) { return new XFindLastIndex(f, xf); }); + var _xfindLastIndex = _curry2(function _xfindLastIndex(f, xf) { + return new XFindLastIndex(f, xf); + }); /** * Returns the index of the last element of the list which matches the @@ -4738,21 +5189,25 @@ * desired one. * @param {Array} list The array to consider. * @return {Number} The index of the element found, or `-1`. - * @see R.transduce + * @see R.transduce, R.lastIndexOf * @example * * const xs = [{a: 1, b: 0}, {a:1, b: 1}]; * R.findLastIndex(R.propEq('a', 1))(xs); //=> 1 * R.findLastIndex(R.propEq('a', 4))(xs); //=> -1 */ + var findLastIndex = _curry2(_dispatchable([], _xfindLastIndex, function findLastIndex(fn, list) { var idx = list.length - 1; + while (idx >= 0) { if (fn(list[idx])) { return idx; } + idx -= 1; } + return -1; })); @@ -4773,6 +5228,7 @@ * R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]); * //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] */ + var flatten = _curry1(_makeFlat(true)); /** @@ -4795,8 +5251,9 @@ * R.flip(mergeThree)(1, 2, 3); //=> [2, 1, 3] * @symb R.flip(f)(a, b, c) = f(b, a, c) */ + var flip = _curry1(function flip(fn) { - return curryN(fn.length, function(a, b) { + return curryN(fn.length, function (a, b) { var args = Array.prototype.slice.call(arguments, 0); args[0] = b; args[1] = a; @@ -4838,13 +5295,16 @@ * // logs 8 * @symb R.forEach(f, [a, b, c]) = [a, b, c] */ + var forEach = _curry2(_checkForMethod('forEach', function forEach(fn, list) { var len = list.length; var idx = 0; + while (idx < len) { fn(list[idx]); idx += 1; } + return list; })); @@ -4870,14 +5330,17 @@ * // logs y:2 * @symb R.forEachObjIndexed(f, {x: a, y: b}) = {x: a, y: b} */ + var forEachObjIndexed = _curry2(function forEachObjIndexed(fn, obj) { var keyList = keys(obj); var idx = 0; + while (idx < keyList.length) { var key = keyList[idx]; fn(obj[key], key, obj); idx += 1; } + return obj; }); @@ -4897,19 +5360,22 @@ * * R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3} */ + var fromPairs = _curry1(function fromPairs(pairs) { var result = {}; var idx = 0; + while (idx < pairs.length) { result[pairs[idx][0]] = pairs[idx][1]; idx += 1; } + return result; }); /** * Splits a list into sub-lists stored in an object, based on the result of - * calling a String-returning function on each element, and grouping the + * calling a key-returning function on each element, and grouping the * results according to values returned. * * Dispatches to the `groupBy` method of the second argument, if present. @@ -4920,12 +5386,13 @@ * @memberOf R * @since v0.1.0 * @category List - * @sig (a -> String) -> [a] -> {String: [a]} - * @param {Function} fn Function :: a -> String + * @typedefn Idx = String | Int | Symbol + * @sig Idx a => (b -> a) -> [b] -> {a: [b]} + * @param {Function} fn Function :: a -> Idx * @param {Array} list The array to group * @return {Object} An object with the output of `fn` for keys, mapped to arrays of elements * that produced that key when passed to `fn`. - * @see R.reduceBy, R.transduce + * @see R.reduceBy, R.transduce, R.indexBy * @example * * const byGrade = R.groupBy(function(student) { @@ -4947,13 +5414,11 @@ * // 'F': [{name: 'Eddy', score: 58}] * // } */ - var groupBy = _curry2(_checkForMethod('groupBy', reduceBy(function(acc, item) { - if (acc == null) { - acc = []; - } + + var groupBy = _curry2(_checkForMethod('groupBy', reduceBy(function (acc, item) { acc.push(item); return acc; - }, null))); + }, []))); /** * Takes a list and returns a list of lists where each sublist's elements are @@ -4982,21 +5447,27 @@ * R.groupWith((a, b) => a % 2 === b % 2, [0, 1, 1, 2, 3, 5, 8, 13, 21]) * //=> [[0], [1, 1], [2], [3, 5], [8], [13, 21]] * + * const isVowel = R.test(/^[aeiou]$/i); * R.groupWith(R.eqBy(isVowel), 'aestiou') * //=> ['ae', 'st', 'iou'] */ - var groupWith = _curry2(function(fn, list) { + + var groupWith = _curry2(function (fn, list) { var res = []; var idx = 0; var len = list.length; + while (idx < len) { var nextidx = idx + 1; + while (nextidx < len && fn(list[nextidx - 1], list[nextidx])) { nextidx += 1; } + res.push(list.slice(idx, nextidx)); idx = nextidx; } + return res; }); @@ -5021,7 +5492,10 @@ * R.gt('a', 'z'); //=> false * R.gt('z', 'a'); //=> true */ - var gt = _curry2(function gt(a, b) { return a > b; }); + + var gt = _curry2(function gt(a, b) { + return a > b; + }); /** * Returns `true` if the first argument is greater than or equal to the second; @@ -5044,7 +5518,10 @@ * R.gte('a', 'z'); //=> false * R.gte('z', 'a'); //=> true */ - var gte = _curry2(function gte(a, b) { return a >= b; }); + + var gte = _curry2(function gte(a, b) { + return a >= b; + }); /** * Returns whether or not a path exists in an object. Only the object's @@ -5054,7 +5531,7 @@ * @memberOf R * @since v0.26.0 * @category Object - * @typedefn Idx = String | Int + * @typedefn Idx = String | Int | Symbol * @sig [Idx] -> {a} -> Boolean * @param {Array} path The path to use. * @param {Object} obj The object to check the path in. @@ -5067,12 +5544,15 @@ * R.hasPath(['a', 'b'], {a: {c: 2}}); // => false * R.hasPath(['a', 'b'], {}); // => false */ + var hasPath = _curry2(function hasPath(_path, obj) { if (_path.length === 0 || isNil(obj)) { return false; } + var val = obj; var idx = 0; + while (idx < _path.length) { if (!isNil(val) && _has(_path[idx], val)) { val = val[_path[idx]]; @@ -5081,6 +5561,7 @@ return false; } } + return true; }); @@ -5108,6 +5589,7 @@ * pointHas('y'); //=> true * pointHas('z'); //=> false */ + var has = _curry2(function has(prop, obj) { return hasPath([prop], obj); }); @@ -5138,7 +5620,12 @@ * R.hasIn('width', square); //=> true * R.hasIn('area', square); //=> true */ + var hasIn = _curry2(function hasIn(prop, obj) { + if (isNil(obj)) { + return false; + } + return prop in obj; }); @@ -5167,6 +5654,7 @@ * R.identical(0, -0); //=> false * R.identical(NaN, NaN); //=> true */ + var identical = _curry2(_objectIs$1); /** @@ -5191,15 +5679,14 @@ * R.over(R.lensProp('count'), R.inc), * R.assoc('count', 1) * ); - * incCount({}); //=> { count: 1 } * incCount({ count: 1 }); //=> { count: 2 } + * incCount({}); //=> { count: 1 } */ + var ifElse = _curry3(function ifElse(condition, onTrue, onFalse) { - return curryN(Math.max(condition.length, onTrue.length, onFalse.length), - function _ifElse() { - return condition.apply(this, arguments) ? onTrue.apply(this, arguments) : onFalse.apply(this, arguments); - } - ); + return curryN(Math.max(condition.length, onTrue.length, onFalse.length), function _ifElse() { + return condition.apply(this, arguments) ? onTrue.apply(this, arguments) : onFalse.apply(this, arguments); + }); }); /** @@ -5217,12 +5704,13 @@ * * R.inc(42); //=> 43 */ + var inc = add(1); /** * Returns `true` if the specified value is equal, in [`R.equals`](#equals) * terms, to at least one element of the given list; `false` otherwise. - * Works also with strings. + * Also works with strings. * * @func * @memberOf R @@ -5241,6 +5729,7 @@ * R.includes([42], [[42]]); //=> true * R.includes('ba', 'banana'); //=>true */ + var includes = _curry2(_includes); /** @@ -5255,17 +5744,22 @@ * @memberOf R * @since v0.19.0 * @category List - * @sig (a -> String) -> [{k: v}] -> {k: {k: v}} - * @param {Function} fn Function :: a -> String + * @typedefn Idx = String | Int | Symbol + * @sig Idx a => (b -> a) -> [b] -> {a: b} + * @param {Function} fn Function :: a -> Idx * @param {Array} array The array of objects to index * @return {Object} An object indexing each array element by the given property. + * @see R.groupBy * @example * * const list = [{id: 'xyz', title: 'A'}, {id: 'abc', title: 'B'}]; * R.indexBy(R.prop('id'), list); * //=> {abc: {id: 'abc', title: 'B'}, xyz: {id: 'xyz', title: 'A'}} */ - var indexBy = reduceBy(function(acc, elem) { return elem; }, null); + + var indexBy = reduceBy(function (acc, elem) { + return elem; + }, null); /** * Returns the position of the first occurrence of an item in an array, or -1 @@ -5280,16 +5774,15 @@ * @param {*} target The item to find. * @param {Array} xs The array to search in. * @return {Number} the index of the target, or -1 if the target is not found. - * @see R.lastIndexOf + * @see R.lastIndexOf, R.findIndex * @example * * R.indexOf(3, [1,2,3,4]); //=> 2 * R.indexOf(10, [1,2,3,4]); //=> -1 */ + var indexOf = _curry2(function indexOf(target, xs) { - return typeof xs.indexOf === 'function' && !_isArray(xs) ? - xs.indexOf(target) : - _indexOf(xs, target, 0); + return typeof xs.indexOf === 'function' && !_isArray(xs) ? xs.indexOf(target) : _indexOf(xs, target, 0); }); /** @@ -5316,6 +5809,7 @@ * R.init('a'); //=> '' * R.init(''); //=> '' */ + var init = slice(0, -1); /** @@ -5353,8 +5847,11 @@ * ); * //=> [{id: 456, name: 'Stephen Stills'}, {id: 177, name: 'Neil Young'}] */ + var innerJoin = _curry3(function innerJoin(pred, xs, ys) { - return _filter(function(x) { return _includesWith(pred, x, ys); }, xs); + return _filter(function (x) { + return _includesWith(pred, x, ys); + }, xs); }); /** @@ -5376,6 +5873,7 @@ * * R.insert(2, 'x', [1,2,3,4]); //=> [1,2,'x',3,4] */ + var insert = _curry3(function insert(idx, elt, list) { idx = idx < list.length && idx >= 0 ? idx : list.length; var result = Array.prototype.slice.call(list, 0); @@ -5401,13 +5899,27 @@ * * R.insertAll(2, ['x','y','z'], [1,2,3,4]); //=> [1,2,'x','y','z',3,4] */ + var insertAll = _curry3(function insertAll(idx, elts, list) { idx = idx < list.length && idx >= 0 ? idx : list.length; - return [].concat( - Array.prototype.slice.call(list, 0, idx), - elts, - Array.prototype.slice.call(list, idx) - ); + return [].concat(Array.prototype.slice.call(list, 0, idx), elts, Array.prototype.slice.call(list, idx)); + }); + + function XUniqBy(f, xf) { + this.xf = xf; + this.f = f; + this.set = new _Set(); + } + + XUniqBy.prototype['@@transducer/init'] = _xfBase.init; + XUniqBy.prototype['@@transducer/result'] = _xfBase.result; + + XUniqBy.prototype['@@transducer/step'] = function (result, input) { + return this.set.add(this.f(input)) ? this.xf['@@transducer/step'](result, input) : result; + }; + + var _xuniqBy = _curry2(function _xuniqBy(f, xf) { + return new XUniqBy(f, xf); }); /** @@ -5416,6 +5928,8 @@ * each list element. Prefers the first item if the supplied function produces * the same value on two items. [`R.equals`](#equals) is used for comparison. * + * Acts as a transducer if a transformer is given in list position. + * * @func * @memberOf R * @since v0.16.0 @@ -5428,7 +5942,8 @@ * * R.uniqBy(Math.abs, [-1, -5, 2, 10, 1, 2]); //=> [-1, -5, 2, 10] */ - var uniqBy = _curry2(function uniqBy(fn, list) { + + var uniqBy = _curry2(_dispatchable([], _xuniqBy, function (fn, list) { var set = new _Set(); var result = []; var idx = 0; @@ -5437,13 +5952,16 @@ while (idx < list.length) { item = list[idx]; appliedItem = fn(item); + if (set.add(appliedItem)) { result.push(item); } + idx += 1; } + return result; - }); + })); /** * Returns a new list containing only one copy of each element in the original @@ -5462,6 +5980,7 @@ * R.uniq([1, '1']); //=> [1, '1'] * R.uniq([[42], [42]]); //=> [[42]] */ + var uniq = uniqBy(identity); /** @@ -5481,8 +6000,10 @@ * * R.intersection([1,2,3,4], [7,6,5,4,3]); //=> [4, 3] */ + var intersection = _curry2(function intersection(list1, list2) { var lookupList, filteredList; + if (list1.length > list2.length) { lookupList = list1; filteredList = list2; @@ -5490,6 +6011,7 @@ lookupList = list2; filteredList = list1; } + return uniq(_filter(flip(_includes)(lookupList), filteredList)); }); @@ -5510,22 +6032,25 @@ * * R.intersperse('a', ['b', 'n', 'n', 's']); //=> ['b', 'a', 'n', 'a', 'n', 'a', 's'] */ + var intersperse = _curry2(_checkForMethod('intersperse', function intersperse(separator, list) { var out = []; var idx = 0; var length = list.length; + while (idx < length) { if (idx === length - 1) { out.push(list[idx]); } else { out.push(list[idx], separator); } + idx += 1; } + return out; })); - // Based on https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign function _objectAssign(target) { if (target == null) { throw new TypeError('Cannot convert undefined or null to object'); @@ -5534,8 +6059,10 @@ var output = Object(target); var idx = 1; var length = arguments.length; + while (idx < length) { var source = arguments[idx]; + if (source != null) { for (var nextKey in source) { if (_has(nextKey, source)) { @@ -5543,8 +6070,10 @@ } } } + idx += 1; } + return output; } @@ -5570,6 +6099,7 @@ * ); * matchPhrases(['foo', 'bar', 'baz']); //=> {must: [{match_phrase: 'foo'}, {match_phrase: 'bar'}, {match_phrase: 'baz'}]} */ + var objOf = _curry2(function objOf(key, val) { var obj = {}; obj[key] = val; @@ -5578,7 +6108,7 @@ var _stepCatArray = { '@@transducer/init': Array, - '@@transducer/step': function(xs, x) { + '@@transducer/step': function transducerStep(xs, x) { xs.push(x); return xs; }, @@ -5586,33 +6116,35 @@ }; var _stepCatString = { '@@transducer/init': String, - '@@transducer/step': function(a, b) { return a + b; }, + '@@transducer/step': function transducerStep(a, b) { + return a + b; + }, '@@transducer/result': _identity }; var _stepCatObject = { '@@transducer/init': Object, - '@@transducer/step': function(result, input) { - return _objectAssign$1( - result, - _isArrayLike(input) ? objOf(input[0], input[1]) : input - ); + '@@transducer/step': function transducerStep(result, input) { + return _objectAssign$1(result, _isArrayLike(input) ? objOf(input[0], input[1]) : input); }, '@@transducer/result': _identity }; - function _stepCat(obj) { if (_isTransformer(obj)) { return obj; } + if (_isArrayLike(obj)) { return _stepCatArray; } + if (typeof obj === 'string') { return _stepCatString; } - if (typeof obj === 'object') { + + if (_typeof(obj) === 'object') { return _stepCatObject; } + throw new Error('Cannot create transformer for ' + obj); } @@ -5655,10 +6187,9 @@ * const intoArray = R.into([]); * intoArray(transducer, numbers); //=> [2, 3] */ + var into = _curry3(function into(acc, xf, list) { - return _isTransformer(acc) ? - _reduce(xf(acc), acc['@@transducer/init'](), list) : - _reduce(xf(_stepCat(acc)), _clone(acc, [], [], false), list); + return _isTransformer(acc) ? _reduce(xf(acc), acc['@@transducer/init'](), list) : _reduce(xf(_stepCat(acc)), _clone(acc, [], [], false), list); }); /** @@ -5683,6 +6214,7 @@ * R.invert(raceResultsByFirstName); * //=> { 'alice': ['first', 'third'], 'jake':['second'] } */ + var invert = _curry1(function invert(obj) { var props = keys(obj); var len = props.length; @@ -5692,10 +6224,11 @@ while (idx < len) { var key = props[idx]; var val = obj[key]; - var list = _has(val, out) ? out[val] : (out[val] = []); + var list = _has(val, out) ? out[val] : out[val] = []; list[list.length] = key; idx += 1; } + return out; }); @@ -5726,6 +6259,7 @@ * R.invertObj(raceResults); * //=> { 'alice': '0', 'jake':'1' } */ + var invertObj = _curry1(function invertObj(obj) { var props = keys(obj); var len = props.length; @@ -5737,6 +6271,7 @@ out[obj[key]] = key; idx += 1; } + return out; }); @@ -5774,19 +6309,23 @@ * @symb R.invoker(1, 'method')(a, o) = o['method'](a) * @symb R.invoker(2, 'method')(a, b, o) = o['method'](a, b) */ + var invoker = _curry2(function invoker(arity, method) { - return curryN(arity + 1, function() { + return curryN(arity + 1, function () { var target = arguments[arity]; + if (target != null && _isFunction(target[method])) { return target[method].apply(target, Array.prototype.slice.call(arguments, 0, arity)); } + throw new TypeError(toString$1(target) + ' does not have a method named "' + method + '"'); }); }); /** - * See if an object (`val`) is an instance of the supplied constructor. This + * See if an object (i.e. `val`) is an instance of the supplied constructor. This * function will check up the inheritance chain, if any. + * If `val` was created using `Object.create`, `R.is(Object, val) === true`. * * @func * @memberOf R @@ -5807,8 +6346,9 @@ * R.is(Object, 's'); //=> false * R.is(Number, {}); //=> false */ + var is = _curry2(function is(Ctor, val) { - return val != null && val.constructor === Ctor || val instanceof Ctor; + return val instanceof Ctor || val != null && (val.constructor === Ctor || Ctor.name === 'Object' && _typeof(val) === 'object'); }); /** @@ -5825,13 +6365,15 @@ * @see R.empty * @example * - * R.isEmpty([1, 2, 3]); //=> false - * R.isEmpty([]); //=> true - * R.isEmpty(''); //=> true - * R.isEmpty(null); //=> false - * R.isEmpty({}); //=> true - * R.isEmpty({length: 0}); //=> false + * R.isEmpty([1, 2, 3]); //=> false + * R.isEmpty([]); //=> true + * R.isEmpty(''); //=> true + * R.isEmpty(null); //=> false + * R.isEmpty({}); //=> true + * R.isEmpty({length: 0}); //=> false + * R.isEmpty(Uint8Array.from('')); //=> true */ + var isEmpty = _curry1(function isEmpty(x) { return x != null && equals(x, empty(x)); }); @@ -5855,6 +6397,7 @@ * spacer(['a', 2, 3.4]); //=> 'a 2 3.4' * R.join('|', [1, 2, 3]); //=> '1|2|3' */ + var join = invoker(1, 'join'); /** @@ -5874,8 +6417,11 @@ * getRange(3, 4, 9, -3); //=> [-3, 9] * @symb R.juxt([f, g, h])(a, b) = [f(a, b), g(a, b), h(a, b)] */ + var juxt = _curry1(function juxt(fns) { - return converge(function() { return Array.prototype.slice.call(arguments, 0); }, fns); + return converge(function () { + return Array.prototype.slice.call(arguments, 0); + }, fns); }); /** @@ -5899,12 +6445,15 @@ * const f = new F(); * R.keysIn(f); //=> ['x', 'y'] */ + var keysIn = _curry1(function keysIn(obj) { var prop; var ks = []; + for (prop in obj) { ks[ks.length] = prop; } + return ks; }); @@ -5921,23 +6470,27 @@ * @param {*} target The item to find. * @param {Array} xs The array to search in. * @return {Number} the index of the target, or -1 if the target is not found. - * @see R.indexOf + * @see R.indexOf, R.findLastIndex * @example * * R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6 * R.lastIndexOf(10, [1,2,3,4]); //=> -1 */ + var lastIndexOf = _curry2(function lastIndexOf(target, xs) { if (typeof xs.lastIndexOf === 'function' && !_isArray(xs)) { return xs.lastIndexOf(target); } else { var idx = xs.length - 1; + while (idx >= 0) { if (equals(xs[idx], target)) { return idx; } + idx -= 1; } + return -1; } }); @@ -5961,6 +6514,7 @@ * R.length([]); //=> 0 * R.length([1, 2, 3]); //=> 3 */ + var length = _curry1(function length(list) { return list != null && _isNumber(list.length) ? list.length : NaN; }); @@ -5988,41 +6542,131 @@ * R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} * R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} */ + var lens = _curry2(function lens(getter, setter) { - return function(toFunctorFn) { - return function(target) { - return map( - function(focus) { - return setter(focus, target); - }, - toFunctorFn(getter(target)) - ); + return function (toFunctorFn) { + return function (target) { + return map(function (focus) { + return setter(focus, target); + }, toFunctorFn(getter(target))); }; }; }); /** - * Returns a lens whose focus is the specified index. + * Returns a new copy of the array with the element at the provided index + * replaced with the given value. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category List + * @sig Number -> a -> [a] -> [a] + * @param {Number} idx The index to update. + * @param {*} x The value to exist at the given index of the returned array. + * @param {Array|Arguments} list The source array-like object to be updated. + * @return {Array} A copy of `list` with the value at index `idx` replaced with `x`. + * @see R.adjust + * @example + * + * R.update(1, '_', ['a', 'b', 'c']); //=> ['a', '_', 'c'] + * R.update(-1, '_', ['a', 'b', 'c']); //=> ['a', 'b', '_'] + * @symb R.update(-1, a, [b, c]) = [b, a] + * @symb R.update(0, a, [b, c]) = [a, c] + * @symb R.update(1, a, [b, c]) = [b, a] + */ + + var update = _curry3(function update(idx, x, list) { + return adjust(idx, always(x), list); + }); + + /** + * Returns a lens whose focus is the specified index. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category Object + * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s + * @sig Number -> Lens s a + * @param {Number} n + * @return {Lens} + * @see R.view, R.set, R.over, R.nth + * @example + * + * const headLens = R.lensIndex(0); + * + * R.view(headLens, ['a', 'b', 'c']); //=> 'a' + * R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c'] + * R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c'] + */ + + var lensIndex = _curry1(function lensIndex(n) { + return lens(nth(n), update(n)); + }); + + /** + * Retrieves the values at given paths of an object. + * + * @func + * @memberOf R + * @since v0.27.1 + * @category Object + * @typedefn Idx = [String | Int | Symbol] + * @sig [Idx] -> {a} -> [a | Undefined] + * @param {Array} pathsArray The array of paths to be fetched. + * @param {Object} obj The object to retrieve the nested properties from. + * @return {Array} A list consisting of values at paths specified by "pathsArray". + * @see R.path + * @example + * + * R.paths([['a', 'b'], ['p', 0, 'q']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, 3] + * R.paths([['a', 'b'], ['p', 'r']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, undefined] + */ + + var paths = _curry2(function paths(pathsArray, obj) { + return pathsArray.map(function (paths) { + var val = obj; + var idx = 0; + var p; + + while (idx < paths.length) { + if (val == null) { + return; + } + + p = paths[idx]; + val = _isInteger(p) ? nth(p, val) : val[p]; + idx += 1; + } + + return val; + }); + }); + + /** + * Retrieve the value at a given path. * * @func * @memberOf R - * @since v0.14.0 + * @since v0.2.0 * @category Object - * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s - * @sig Number -> Lens s a - * @param {Number} n - * @return {Lens} - * @see R.view, R.set, R.over, R.nth + * @typedefn Idx = String | Int | Symbol + * @sig [Idx] -> {a} -> a | Undefined + * @param {Array} path The path to use. + * @param {Object} obj The object to retrieve the nested property from. + * @return {*} The data at `path`. + * @see R.prop, R.nth * @example * - * const headLens = R.lensIndex(0); - * - * R.view(headLens, ['a', 'b', 'c']); //=> 'a' - * R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c'] - * R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c'] + * R.path(['a', 'b'], {a: {b: 2}}); //=> 2 + * R.path(['a', 'b'], {c: {b: 2}}); //=> undefined + * R.path(['a', 'b', 0], {a: {b: [1, 2, 3]}}); //=> 1 + * R.path(['a', 'b', -2], {a: {b: [1, 2, 3]}}); //=> 2 */ - var lensIndex = _curry1(function lensIndex(n) { - return lens(nth(n), update(n)); + + var path = _curry2(function path(pathAr, obj) { + return paths([pathAr], obj)[0]; }); /** @@ -6032,7 +6676,7 @@ * @memberOf R * @since v0.19.0 * @category Object - * @typedefn Idx = String | Int + * @typedefn Idx = String | Int | Symbol * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s * @sig [Idx] -> Lens s a * @param {Array} path The path to use. @@ -6049,6 +6693,7 @@ * R.over(xHeadYLens, R.negate, {x: [{y: 2, z: 3}, {y: 4, z: 5}]}); * //=> {x: [{y: -2, z: 3}, {y: 4, z: 5}]} */ + var lensPath = _curry1(function lensPath(p) { return lens(path(p), assocPath(p)); }); @@ -6073,6 +6718,7 @@ * R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} * R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} */ + var lensProp = _curry1(function lensProp(k) { return lens(prop(k), assoc(k)); }); @@ -6098,7 +6744,10 @@ * R.lt('a', 'z'); //=> true * R.lt('z', 'a'); //=> false */ - var lt = _curry2(function lt(a, b) { return a < b; }); + + var lt = _curry2(function lt(a, b) { + return a < b; + }); /** * Returns `true` if the first argument is less than or equal to the second; @@ -6121,7 +6770,10 @@ * R.lte('a', 'z'); //=> true * R.lte('z', 'a'); //=> false */ - var lte = _curry2(function lte(a, b) { return a <= b; }); + + var lte = _curry2(function lte(a, b) { + return a <= b; + }); /** * The `mapAccum` function behaves like a combination of map and reduce; it @@ -6157,16 +6809,19 @@ * ] * ] */ + var mapAccum = _curry3(function mapAccum(fn, acc, list) { var idx = 0; var len = list.length; var result = []; var tuple = [acc]; + while (idx < len) { tuple = fn(tuple[0], list[idx]); result[idx] = tuple[1]; idx += 1; } + return [tuple[0], result]; }); @@ -6207,15 +6862,18 @@ * ] * ] */ + var mapAccumRight = _curry3(function mapAccumRight(fn, acc, list) { var idx = list.length - 1; var result = []; var tuple = [acc]; + while (idx >= 0) { tuple = fn(tuple[0], list[idx]); result[idx] = tuple[1]; idx -= 1; } + return [tuple[0], result]; }); @@ -6240,8 +6898,9 @@ * * R.mapObjIndexed(prependKeyAndDouble, xyz); //=> { x: 'x2', y: 'y4', z: 'z6' } */ + var mapObjIndexed = _curry2(function mapObjIndexed(fn, obj) { - return _reduce(function(acc, key) { + return _reduce(function (acc, key) { acc[key] = fn(obj[key], key, obj); return acc; }, {}, keys(obj)); @@ -6268,6 +6927,7 @@ * R.match(/a/, 'b'); //=> [] * R.match(/a/, null); //=> TypeError: null does not have a method named "match" */ + var match = _curry2(function match(rx, str) { return str.match(rx) || []; }); @@ -6305,10 +6965,17 @@ * seventeenMod(4); //=> 1 * seventeenMod(10); //=> 7 */ + var mathMod = _curry2(function mathMod(m, p) { - if (!_isInteger(m)) { return NaN; } - if (!_isInteger(p) || p < 1) { return NaN; } - return ((m % p) + p) % p; + if (!_isInteger(m)) { + return NaN; + } + + if (!_isInteger(p) || p < 1) { + return NaN; + } + + return (m % p + p) % p; }); /** @@ -6335,6 +7002,7 @@ * R.reduce(R.maxBy(square), 0, [3, -5, 4, 1, -2]); //=> -5 * R.reduce(R.maxBy(square), 0, []); //=> 0 */ + var maxBy = _curry3(function maxBy(f, a, b) { return f(b) > f(a) ? b : a; }); @@ -6354,6 +7022,7 @@ * * R.sum([2,4,6,8,100,1]); //=> 121 */ + var sum = reduce(add, 0); /** @@ -6372,6 +7041,7 @@ * R.mean([2, 7, 9]); //=> 6 * R.mean([]); //=> NaN */ + var mean = _curry1(function mean(list) { return sum(list) / list.length; }); @@ -6393,14 +7063,17 @@ * R.median([7, 2, 10, 9]); //=> 8 * R.median([]); //=> NaN */ + var median = _curry1(function median(list) { var len = list.length; + if (len === 0) { return NaN; } + var width = 2 - len % 2; var idx = (len - width) / 2; - return mean(Array.prototype.slice.call(list, 0).sort(function(a, b) { + return mean(Array.prototype.slice.call(list, 0).sort(function (a, b) { return a < b ? -1 : a > b ? 1 : 0; }).slice(idx, idx + width)); }); @@ -6412,6 +7085,8 @@ * call to `fn`; instead, the cached result for that set of arguments will be * returned. * + * Care must be taken when implementing key generation to avoid key collision, + * or if tracking references, memory leaks and mutating arguments. * * @func * @memberOf R @@ -6424,7 +7099,7 @@ * @example * * let count = 0; - * const factorial = R.memoizeWith(R.identity, n => { + * const factorial = R.memoizeWith(Number, n => { * count += 1; * return R.product(R.range(1, n + 1)); * }); @@ -6433,47 +7108,24 @@ * factorial(5); //=> 120 * count; //=> 1 */ + var memoizeWith = _curry2(function memoizeWith(mFn, fn) { var cache = {}; - return _arity(fn.length, function() { + return _arity(fn.length, function () { var key = mFn.apply(this, arguments); + if (!_has(key, cache)) { cache[key] = fn.apply(this, arguments); } + return cache[key]; }); }); /** - * Create a new object with the own properties of the first object merged with - * the own properties of the second object. If a key exists in both objects, - * the value from the second object will be used. - * - * @func - * @memberOf R - * @since v0.1.0 - * @category Object - * @sig {k: v} -> {k: v} -> {k: v} - * @param {Object} l - * @param {Object} r - * @return {Object} - * @see R.mergeRight, R.mergeDeepRight, R.mergeWith, R.mergeWithKey - * @deprecated since v0.26.0 - * @example - * - * R.merge({ 'name': 'fred', 'age': 10 }, { 'age': 40 }); - * //=> { 'name': 'fred', 'age': 40 } - * - * const withDefaults = R.merge({x: 0, y: 0}); - * withDefaults({y: 2}); //=> {x: 0, y: 2} - * @symb R.merge(a, b) = {...a, ...b} - */ - var merge = _curry2(function merge(l, r) { - return _objectAssign$1({}, l, r); - }); - - /** - * Merges a list of objects together into one object. + * Creates one new object with the own properties from a list of objects. + * If a key exists in more than one object, the value from the last + * object it exists in will be used. * * @func * @memberOf R @@ -6489,6 +7141,7 @@ * R.mergeAll([{foo:1},{foo:2},{bar:2}]); //=> {foo:2,bar:2} * @symb R.mergeAll([{ x: 1 }, { y: 2 }, { z: 3 }]) = { x: 1, y: 2, z: 3 } */ + var mergeAll = _curry1(function mergeAll(list) { return _objectAssign$1.apply(null, [{}].concat(list)); }); @@ -6518,6 +7171,7 @@ * //=> { a: true, b: true, thing: 'bar', values: [10, 20, 15, 35] } * @symb R.mergeWithKey(f, { x: 1, y: 2 }, { y: 5, z: 3 }) = { x: 1, y: f('y', 2, 5), z: 3 } */ + var mergeWithKey = _curry3(function mergeWithKey(fn, l, r) { var result = {}; var k; @@ -6529,7 +7183,7 @@ } for (k in r) { - if (_has(k, r) && !(_has(k, result))) { + if (_has(k, r) && !_has(k, result)) { result[k] = r[k]; } } @@ -6565,8 +7219,9 @@ * { b: true, c: { thing: 'bar', values: [15, 35] }}); * //=> { a: true, b: true, c: { thing: 'bar', values: [10, 20, 15, 35] }} */ + var mergeDeepWithKey = _curry3(function mergeDeepWithKey(fn, lObj, rObj) { - return mergeWithKey(function(k, lVal, rVal) { + return mergeWithKey(function (k, lVal, rVal) { if (_isObject(lVal) && _isObject(rVal)) { return mergeDeepWithKey(fn, lVal, rVal); } else { @@ -6596,8 +7251,9 @@ * { age: 40, contact: { email: 'baa@example.com' }}); * //=> { name: 'fred', age: 10, contact: { email: 'moo@example.com' }} */ + var mergeDeepLeft = _curry2(function mergeDeepLeft(lObj, rObj) { - return mergeDeepWithKey(function(k, lVal, rVal) { + return mergeDeepWithKey(function (k, lVal, rVal) { return lVal; }, lObj, rObj); }); @@ -6623,8 +7279,9 @@ * { age: 40, contact: { email: 'baa@example.com' }}); * //=> { name: 'fred', age: 40, contact: { email: 'baa@example.com' }} */ + var mergeDeepRight = _curry2(function mergeDeepRight(lObj, rObj) { - return mergeDeepWithKey(function(k, lVal, rVal) { + return mergeDeepWithKey(function (k, lVal, rVal) { return rVal; }, lObj, rObj); }); @@ -6656,8 +7313,9 @@ * { b: true, c: { values: [15, 35] }}); * //=> { a: true, b: true, c: { values: [10, 20, 15, 35] }} */ + var mergeDeepWith = _curry3(function mergeDeepWith(fn, lObj, rObj) { - return mergeDeepWithKey(function(k, lVal, rVal) { + return mergeDeepWithKey(function (k, lVal, rVal) { return fn(lVal, rVal); }, lObj, rObj); }); @@ -6685,6 +7343,7 @@ * resetToDefault({x: 5, y: 2}); //=> {x: 0, y: 2} * @symb R.mergeLeft(a, b) = {...b, ...a} */ + var mergeLeft = _curry2(function mergeLeft(l, r) { return _objectAssign$1({}, r, l); }); @@ -6712,6 +7371,7 @@ * withDefaults({y: 2}); //=> {x: 0, y: 2} * @symb R.mergeRight(a, b) = {...a, ...b} */ + var mergeRight = _curry2(function mergeRight(l, r) { return _objectAssign$1({}, l, r); }); @@ -6739,8 +7399,9 @@ * { b: true, values: [15, 35] }); * //=> { a: true, b: true, values: [10, 20, 15, 35] } */ + var mergeWith = _curry3(function mergeWith(fn, l, r) { - return mergeWithKey(function(_, _l, _r) { + return mergeWithKey(function (_, _l, _r) { return fn(_l, _r); }, l, r); }); @@ -6762,7 +7423,10 @@ * R.min(789, 123); //=> 123 * R.min('a', 'b'); //=> 'a' */ - var min = _curry2(function min(a, b) { return b < a ? b : a; }); + + var min = _curry2(function min(a, b) { + return b < a ? b : a; + }); /** * Takes a function and two values, and returns whichever value produces the @@ -6788,10 +7452,119 @@ * R.reduce(R.minBy(square), Infinity, [3, -5, 4, 1, -2]); //=> 1 * R.reduce(R.minBy(square), Infinity, []); //=> Infinity */ + var minBy = _curry3(function minBy(f, a, b) { return f(b) < f(a) ? b : a; }); + /** + * Makes a shallow clone of an object, applying the given fn to the specified + * property with the given value. Note that this copies and flattens prototype + * properties onto the new object as well. All non-primitive properties are + * copied by reference. + * + * @private + * @param {String|Number} prop The property name to set + * @param {Function} fn The function to apply to the property + * @param {Object|Array} obj The object to clone + * @return {Object|Array} A new object equivalent to the original except for the changed property. + */ + + function _modify(prop, fn, obj) { + if (_isInteger(prop) && _isArray(obj)) { + var arr = [].concat(obj); + arr[prop] = fn(arr[prop]); + return arr; + } + + var result = {}; + + for (var p in obj) { + result[p] = obj[p]; + } + + result[prop] = fn(result[prop]); + return result; + } + + /** + * Creates a shallow clone of the passed object by applying an `fn` function + * to the value at the given path. + * + * The function will not be invoked, and the object will not change + * if its corresponding path does not exist in the object. + * All non-primitive properties are copied to the new object by reference. + * + * @func + * @memberOf R + * @since v0.28.0 + * @category Object + * @sig [Idx] -> (v -> v) -> {k: v} -> {k: v} + * @param {Array} path The path to be modified. + * @param {Function} fn The function to apply to the path. + * @param {Object} object The object to be transformed. + * @return {Object} The transformed object. + * @example + * + * const person = {name: 'James', address: { zipCode: '90216' }}; + * R.modifyPath(['address', 'zipCode'], R.reverse, person); //=> {name: 'James', address: { zipCode: '61209' }} + * + * // Can handle arrays too + * const person = {name: 'James', addresses: [{ zipCode: '90216' }]}; + * R.modifyPath(['addresses', 0, 'zipCode'], R.reverse, person); //=> {name: 'James', addresses: [{ zipCode: '61209' }]} + */ + + var modifyPath = _curry3(function modifyPath(path, fn, object) { + if (!_isObject(object) && !_isArray(object) || path.length === 0) { + return object; + } + + var idx = path[0]; + + if (!_has(idx, object)) { + return object; + } + + if (path.length === 1) { + return _modify(idx, fn, object); + } + + var val = modifyPath(Array.prototype.slice.call(path, 1), fn, object[idx]); + + if (val === object[idx]) { + return object; + } + + return _assoc(idx, val, object); + }); + + /** + * Creates a copy of the passed object by applying an `fn` function to the given `prop` property. + * + * The function will not be invoked, and the object will not change + * if its corresponding property does not exist in the object. + * All non-primitive properties are copied to the new object by reference. + * + * @func + * @memberOf R + * @since v0.28.0 + * @category Object + * @sig Idx -> (v -> v) -> {k: v} -> {k: v} + * @param {String|Number} prop The property to be modified. + * @param {Function} fn The function to apply to the property. + * @param {Object} object The object to be transformed. + * @return {Object} The transformed object. + * @example + * + * const person = {name: 'James', age: 20, pets: ['dog', 'cat']}; + * R.modify('age', R.add(1), person); //=> {name: 'James', age: 21, pets: ['dog', 'cat']} + * R.modify('pets', R.append('turtle'), person); //=> {name: 'James', age: 20, pets: ['dog', 'cat', 'turtle']} + */ + + var modify = _curry3(function modify(prop, fn, object) { + return modifyPath([prop], fn, object); + }); + /** * Divides the first parameter by the second and returns the remainder. Note * that this function preserves the JavaScript-style behavior for modulo. For @@ -6817,7 +7590,10 @@ * isOdd(42); //=> 0 * isOdd(21); //=> 1 */ - var modulo = _curry2(function modulo(a, b) { return a % b; }); + + var modulo = _curry2(function modulo(a, b) { + return a % b; + }); /** * Move an item, at index `from`, to index `to`, in a list of elements. @@ -6837,20 +7613,14 @@ * R.move(0, 2, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['b', 'c', 'a', 'd', 'e', 'f'] * R.move(-1, 0, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['f', 'a', 'b', 'c', 'd', 'e'] list rotation */ - var move = _curry3(function(from, to, list) { + + var move = _curry3(function (from, to, list) { var length = list.length; var result = list.slice(); var positiveFrom = from < 0 ? length + from : from; var positiveTo = to < 0 ? length + to : to; var item = result.splice(positiveFrom, 1); - - return positiveFrom < 0 || positiveFrom >= list.length - || positiveTo < 0 || positiveTo >= list.length - ? list - : [] - .concat(result.slice(0, positiveTo)) - .concat(item) - .concat(result.slice(positiveTo, list.length)); + return positiveFrom < 0 || positiveFrom >= list.length || positiveTo < 0 || positiveTo >= list.length ? list : [].concat(result.slice(0, positiveTo)).concat(item).concat(result.slice(positiveTo, list.length)); }); /** @@ -6873,7 +7643,46 @@ * triple(4); //=> 12 * R.multiply(2, 5); //=> 10 */ - var multiply = _curry2(function multiply(a, b) { return a * b; }); + + var multiply = _curry2(function multiply(a, b) { + return a * b; + }); + + var _this = undefined; + /** + * Takes a function `f` and an object, and returns a function `g`. + * When applied, `g` returns the result of applying `f` to the object + * provided initially merged deeply (right) with the object provided as an argument to `g`. + * + * @func + * @memberOf R + * @since v0.28.0 + * @category Function + * @sig (({ a, b, c, ..., n }) -> x) -> { a, b, c, ...} -> ({ d, e, f, ..., n } -> x) + * @param {Function} f + * @param {Object} props + * @return {Function} + * @see R.partial, R.partialRight, R.curry, R.mergeDeepRight + * @example + * + * const multiply2 = ({ a, b }) => a * b; + * const double = R.partialObject(multiply2, { a: 2 }); + * double({ b: 2 }); //=> 4 + * + * const greet = ({ salutation, title, firstName, lastName }) => + * salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; + * + * const sayHello = R.partialObject(greet, { salutation: 'Hello' }); + * const sayHelloToMs = R.partialObject(sayHello, { title: 'Ms.' }); + * sayHelloToMs({ firstName: 'Jane', lastName: 'Jones' }); //=> 'Hello, Ms. Jane Jones!' + * @symb R.partialObject(f, { a, b })({ c, d }) = f({ a, b, c, d }) + */ + + var partialObject = _curry2(function (f, o) { + return function (props) { + return f.call(_this, mergeDeepRight(o, props)); + }; + }); /** * Negates its argument. @@ -6889,7 +7698,10 @@ * * R.negate(42); //=> -42 */ - var negate = _curry1(function negate(n) { return -n; }); + + var negate = _curry1(function negate(n) { + return -n; + }); /** * Returns `true` if no elements of the list match the predicate, `false` @@ -6911,11 +7723,12 @@ * @example * * const isEven = n => n % 2 === 0; - * const isOdd = n => n % 2 === 1; + * const isOdd = n => n % 2 !== 0; * * R.none(isEven, [1, 3, 5, 7, 9, 11]); //=> true * R.none(isOdd, [1, 3, 5, 7, 8, 11]); //=> false */ + var none = _curry2(function none(fn, input) { return all(_complement(fn), input); }); @@ -6938,9 +7751,10 @@ * @symb R.nthArg(0)(a, b, c) = a * @symb R.nthArg(1)(a, b, c) = b */ + var nthArg = _curry1(function nthArg(n) { var arity = n < 0 ? 1 : n + 1; - return curryN(arity, function() { + return curryN(arity, function () { return nth(n, arguments); }); }); @@ -6972,11 +7786,14 @@ * * @symb R.o(f, g, x) = f(g(x)) */ + var o = _curry3(function o(f, g, x) { return f(g(x)); }); - function _of(x) { return [x]; } + function _of(x) { + return [x]; + } /** * Returns a singleton array containing the value provided. @@ -6996,6 +7813,7 @@ * R.of(null); //=> [null] * R.of([42]); //=> [[42]] */ + var of = _curry1(_of); /** @@ -7014,6 +7832,7 @@ * * R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3} */ + var omit = _curry2(function omit(names, obj) { var result = {}; var index = {}; @@ -7030,9 +7849,40 @@ result[prop] = obj[prop]; } } + return result; }); + /** + * Takes a binary function `f`, a unary function `g`, and two values. + * Applies `g` to each value, then applies the result of each to `f`. + * + * Also known as the P combinator. + * + * @func + * @memberOf R + * @since v0.28.0 + * @category Function + * @sig ((a, a) -> b) -> (c -> a) -> c -> c -> b + * @param {Function} f a binary function + * @param {Function} g a unary function + * @param {any} a any value + * @param {any} b any value + * @return {any} The result of `f` + * @example + * + * const eqBy = R.on((a, b) => a === b); + * eqBy(R.prop('a'), {b:0, a:1}, {a:1}) //=> true; + * + * const containsInsensitive = R.on(R.contains, R.toLower); + * containsInsensitive('o', 'FOO'); //=> true + * @symb R.on(f, g, a, b) = f(g(a), g(b)) + */ + + var on = _curryN(4, [], function on(f, g, a, b) { + return f(g(a), g(b)); + }); + /** * Accepts a function `fn` and returns a function that guards invocation of * `fn` such that `fn` can only ever be called once, no matter how many times @@ -7052,13 +7902,15 @@ * addOneOnce(10); //=> 11 * addOneOnce(addOneOnce(50)); //=> 11 */ + var once = _curry1(function once(fn) { var called = false; var result; - return _arity(fn.length, function() { + return _arity(fn.length, function () { if (called) { return result; } + called = true; result = fn.apply(this, arguments); return result; @@ -7085,33 +7937,37 @@ * @param {Function} onFailure The function to apply. Can return a value or a promise of a value. * @param {Promise} p * @return {Promise} The result of calling `p.then(null, onFailure)` - * @see R.then + * @see R.andThen * @example * - * var failedFetch = (id) => Promise.reject('bad ID'); - * var useDefault = () => ({ firstName: 'Bob', lastName: 'Loblaw' }) + * const failedFetch = id => Promise.reject('bad ID'); + * const useDefault = () => ({ firstName: 'Bob', lastName: 'Loblaw' }); * - * //recoverFromFailure :: String -> Promise ({firstName, lastName}) - * var recoverFromFailure = R.pipe( + * //recoverFromFailure :: String -> Promise ({ firstName, lastName }) + * const recoverFromFailure = R.pipe( * failedFetch, * R.otherwise(useDefault), - * R.then(R.pick(['firstName', 'lastName'])), + * R.andThen(R.pick(['firstName', 'lastName'])), * ); - * recoverFromFailure(12345).then(console.log) + * recoverFromFailure(12345).then(console.log); */ + var otherwise = _curry2(function otherwise(f, p) { _assertPromise('otherwise', p); return p.then(null, f); }); - // `Identity` is a functor that holds a single value, where `map` simply // transforms the held value with the provided function. - var Identity = function(x) { - return {value: x, map: function(f) { return Identity(f(x)); }}; - }; - + var Identity = function Identity(x) { + return { + value: x, + map: function map(f) { + return Identity(f(x)); + } + }; + }; /** * Returns the result of "setting" the portion of the given data structure * focused by the given lens to the result of applying the given function to @@ -7127,18 +7983,22 @@ * @param {*} v * @param {*} x * @return {*} - * @see R.prop, R.lensIndex, R.lensProp + * @see R.view, R.set, R.lens, R.lensIndex, R.lensProp, R.lensPath * @example * * const headLens = R.lensIndex(0); * * R.over(headLens, R.toUpper, ['foo', 'bar', 'baz']); //=> ['FOO', 'bar', 'baz'] */ + + var over = _curry3(function over(lens, f, x) { // The value returned by the getter function is first transformed with `f`, // then set as the value of an `Identity`. This is then mapped over with the // setter function of the lens. - return lens(function(y) { return Identity(f(y)); })(x).value; + return lens(function (y) { + return Identity(f(y)); + })(x).value; }); /** @@ -7157,11 +8017,14 @@ * * R.pair('foo', 'bar'); //=> ['foo', 'bar'] */ - var pair = _curry2(function pair(fst, snd) { return [fst, snd]; }); + + var pair = _curry2(function pair(fst, snd) { + return [fst, snd]; + }); function _createPartialApplicator(concat) { - return _curry2(function(fn, args) { - return _arity(Math.max(0, fn.length - args.length), function() { + return _curry2(function (fn, args) { + return _arity(Math.max(0, fn.length - args.length), function () { return fn.apply(this, concat(args, arguments)); }); }); @@ -7185,7 +8048,7 @@ * * const multiply2 = (a, b) => a * b; * const double = R.partial(multiply2, [2]); - * double(2); //=> 4 + * double(3); //=> 6 * * const greet = (salutation, title, firstName, lastName) => * salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; @@ -7195,6 +8058,7 @@ * sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!' * @symb R.partial(f, [a, b])(c, d) = f(a, b, c, d) */ + var partial = _createPartialApplicator(_concat); /** @@ -7221,6 +8085,7 @@ * greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!' * @symb R.partialRight(f, [a, b])(c, d) = f(c, d, a, b) */ + var partialRight = _createPartialApplicator(flip(_concat)); /** @@ -7247,6 +8112,7 @@ * R.partition(R.includes('s'), { a: 'sss', b: 'ttt', foo: 'bars' }); * // => [ { a: 'sss', foo: 'bars' }, { b: 'ttt' } ] */ + var partition = juxt([filter, reject]); /** @@ -7257,7 +8123,7 @@ * @memberOf R * @since v0.7.0 * @category Relation - * @typedefn Idx = String | Int + * @typedefn Idx = String | Int | Symbol * @sig [Idx] -> a -> {a} -> Boolean * @param {Array} path The path of the nested property to use * @param {*} val The value to compare the nested property with @@ -7273,6 +8139,7 @@ * const isFamous = R.pathEq(['address', 'zipCode'], 90210); * R.filter(isFamous, users); //=> [ user1 ] */ + var pathEq = _curry3(function pathEq(_path, val, obj) { return equals(path(_path, obj), val); }); @@ -7285,7 +8152,7 @@ * @memberOf R * @since v0.18.0 * @category Object - * @typedefn Idx = String | Int + * @typedefn Idx = String | Int | Symbol * @sig a -> [Idx] -> {a} -> a * @param {*} d The default value. * @param {Array} p The path to use. @@ -7296,6 +8163,7 @@ * R.pathOr('N/A', ['a', 'b'], {a: {b: 2}}); //=> 2 * R.pathOr('N/A', ['a', 'b'], {c: {b: 2}}); //=> "N/A" */ + var pathOr = _curry3(function pathOr(d, p, obj) { return defaultTo(d, path(p, obj)); }); @@ -7308,7 +8176,7 @@ * @memberOf R * @since v0.19.0 * @category Logic - * @typedefn Idx = String | Int + * @typedefn Idx = String | Int | Symbol * @sig (a -> Boolean) -> [Idx] -> {a} -> Boolean * @param {Function} pred * @param {Array} propPath @@ -7320,6 +8188,7 @@ * R.pathSatisfies(y => y > 0, ['x', 'y'], {x: {y: 2}}); //=> true * R.pathSatisfies(R.is(Object), [], {x: {y: 2}}); //=> true */ + var pathSatisfies = _curry3(function pathSatisfies(pred, propPath, obj) { return pred(path(propPath, obj)); }); @@ -7342,15 +8211,19 @@ * R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} * R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1} */ + var pick = _curry2(function pick(names, obj) { var result = {}; var idx = 0; + while (idx < names.length) { if (names[idx] in obj) { result[names[idx]] = obj[names[idx]]; } + idx += 1; } + return result; }); @@ -7372,15 +8245,18 @@ * R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} * R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined} */ + var pickAll = _curry2(function pickAll(names, obj) { var result = {}; var idx = 0; var len = names.length; + while (idx < len) { var name = names[idx]; result[name] = obj[name]; idx += 1; } + return result; }); @@ -7404,58 +8280,19 @@ * const isUpperCase = (val, key) => key.toUpperCase() === key; * R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4} */ + var pickBy = _curry2(function pickBy(test, obj) { var result = {}; + for (var prop in obj) { if (test(obj[prop], prop, obj)) { result[prop] = obj[prop]; } } + return result; }); - /** - * Returns the left-to-right Kleisli composition of the provided functions, - * each of which must return a value of a type supported by [`chain`](#chain). - * - * `R.pipeK(f, g, h)` is equivalent to `R.pipe(f, R.chain(g), R.chain(h))`. - * - * @func - * @memberOf R - * @since v0.16.0 - * @category Function - * @sig Chain m => ((a -> m b), (b -> m c), ..., (y -> m z)) -> (a -> m z) - * @param {...Function} - * @return {Function} - * @see R.composeK - * @deprecated since v0.26.0 - * @example - * - * // parseJson :: String -> Maybe * - * // get :: String -> Object -> Maybe * - * - * // getStateCode :: Maybe String -> Maybe String - * const getStateCode = R.pipeK( - * parseJson, - * get('user'), - * get('address'), - * get('state'), - * R.compose(Maybe.of, R.toUpper) - * ); - * - * getStateCode('{"user":{"address":{"state":"ny"}}}'); - * //=> Just('NY') - * getStateCode('[Invalid JSON]'); - * //=> Nothing() - * @symb R.pipeK(f, g, h)(a) = R.chain(h, R.chain(g, f(a))) - */ - function pipeK() { - if (arguments.length === 0) { - throw new Error('pipeK requires at least one argument'); - } - return composeK.apply(this, reverse(arguments)); - } - /** * Returns a new list with the given element at the front, followed by the * contents of the list. @@ -7473,6 +8310,7 @@ * * R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum'] */ + var prepend = _curry2(function prepend(el, list) { return _concat([el], list); }); @@ -7492,6 +8330,7 @@ * * R.product([2,4,6,8,100,1]); //=> 38400 */ + var product = reduce(multiply, 1); /** @@ -7523,14 +8362,17 @@ * R.useWith(Math.pow, [R.dec, R.inc])(3)(4); //=> 32 * @symb R.useWith(f, [g, h])(a, b) = f(g(a), h(b)) */ + var useWith = _curry2(function useWith(fn, transformers) { - return curryN(transformers.length, function() { + return curryN(transformers.length, function () { var args = []; var idx = 0; + while (idx < transformers.length) { args.push(transformers[idx].call(this, arguments[idx])); idx += 1; } + return fn.apply(this, args.concat(Array.prototype.slice.call(arguments, transformers.length))); }); }); @@ -7547,6 +8389,7 @@ * @param {Array} props The property names to project * @param {Array} objs The objects to query * @return {Array} An array of objects with just the `props` properties. + * @see R.pluck, R.props, R.prop * @example * * const abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2}; @@ -7554,8 +8397,64 @@ * const kids = [abby, fred]; * R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}] */ + var project = useWith(_map, [pickAll, identity]); // passing `identity` gives correct arity + function _promap(f, g, profunctor) { + return function (x) { + return g(profunctor(f(x))); + }; + } + + function XPromap(f, g, xf) { + this.xf = xf; + this.f = f; + this.g = g; + } + + XPromap.prototype['@@transducer/init'] = _xfBase.init; + XPromap.prototype['@@transducer/result'] = _xfBase.result; + + XPromap.prototype['@@transducer/step'] = function (result, input) { + return this.xf['@@transducer/step'](result, _promap(this.f, this.g, input)); + }; + + var _xpromap = _curry3(function _xpromap(f, g, xf) { + return new XPromap(f, g, xf); + }); + + /** + * Takes two functions as pre- and post- processors respectively for a third function, + * i.e. `promap(f, g, h)(x) === g(h(f(x)))`. + * + * Dispatches to the `promap` method of the third argument, if present, + * according to the [FantasyLand Profunctor spec](https://github.com/fantasyland/fantasy-land#profunctor). + * + * Acts as a transducer if a transformer is given in profunctor position. + * + * @func + * @memberOf R + * @since v0.28.0 + * @category Function + * @sig (a -> b) -> (c -> d) -> (b -> c) -> (a -> d) + * @sig Profunctor p => (a -> b) -> (c -> d) -> p b c -> p a d + * @param {Function} f The preprocessor function, a -> b + * @param {Function} g The postprocessor function, c -> d + * @param {Profunctor} profunctor The profunctor instance to be promapped, e.g. b -> c + * @return {Profunctor} The new profunctor instance, e.g. a -> d + * @see R.transduce + * @example + * + * const decodeChar = R.promap(s => s.charCodeAt(), String.fromCharCode, R.add(-8)) + * const decodeString = R.promap(R.split(''), R.join(''), R.map(decodeChar)) + * decodeString("ziuli") //=> "ramda" + * + * @symb R.promap(f, g, h) = x => g(h(f(x))) + * @symb R.promap(f, g, profunctor) = profunctor.promap(f, g) + */ + + var promap = _curry3(_dispatchable(['fantasy-land/promap', 'promap'], _xpromap, _promap)); + /** * Returns `true` if the specified object property is equal, in * [`R.equals`](#equals) terms, to the given value; `false` otherwise. @@ -7581,8 +8480,9 @@ * const hasBrownHair = R.propEq('hair', 'brown'); * R.filter(hasBrownHair, kids); //=> [fred, rusty] */ + var propEq = _curry3(function propEq(name, val, obj) { - return equals(val, obj[name]); + return equals(val, prop(name, obj)); }); /** @@ -7605,14 +8505,16 @@ * R.propIs(Number, 'x', {x: 'foo'}); //=> false * R.propIs(Number, 'x', {}); //=> false */ + var propIs = _curry3(function propIs(type, name, obj) { - return is(type, obj[name]); + return is(type, prop(name, obj)); }); /** - * If the given, non-null object has an own property with the specified name, - * returns the value of that property. Otherwise returns the provided default - * value. + * Return the specified property of the given non-null object if the property + * is present and it's value is not `null`, `undefined` or `NaN`. + * + * Otherwise the first argument is returned. * * @func * @memberOf R @@ -7635,8 +8537,9 @@ * favorite(alice); //=> undefined * favoriteWithDefault(alice); //=> 'Ramda' */ + var propOr = _curry3(function propOr(val, p, obj) { - return pathOr(val, [p], obj); + return defaultTo(val, prop(p, obj)); }); /** @@ -7658,8 +8561,9 @@ * * R.propSatisfies(x => x > 0, 'x', {x: 1, y: 2}); //=> true */ + var propSatisfies = _curry3(function propSatisfies(pred, name, obj) { - return pred(obj[name]); + return pred(prop(name, obj)); }); /** @@ -7674,6 +8578,7 @@ * @param {Array} ps The property names to fetch * @param {Object} obj The object to query * @return {Array} The corresponding values or partially applied function. + * @see R.prop, R.pluck, R.project * @example * * R.props(['x', 'y'], {x: 1, y: 2}); //=> [1, 2] @@ -7682,8 +8587,9 @@ * const fullName = R.compose(R.join(' '), R.props(['first', 'last'])); * fullName({last: 'Bullet-Tooth', age: 33, first: 'Tony'}); //=> 'Tony Bullet-Tooth' */ + var props = _curry2(function props(ps, obj) { - return ps.map(function(p) { + return ps.map(function (p) { return path([p], obj); }); }); @@ -7704,16 +8610,20 @@ * R.range(1, 5); //=> [1, 2, 3, 4] * R.range(50, 53); //=> [50, 51, 52] */ + var range = _curry2(function range(from, to) { if (!(_isNumber(from) && _isNumber(to))) { throw new TypeError('Both arguments to range must be numbers'); } + var result = []; var n = from; + while (n < to) { result.push(n); n += 1; } + return result; }); @@ -7726,7 +8636,8 @@ * right to the left. * * The iterator function receives two values: *(value, acc)*, while the arguments' - * order of `reduce`'s iterator function is *(acc, value)*. + * order of `reduce`'s iterator function is *(acc, value)*. `reduceRight` may use [`reduced`](#reduced) + * to short circuit the iteration. * * Note: `R.reduceRight` does not skip deleted or unassigned indices (sparse * arrays), unlike the native `Array.prototype.reduceRight` method. For more details @@ -7743,7 +8654,7 @@ * @param {*} acc The accumulator value. * @param {Array} list The list to iterate over. * @return {*} The final, accumulated value. - * @see R.reduce, R.addIndex + * @see R.reduce, R.addIndex, R.reduced * @example * * R.reduceRight(R.subtract, 0, [1, 2, 3, 4]) // => (1 - (2 - (3 - (4 - 0)))) = -2 @@ -7759,12 +8670,21 @@ * * @symb R.reduceRight(f, a, [b, c, d]) = f(b, f(c, f(d, a))) */ + var reduceRight = _curry3(function reduceRight(fn, acc, list) { var idx = list.length - 1; + while (idx >= 0) { acc = fn(list[idx], acc); + + if (acc && acc['@@transducer/reduced']) { + acc = acc['@@transducer/value']; + break; + } + idx -= 1; } + return acc; }); @@ -7773,7 +8693,8 @@ * through the list, successively calling the iterator function. `reduceWhile` * also takes a predicate that is evaluated before each step. If the predicate * returns `false`, it "short-circuits" the iteration and returns the current - * value of the accumulator. + * value of the accumulator. `reduceWhile` may alternatively be short-circuited + * via [`reduced`](#reduced). * * @func * @memberOf R @@ -7790,15 +8711,16 @@ * @see R.reduce, R.reduced * @example * - * const isOdd = (acc, x) => x % 2 === 1; + * const isOdd = (acc, x) => x % 2 !== 0; * const xs = [1, 3, 5, 60, 777, 800]; * R.reduceWhile(isOdd, R.add, 0, xs); //=> 9 * * const ys = [2, 4, 6] * R.reduceWhile(isOdd, R.add, 111, ys); //=> 111 */ + var reduceWhile = _curryN(4, [], function _reduceWhile(pred, fn, a, list) { - return _reduce(function(acc, x) { + return _reduce(function (acc, x) { return pred(acc, x) ? fn(acc, x) : _reduced(acc); }, a, list); }); @@ -7808,9 +8730,11 @@ * and transduce functions. The returned value should be considered a black * box: the internal structure is not guaranteed to be stable. * - * Note: this optimization is only available to the below functions: + * This optimization is available to the below functions: * - [`reduce`](#reduce) * - [`reduceWhile`](#reduceWhile) + * - [`reduceBy`](#reduceBy) + * - [`reduceRight`](#reduceRight) * - [`transduce`](#transduce) * * @func @@ -7820,7 +8744,7 @@ * @sig a -> * * @param {*} x The final value of the reduce. * @return {*} The wrapped value. - * @see R.reduce, R.reduceWhile, R.transduce + * @see R.reduce, R.reduceWhile, R.reduceBy, R.reduceRight, R.transduce * @example * * R.reduce( @@ -7828,6 +8752,7 @@ * [], * [1, 2, 3, 4, 5]) // [1, 2, 3] */ + var reduced = _curry1(_reduced); /** @@ -7853,6 +8778,7 @@ * @symb R.times(f, 1) = [f(0)] * @symb R.times(f, 2) = [f(0), f(1)] */ + var times = _curry2(function times(fn, n) { var len = Number(n); var idx = 0; @@ -7861,11 +8787,14 @@ if (len < 0 || isNaN(len)) { throw new RangeError('n must be a non-negative number'); } + list = new Array(len); + while (idx < len) { list[idx] = fn(idx); idx += 1; } + return list; }); @@ -7892,6 +8821,7 @@ * @symb R.repeat(a, 1) = [a] * @symb R.repeat(a, 2) = [a, a] */ + var repeat = _curry2(function repeat(value, n) { return times(always(value), n); }); @@ -7920,6 +8850,7 @@ * // Use the "g" (global) flag to replace all occurrences: * R.replace(/foo/g, 'bar', 'foo foo foo'); //=> 'bar bar bar' */ + var replace = _curry3(function replace(regex, replacement, str) { return str.replace(regex, replacement); }); @@ -7945,15 +8876,18 @@ * const factorials = R.scan(R.multiply, 1, numbers); //=> [1, 1, 2, 6, 24] * @symb R.scan(f, a, [b, c]) = [a, f(a, b), f(f(a, b), c)] */ + var scan = _curry3(function scan(fn, acc, list) { var idx = 0; var len = list.length; var result = [acc]; + while (idx < len) { acc = fn(acc, list[idx]); result[idx + 1] = acc; idx += 1; } + return result; }); @@ -7981,14 +8915,11 @@ * R.sequence(R.of, Just([1, 2, 3])); //=> [Just(1), Just(2), Just(3)] * R.sequence(R.of, Nothing()); //=> [Nothing()] */ + var sequence = _curry2(function sequence(of, traversable) { - return typeof traversable.sequence === 'function' ? - traversable.sequence(of) : - reduceRight( - function(x, acc) { return ap(map(prepend, x), acc); }, - of([]), - traversable - ); + return typeof traversable.sequence === 'function' ? traversable.sequence(of) : reduceRight(function (x, acc) { + return ap(map(prepend, x), acc); + }, of([]), traversable); }); /** @@ -8005,7 +8936,7 @@ * @param {*} v * @param {*} x * @return {*} - * @see R.prop, R.lensIndex, R.lensProp + * @see R.view, R.over, R.lens, R.lensIndex, R.lensProp, R.lensPath * @example * * const xLens = R.lensProp('x'); @@ -8013,6 +8944,7 @@ * R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} * R.set(xLens, 8, {x: 1, y: 2}); //=> {x: 8, y: 2} */ + var set = _curry3(function set(lens, v, x) { return over(lens, always(v), x); }); @@ -8032,11 +8964,13 @@ * @param {Function} comparator A sorting function :: a -> b -> Int * @param {Array} list The list to sort * @return {Array} a new array with its elements sorted by the comparator function. + * @see R.ascend, R.descend * @example * * const diff = function(a, b) { return a - b; }; * R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7] */ + var sort = _curry2(function sort(comparator, list) { return Array.prototype.slice.call(list, 0).sort(comparator); }); @@ -8074,8 +9008,9 @@ * const people = [clara, bob, alice]; * sortByNameCaseInsensitive(people); //=> [alice, bob, clara] */ + var sortBy = _curry2(function sortBy(fn, list) { - return Array.prototype.slice.call(list, 0).sort(function(a, b) { + return Array.prototype.slice.call(list, 0).sort(function (a, b) { var aa = fn(a); var bb = fn(b); return aa < bb ? -1 : aa > bb ? 1 : 0; @@ -8093,6 +9028,7 @@ * @param {Array} functions A list of comparator functions. * @param {Array} list The list to sort. * @return {Array} A new list sorted according to the comarator functions. + * @see R.ascend, R.descend * @example * * const alice = { @@ -8114,14 +9050,17 @@ * ]); * ageNameSort(people); //=> [alice, clara, bob] */ + var sortWith = _curry2(function sortWith(fns, list) { - return Array.prototype.slice.call(list, 0).sort(function(a, b) { + return Array.prototype.slice.call(list, 0).sort(function (a, b) { var result = 0; var i = 0; + while (result === 0 && i < fns.length) { result = fns[i](a, b); i += 1; } + return result; }); }); @@ -8146,6 +9085,7 @@ * * R.split('.', 'a.b.c.xyz.d'); //=> ['a', 'b', 'c', 'xyz', 'd'] */ + var split = invoker(1, 'split'); /** @@ -8166,6 +9106,7 @@ * R.splitAt(5, 'hello world'); //=> ['hello', ' world'] * R.splitAt(-1, 'foobar'); //=> ['fooba', 'r'] */ + var splitAt = _curry2(function splitAt(index, array) { return [slice(0, index, array), slice(index, length(array), array)]; }); @@ -8187,15 +9128,19 @@ * R.splitEvery(3, [1, 2, 3, 4, 5, 6, 7]); //=> [[1, 2, 3], [4, 5, 6], [7]] * R.splitEvery(3, 'foobarbaz'); //=> ['foo', 'bar', 'baz'] */ + var splitEvery = _curry2(function splitEvery(n, list) { if (n <= 0) { throw new Error('First argument to splitEvery must be a positive integer'); } + var result = []; var idx = 0; + while (idx < list.length) { result.push(slice(idx, idx += n, list)); } + return result; }); @@ -8218,6 +9163,7 @@ * * R.splitWhen(R.equals(2), [1, 2, 3, 1, 2, 3]); //=> [[1], [2, 3, 1, 2, 3]] */ + var splitWhen = _curry2(function splitWhen(pred, list) { var idx = 0; var len = list.length; @@ -8231,6 +9177,40 @@ return [prefix, Array.prototype.slice.call(list, idx)]; }); + /** + * Splits an array into slices on every occurrence of a value. + * + * @func + * @memberOf R + * @since v0.26.1 + * @category List + * @sig (a -> Boolean) -> [a] -> [[a]] + * @param {Function} pred The predicate that determines where the array is split. + * @param {Array} list The array to be split. + * @return {Array} + * @example + * + * R.splitWhenever(R.equals(2), [1, 2, 3, 2, 4, 5, 2, 6, 7]); //=> [[1], [3], [4, 5], [6, 7]] + */ + + var splitWhenever = _curryN(2, [], function splitWhenever(pred, list) { + var acc = []; + var curr = []; + + for (var i = 0; i < list.length; i = i + 1) { + if (!pred(list[i])) { + curr.push(list[i]); + } + + if ((i < list.length - 1 && pred(list[i + 1]) || i === list.length - 1) && curr.length > 0) { + acc.push(curr); + curr = []; + } + } + + return acc; + }); + /** * Checks if a list starts with the provided sublist. * @@ -8253,7 +9233,8 @@ * R.startsWith(['a'], ['a', 'b', 'c']) //=> true * R.startsWith(['b'], ['a', 'b', 'c']) //=> false */ - var startsWith = _curry2(function(prefix, list) { + + var startsWith = _curry2(function (prefix, list) { return equals(take(prefix.length, list), prefix); }); @@ -8280,6 +9261,7 @@ * complementaryAngle(30); //=> 60 * complementaryAngle(72); //=> 18 */ + var subtract = _curry2(function subtract(a, b) { return Number(a) - Number(b); }); @@ -8302,6 +9284,7 @@ * R.symmetricDifference([1,2,3,4], [7,6,5,4,3]); //=> [1,2,7,6,5] * R.symmetricDifference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5,1,2] */ + var symmetricDifference = _curry2(function symmetricDifference(list1, list2) { return concat(difference(list1, list2), difference(list2, list1)); }); @@ -8328,6 +9311,7 @@ * const l2 = [{a: 3}, {a: 4}, {a: 5}, {a: 6}]; * R.symmetricDifferenceWith(eqA, l1, l2); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}] */ + var symmetricDifferenceWith = _curry3(function symmetricDifferenceWith(pred, list1, list2) { return concat(differenceWith(pred, list1, list2), differenceWith(pred, list2, list1)); }); @@ -8357,11 +9341,14 @@ * * R.takeLastWhile(x => x !== 'R' , 'Ramda'); //=> 'amda' */ + var takeLastWhile = _curry2(function takeLastWhile(fn, xs) { var idx = xs.length - 1; + while (idx >= 0 && fn(xs[idx])) { idx -= 1; } + return slice(idx + 1, Infinity, xs); }); @@ -8369,13 +9356,17 @@ this.xf = xf; this.f = f; } + XTakeWhile.prototype['@@transducer/init'] = _xfBase.init; XTakeWhile.prototype['@@transducer/result'] = _xfBase.result; - XTakeWhile.prototype['@@transducer/step'] = function(result, input) { + + XTakeWhile.prototype['@@transducer/step'] = function (result, input) { return this.f(input) ? this.xf['@@transducer/step'](result, input) : _reduced(result); }; - var _xtakeWhile = _curry2(function _xtakeWhile(f, xf) { return new XTakeWhile(f, xf); }); + var _xtakeWhile = _curry2(function _xtakeWhile(f, xf) { + return new XTakeWhile(f, xf); + }); /** * Returns a new list containing the first `n` elements of a given list, @@ -8406,12 +9397,15 @@ * * R.takeWhile(x => x !== 'd' , 'Ramda'); //=> 'Ram' */ + var takeWhile = _curry2(_dispatchable(['takeWhile'], _xtakeWhile, function takeWhile(fn, xs) { var idx = 0; var len = xs.length; + while (idx < len && fn(xs[idx])) { idx += 1; } + return slice(0, idx, xs); })); @@ -8419,14 +9413,18 @@ this.xf = xf; this.f = f; } + XTap.prototype['@@transducer/init'] = _xfBase.init; XTap.prototype['@@transducer/result'] = _xfBase.result; - XTap.prototype['@@transducer/step'] = function(result, input) { + + XTap.prototype['@@transducer/step'] = function (result, input) { this.f(input); return this.xf['@@transducer/step'](result, input); }; - var _xtap = _curry2(function _xtap(f, xf) { return new XTap(f, xf); }); + var _xtap = _curry2(function _xtap(f, xf) { + return new XTap(f, xf); + }); /** * Runs the given function with the supplied object, then returns the object. @@ -8448,6 +9446,7 @@ * // logs 'x is 100' * @symb R.tap(f, a) = a */ + var tap = _curry2(_dispatchable([], _xtap, function tap(fn, x) { fn(x); return x; @@ -8474,10 +9473,12 @@ * R.test(/^x/, 'xyz'); //=> true * R.test(/^y/, 'xyz'); //=> false */ + var test = _curry2(function test(pattern, str) { if (!_isRegExp(pattern)) { throw new TypeError('‘test’ requires a value of type RegExp as its first argument; received ' + toString$1(pattern)); } + return _cloneRegExp(pattern).test(str); }); @@ -8498,15 +9499,20 @@ * @see R.otherwise * @example * - * var makeQuery = (email) => ({ query: { email }}); + * const makeQuery = email => ({ query: { email }}); + * const fetchMember = request => + * Promise.resolve({ firstName: 'Bob', lastName: 'Loblaw', id: 42 }); * - * //getMemberName :: String -> Promise ({firstName, lastName}) - * var getMemberName = R.pipe( + * //getMemberName :: String -> Promise ({ firstName, lastName }) + * const getMemberName = R.pipe( * makeQuery, * fetchMember, * R.andThen(R.pick(['firstName', 'lastName'])) * ); + * + * getMemberName('bob@gmail.com').then(console.log); */ + var andThen = _curry2(function andThen(f, p) { _assertPromise('andThen', p); @@ -8528,6 +9534,7 @@ * * R.toLower('XYZ'); //=> 'xyz' */ + var toLower = invoker(0, 'toLowerCase'); /** @@ -8543,18 +9550,21 @@ * @sig {String: *} -> [[String,*]] * @param {Object} obj The object to extract from * @return {Array} An array of key, value arrays from the object's own properties. - * @see R.fromPairs + * @see R.fromPairs, R.keys, R.values * @example * * R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]] */ + var toPairs = _curry1(function toPairs(obj) { var pairs = []; + for (var prop in obj) { if (_has(prop, obj)) { pairs[pairs.length] = [prop, obj[prop]]; } } + return pairs; }); @@ -8579,11 +9589,14 @@ * const f = new F(); * R.toPairsIn(f); //=> [['x','X'], ['y','Y']] */ + var toPairsIn = _curry1(function toPairsIn(obj) { var pairs = []; + for (var prop in obj) { pairs[pairs.length] = [prop, obj[prop]]; } + return pairs; }); @@ -8602,6 +9615,7 @@ * * R.toUpper('abc'); //=> 'ABC' */ + var toUpper = invoker(0, 'toUpperCase'); /** @@ -8618,7 +9632,7 @@ * A transducer is a function that accepts a transformer and returns a * transformer and can be composed directly. * - * A transformer is an an object that provides a 2-arity reducing iterator + * A transformer is an object that provides a 2-arity reducing iterator * function, step, 0-arity initial value function, init, and 1-arity result * extraction function, result. The step function is used as the iterator * function in reduce. The result function is used to convert the final @@ -8647,10 +9661,11 @@ * const transducer = R.compose(R.map(R.add(1)), R.take(2)); * R.transduce(transducer, R.flip(R.append), [], numbers); //=> [2, 3] * - * const isOdd = (x) => x % 2 === 1; + * const isOdd = (x) => x % 2 !== 0; * const firstOddTransducer = R.compose(R.filter(isOdd), R.take(1)); * R.transduce(firstOddTransducer, R.flip(R.append), [], R.range(0, 100)); //=> [1] */ + var transduce = curryN(4, function transduce(xf, fn, acc, list) { return _reduce(xf(typeof fn === 'function' ? _xwrap(fn) : fn), acc, list); }); @@ -8679,21 +9694,27 @@ * @symb R.transpose([[a, b], [c, d]]) = [[a, c], [b, d]] * @symb R.transpose([[a, b], [c]]) = [[a, c], [b]] */ + var transpose = _curry1(function transpose(outerlist) { var i = 0; var result = []; + while (i < outerlist.length) { var innerlist = outerlist[i]; var j = 0; + while (j < innerlist.length) { if (typeof result[j] === 'undefined') { result[j] = []; } + result[j].push(innerlist[j]); j += 1; } + i += 1; } + return result; }); @@ -8723,17 +9744,14 @@ * R.traverse(Maybe.of, safeDiv(10), [2, 4, 5]); //=> Maybe.Just([5, 2.5, 2]) * R.traverse(Maybe.of, safeDiv(10), [2, 0, 5]); //=> Maybe.Nothing */ + var traverse = _curry3(function traverse(of, f, traversable) { - return typeof traversable['fantasy-land/traverse'] === 'function' ? - traversable['fantasy-land/traverse'](f, of) : - sequence(of, map(f, traversable)); + return typeof traversable['fantasy-land/traverse'] === 'function' ? traversable['fantasy-land/traverse'](f, of) : typeof traversable.traverse === 'function' ? traversable.traverse(f, of) : sequence(of, map(f, traversable)); }); - var ws = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003' + - '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028' + - '\u2029\uFEFF'; - var zeroWidth = '\u200b'; - var hasProtoTrim = (typeof String.prototype.trim === 'function'); + var ws = "\t\n\x0B\f\r \xA0\u1680\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; + var zeroWidth = "\u200B"; + var hasProtoTrim = typeof String.prototype.trim === 'function'; /** * Removes (strips) whitespace from both ends of the string. * @@ -8749,15 +9767,14 @@ * R.trim(' xyz '); //=> 'xyz' * R.map(R.trim, R.split(',', 'x, y, z')); //=> ['x', 'y', 'z'] */ - var trim = !hasProtoTrim || ws.trim() || !zeroWidth.trim() ? - _curry1(function trim(str) { - var beginRx = new RegExp('^[' + ws + '][' + ws + ']*'); - var endRx = new RegExp('[' + ws + '][' + ws + ']*$'); - return str.replace(beginRx, '').replace(endRx, ''); - }) : - _curry1(function trim(str) { - return str.trim(); - }); + + var trim = !hasProtoTrim || ws.trim() || !zeroWidth.trim() ? _curry1(function trim(str) { + var beginRx = new RegExp('^[' + ws + '][' + ws + ']*'); + var endRx = new RegExp('[' + ws + '][' + ws + ']*$'); + return str.replace(beginRx, '').replace(endRx, ''); + }) : _curry1(function trim(str) { + return str.trim(); + }); /** * `tryCatch` takes two functions, a `tryer` and a `catcher`. The returned @@ -8774,16 +9791,18 @@ * @sig (...x -> a) -> ((e, ...x) -> a) -> (...x -> a) * @param {Function} tryer The function that may throw. * @param {Function} catcher The function that will be evaluated if `tryer` throws. - * @return {Function} A new function that will catch exceptions and send then to the catcher. + * @return {Function} A new function that will catch exceptions and send them to the catcher. * @example * * R.tryCatch(R.prop('x'), R.F)({x: true}); //=> true - * R.tryCatch(() => { throw 'foo'}, R.always('catched'))('bar') // => 'catched' + * R.tryCatch(() => { throw 'foo'}, R.always('caught'))('bar') // => + * 'caught' * R.tryCatch(R.times(R.identity), R.always([]))('s') // => [] * R.tryCatch(() => { throw 'this is not a valid value'}, (err, value)=>({error : err, value }))('bar') // => {'error': 'this is not a valid value', 'value': 'bar'} */ + var tryCatch = _curry2(function _tryCatch(tryer, catcher) { - return _arity(tryer.length, function() { + return _arity(tryer.length, function () { try { return tryer.apply(this, arguments); } catch (e) { @@ -8816,8 +9835,9 @@ * R.unapply(JSON.stringify)(1, 2, 3); //=> '[1,2,3]' * @symb R.unapply(f)(a, b) = f([a, b]) */ + var unapply = _curry1(function unapply(fn) { - return function() { + return function () { return fn(Array.prototype.slice.call(arguments, 0)); }; }); @@ -8831,7 +9851,7 @@ * @memberOf R * @since v0.2.0 * @category Function - * @sig (* -> b) -> (a -> b) + * @sig (a -> b -> c -> ... -> z) -> (a -> z) * @param {Function} fn The function to wrap. * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of * arity 1. @@ -8850,22 +9870,26 @@ * takesOneArg(1, 2); //=> [1, undefined] * @symb R.unary(f)(a, b, c) = f(a) */ + var unary = _curry1(function unary(fn) { return nAry(1, fn); }); /** * Returns a function of arity `n` from a (manually) curried function. + * Note that, the returned function is actually a ramda style + * curryied function, which can accept one or more arguments in each + * function calling. * * @func * @memberOf R * @since v0.14.0 * @category Function - * @sig Number -> (a -> b) -> (a -> c) + * @sig Number -> (a -> b -> c ... -> z) -> ((a -> b -> c ...) -> z) * @param {Number} length The arity for the returned function. * @param {Function} fn The function to uncurry. * @return {Function} A new function. - * @see R.curry + * @see R.curry, R.curryN * @example * * const addFour = a => b => c => d => a + b + c + d; @@ -8873,18 +9897,21 @@ * const uncurriedAddFour = R.uncurryN(4, addFour); * uncurriedAddFour(1, 2, 3, 4); //=> 10 */ + var uncurryN = _curry2(function uncurryN(depth, fn) { - return curryN(depth, function() { + return curryN(depth, function () { var currentDepth = 1; var value = fn; var idx = 0; var endIdx; + while (currentDepth <= depth && typeof value === 'function') { endIdx = currentDepth === depth ? arguments.length : idx + value.length; value = value.apply(this, Array.prototype.slice.call(arguments, idx, endIdx)); currentDepth += 1; idx = endIdx; } + return value; }); }); @@ -8914,13 +9941,16 @@ * R.unfold(f, 10); //=> [-10, -20, -30, -40, -50] * @symb R.unfold(f, x) = [f(x)[0], f(f(x)[1])[0], f(f(f(x)[1])[1])[0], ...] */ + var unfold = _curry2(function unfold(fn, seed) { var pair = fn(seed); var result = []; + while (pair && pair.length) { result[result.length] = pair[0]; pair = fn(pair[1]); } + return result; }); @@ -8941,14 +9971,39 @@ * * R.union([1, 2, 3], [2, 3, 4]); //=> [1, 2, 3, 4] */ + var union = _curry2(compose(uniq, _concat)); + function XUniqWith(pred, xf) { + this.xf = xf; + this.pred = pred; + this.items = []; + } + + XUniqWith.prototype['@@transducer/init'] = _xfBase.init; + XUniqWith.prototype['@@transducer/result'] = _xfBase.result; + + XUniqWith.prototype['@@transducer/step'] = function (result, input) { + if (_includesWith(this.pred, input, this.items)) { + return result; + } else { + this.items.push(input); + return this.xf['@@transducer/step'](result, input); + } + }; + + var _xuniqWith = _curry2(function _xuniqWith(pred, xf) { + return new XUniqWith(pred, xf); + }); + /** * Returns a new list containing only one copy of each element in the original * list, based upon the value returned by applying the supplied predicate to * two list elements. Prefers the first item if two items compare equal based * on the predicate. * + * Acts as a transducer if a transformer is given in list position. + * * @func * @memberOf R * @since v0.2.0 @@ -8965,25 +10020,31 @@ * R.uniqWith(strEq)([1, '1', 1]); //=> [1] * R.uniqWith(strEq)(['1', 1, 1]); //=> ['1'] */ - var uniqWith = _curry2(function uniqWith(pred, list) { + + var uniqWith = _curry2(_dispatchable([], _xuniqWith, function (pred, list) { var idx = 0; var len = list.length; var result = []; var item; + while (idx < len) { item = list[idx]; + if (!_includesWith(pred, item, result)) { result[result.length] = item; } + idx += 1; } + return result; - }); + })); /** * Combines two lists into a set (i.e. no duplicates) composed of the elements * of each list. Duplication is determined according to the value returned by - * applying the supplied predicate to two list elements. + * applying the supplied predicate to two list elements. If an element exists + * in both lists, the first element from the first list will be used. * * @func * @memberOf R @@ -9002,6 +10063,7 @@ * const l2 = [{a: 1}, {a: 4}]; * R.unionWith(R.eqBy(R.prop('a')), l1, l2); //=> [{a: 1}, {a: 2}, {a: 4}] */ + var unionWith = _curry3(function unionWith(pred, list1, list2) { return uniqWith(pred, _concat(list1, list2)); }); @@ -9016,7 +10078,7 @@ * @memberOf R * @since v0.18.0 * @category Logic - * @sig (a -> Boolean) -> (a -> a) -> a -> a + * @sig (a -> Boolean) -> (a -> b) -> a -> a | b * @param {Function} pred A predicate function * @param {Function} whenFalseFn A function to invoke when the `pred` evaluates * to a falsy value. @@ -9030,6 +10092,7 @@ * safeInc(null); //=> null * safeInc(1); //=> 2 */ + var unless = _curry3(function unless(pred, whenFalseFn, x) { return pred(x) ? x : whenFalseFn(x); }); @@ -9051,6 +10114,7 @@ * R.unnest([1, [2], [[3]]]); //=> [1, 2, [3]] * R.unnest([[1, 2], [3, 4], [5, 6]]); //=> [1, 2, 3, 4, 5, 6] */ + var unnest = chain(_identity); /** @@ -9072,14 +10136,55 @@ * * R.until(R.gt(R.__, 100), R.multiply(2))(1) // => 128 */ + var until = _curry3(function until(pred, fn, init) { var val = init; + while (!pred(val)) { val = fn(val); } + return val; }); + /** + * + * Deconstructs an array field from the input documents to output a document for each element. + * Each output document is the input document with the value of the array field replaced by the element. + * + * @func + * @memberOf R + * @since v0.28.0 + * @category Object + * @sig String -> {k: [v]} -> [{k: v}] + * @param {String} key The key to determine which property of the object should be unwind + * @param {Object} object The object containing list under property named as key which is to unwind + * @return {List} A new list of object containing the value of input key having list replaced by each element in the object. + * @example + * + * R.unwind('hobbies', { + * name: 'alice', + * hobbies: ['Golf', 'Hacking'], + * colors: ['red', 'green'], + * }); + * // [ + * // { name: 'alice', hobbies: 'Golf', colors: ['red', 'green'] }, + * // { name: 'alice', hobbies: 'Hacking', colors: ['red', 'green'] } + * // ] + */ + + var unwind = _curry2(function (key, object) { + // If key is not in object or key is not as a list in object + if (!(key in object && _isArray(object[key]))) { + return [object]; + } // Map over object[key] which is a list and assoc each element with key + + + return _map(function (item) { + return _assoc(key, item, object); + }, object[key]); + }); + /** * Returns a list of all the properties, including prototype properties, of the * supplied object. @@ -9101,20 +10206,26 @@ * const f = new F(); * R.valuesIn(f); //=> ['X', 'Y'] */ + var valuesIn = _curry1(function valuesIn(obj) { var prop; var vs = []; + for (prop in obj) { vs[vs.length] = obj[prop]; } + return vs; }); - // `Const` is a functor that effectively ignores the function given to `map`. - var Const = function(x) { - return {value: x, 'fantasy-land/map': function() { return this; }}; + var Const = function Const(x) { + return { + value: x, + 'fantasy-land/map': function fantasyLandMap() { + return this; + } + }; }; - /** * Returns a "view" of the given data structure, determined by the given lens. * The lens's focus determines which portion of the data structure is visible. @@ -9128,7 +10239,7 @@ * @param {Lens} lens * @param {*} x * @return {*} - * @see R.prop, R.lensIndex, R.lensProp + * @see R.set, R.over, R.lens, R.lensIndex, R.lensProp, R.lensPath * @example * * const xLens = R.lensProp('x'); @@ -9136,6 +10247,8 @@ * R.view(xLens, {x: 1, y: 2}); //=> 1 * R.view(xLens, {x: 4, y: 2}); //=> 4 */ + + var view = _curry2(function view(lens, x) { // Using `Const` effectively ignores the setter function of the `lens`, // leaving the value returned by the getter function unmodified. @@ -9152,7 +10265,7 @@ * @memberOf R * @since v0.18.0 * @category Logic - * @sig (a -> Boolean) -> (a -> a) -> a -> a + * @sig (a -> Boolean) -> (a -> b) -> a -> a | b * @param {Function} pred A predicate function * @param {Function} whenTrueFn A function to invoke when the `condition` * evaluates to a truthy value. @@ -9170,6 +10283,7 @@ * truncate('12345'); //=> '12345' * truncate('0123456789ABC'); //=> '0123456789…' */ + var when = _curry3(function when(pred, whenTrueFn, x) { return pred(x) ? whenTrueFn(x) : x; }); @@ -9209,15 +10323,62 @@ * pred({a: 'foo', b: 'xxx', x: 10, y: 19}); //=> false * pred({a: 'foo', b: 'xxx', x: 11, y: 20}); //=> false */ + var where = _curry2(function where(spec, testObj) { for (var prop in spec) { if (_has(prop, spec) && !spec[prop](testObj[prop])) { return false; } } + return true; }); + /** + * Takes a spec object and a test object; each of the spec's own properties must be a predicate function. + * Each predicate is applied to the value of the corresponding property of the + * test object. `whereAny` returns true if at least one of the predicates return true, + * false otherwise. + * + * `whereAny` is well suited to declaratively expressing constraints for other + * functions such as [`filter`](#filter) and [`find`](#find). + * + * @func + * @memberOf R + * @since v0.28.0 + * @category Object + * @sig {String: (* -> Boolean)} -> {String: *} -> Boolean + * @param {Object} spec + * @param {Object} testObj + * @return {Boolean} + * @see R.propSatisfies, R.where + * @example + * + * // pred :: Object -> Boolean + * const pred = R.whereAny({ + * a: R.equals('foo'), + * b: R.complement(R.equals('xxx')), + * x: R.gt(R.__, 10), + * y: R.lt(R.__, 20) + * }); + * + * pred({a: 'foo', b: 'xxx', x: 8, y: 34}); //=> true + * pred({a: 'xxx', b: 'xxx', x: 9, y: 21}); //=> false + * pred({a: 'bar', b: 'xxx', x: 10, y: 20}); //=> false + * pred({a: 'foo', b: 'bar', x: 10, y: 20}); //=> true + * pred({a: 'foo', b: 'xxx', x: 11, y: 20}); //=> true + */ + + var whereAny = _curry2(function whereAny(spec, testObj) { + for (var prop in spec) { + if (_has(prop, spec) && spec[prop](testObj[prop])) { + return true; + } + } + + return false; + }); + /** * Takes a spec object and a test object; returns true if the test satisfies * the spec, false otherwise. An object satisfies the spec if, for each of the @@ -9246,6 +10407,7 @@ * pred({a: 1, b: 2, c: 3}); //=> true * pred({a: 1, b: 1}); //=> false */ + var whereEq = _curry2(function whereEq(spec, testObj) { return where(map(equals, spec), testObj); }); @@ -9269,7 +10431,8 @@ * * R.without([1, 2], [1, 2, 1, 3, 4]); //=> [3, 4] */ - var without = _curry2(function(xs, list) { + + var without = _curry2(function (xs, list) { return reject(flip(_includes)(xs), list); }); @@ -9294,6 +10457,7 @@ * R.xor(false, true); //=> true * R.xor(false, false); //=> false */ + var xor = _curry2(function xor(a, b) { return Boolean(!a ^ !b); }); @@ -9316,20 +10480,26 @@ * R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] * @symb R.xprod([a, b], [c, d]) = [[a, c], [a, d], [b, c], [b, d]] */ - var xprod = _curry2(function xprod(a, b) { // = xprodWith(prepend); (takes about 3 times as long...) + + var xprod = _curry2(function xprod(a, b) { + // = xprodWith(prepend); (takes about 3 times as long...) var idx = 0; var ilen = a.length; var j; var jlen = b.length; var result = []; + while (idx < ilen) { j = 0; + while (j < jlen) { result[result.length] = [a[idx], b[j]]; j += 1; } + idx += 1; } + return result; }); @@ -9352,14 +10522,17 @@ * R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']] * @symb R.zip([a, b, c], [d, e, f]) = [[a, d], [b, e], [c, f]] */ + var zip = _curry2(function zip(a, b) { var rv = []; var idx = 0; var len = Math.min(a.length, b.length); + while (idx < len) { rv[idx] = [a[idx], b[idx]]; idx += 1; } + return rv; }); @@ -9380,14 +10553,17 @@ * * R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3} */ + var zipObj = _curry2(function zipObj(keys, values) { var idx = 0; var len = Math.min(keys.length, values.length); var out = {}; + while (idx < len) { out[keys[idx]] = values[idx]; idx += 1; } + return out; }); @@ -9415,14 +10591,17 @@ * //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] * @symb R.zipWith(fn, [a, b, c], [d, e, f]) = [fn(a, d), fn(b, e), fn(c, f)] */ + var zipWith = _curry3(function zipWith(fn, a, b) { var rv = []; var idx = 0; var len = Math.min(a.length, b.length); + while (idx < len) { rv[idx] = fn(a[idx], b[idx]); idx += 1; } + return rv; }); @@ -9444,6 +10623,7 @@ * R.thunkify(R.identity)(42)(); //=> 42 * R.thunkify((a, b) => a + b)(25, 17)(); //=> 42 */ + var thunkify = _curry1(function thunkify(fn) { return curryN(fn.length, function createThunk() { var fnArgs = arguments; @@ -9463,6 +10643,7 @@ exports.allPass = allPass; exports.always = always; exports.and = and; + exports.andThen = andThen; exports.any = any; exports.anyPass = anyPass; exports.ap = ap; @@ -9481,18 +10662,17 @@ exports.chain = chain; exports.clamp = clamp; exports.clone = clone; + exports.collectBy = collectBy; exports.comparator = comparator; exports.complement = complement; exports.compose = compose; - exports.composeK = composeK; - exports.composeP = composeP; exports.composeWith = composeWith; exports.concat = concat; exports.cond = cond; exports.construct = construct; exports.constructN = constructN; - exports.contains = contains$1; exports.converge = converge; + exports.count = count; exports.countBy = countBy; exports.curry = curry; exports.curryN = curryN; @@ -9581,7 +10761,6 @@ exports.mean = mean; exports.median = median; exports.memoizeWith = memoizeWith; - exports.merge = merge; exports.mergeAll = mergeAll; exports.mergeDeepLeft = mergeDeepLeft; exports.mergeDeepRight = mergeDeepRight; @@ -9593,6 +10772,8 @@ exports.mergeWithKey = mergeWithKey; exports.min = min; exports.minBy = minBy; + exports.modify = modify; + exports.modifyPath = modifyPath; exports.modulo = modulo; exports.move = move; exports.multiply = multiply; @@ -9606,30 +10787,31 @@ exports.objOf = objOf; exports.of = of; exports.omit = omit; + exports.on = on; exports.once = once; exports.or = or; exports.otherwise = otherwise; exports.over = over; exports.pair = pair; exports.partial = partial; + exports.partialObject = partialObject; exports.partialRight = partialRight; exports.partition = partition; exports.path = path; - exports.paths = paths; exports.pathEq = pathEq; exports.pathOr = pathOr; exports.pathSatisfies = pathSatisfies; + exports.paths = paths; exports.pick = pick; exports.pickAll = pickAll; exports.pickBy = pickBy; exports.pipe = pipe; - exports.pipeK = pipeK; - exports.pipeP = pipeP; exports.pipeWith = pipeWith; exports.pluck = pluck; exports.prepend = prepend; exports.product = product; exports.project = project; + exports.promap = promap; exports.prop = prop; exports.propEq = propEq; exports.propIs = propIs; @@ -9658,6 +10840,7 @@ exports.splitAt = splitAt; exports.splitEvery = splitEvery; exports.splitWhen = splitWhen; + exports.splitWhenever = splitWhenever; exports.startsWith = startsWith; exports.subtract = subtract; exports.sum = sum; @@ -9670,7 +10853,7 @@ exports.takeWhile = takeWhile; exports.tap = tap; exports.test = test; - exports.andThen = andThen; + exports.thunkify = thunkify; exports.times = times; exports.toLower = toLower; exports.toPairs = toPairs; @@ -9695,6 +10878,7 @@ exports.unless = unless; exports.unnest = unnest; exports.until = until; + exports.unwind = unwind; exports.update = update; exports.useWith = useWith; exports.values = values; @@ -9702,6 +10886,7 @@ exports.view = view; exports.when = when; exports.where = where; + exports.whereAny = whereAny; exports.whereEq = whereEq; exports.without = without; exports.xor = xor; @@ -9709,8 +10894,7 @@ exports.zip = zip; exports.zipObj = zipObj; exports.zipWith = zipWith; - exports.thunkify = thunkify; Object.defineProperty(exports, '__esModule', { value: true }); -})); +}))); diff --git a/dist/ramda.min.js b/dist/ramda.min.js index b75c5e898..b6f32d53b 100644 --- a/dist/ramda.min.js +++ b/dist/ramda.min.js @@ -1 +1 @@ -!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((t=t||self).R={})}(this,function(t){"use strict";function a(t){return null!=t&&"object"==typeof t&&!0===t["@@functional/placeholder"]}function o(r){return function t(n){return 0===arguments.length||a(n)?t:r.apply(this,arguments)}}function n(e){return function t(n,r){switch(arguments.length){case 0:return t;case 1:return a(n)?t:o(function(t){return e(n,t)});default:return a(n)&&a(r)?t:a(n)?o(function(t){return e(t,r)}):a(r)?o(function(t){return e(n,t)}):e(n,r)}}}var r=n(function(t,n){return+t+ +n});function i(t,n){var r,e=(t=t||[]).length,u=(n=n||[]).length,i=[];for(r=0;r":ln(t,n)}function t(n,t){return x(function(t){return nn(t)+": "+u(n[t])},t.slice().sort())}switch(Object.prototype.toString.call(r)){case"[object Arguments]":return"(function() { return arguments; }("+x(u,r).join(", ")+"))";case"[object Array]":return"["+x(u,r).concat(t(r,sn(function(t){return/^\d+$/.test(t)},U(r)))).join(", ")+"]";case"[object Boolean]":return"object"==typeof r?"new Boolean("+u(r.valueOf())+")":""+r;case"[object Date]":return"new Date("+(isNaN(r.valueOf())?u(NaN):nn(en(r)))+")";case"[object Null]":return"null";case"[object Number]":return"object"==typeof r?"new Number("+u(r.valueOf())+")":1/r==-1/0?"-0":r.toString(10);case"[object String]":return"object"==typeof r?"new String("+u(r.valueOf())+")":nn(r);case"[object Undefined]":return"undefined";default:if("function"==typeof r.toString){var n=""+r;if("[object Object]"!=n)return n}return"{"+t(r,U(r)).join(", ")+"}"}}var pn=o(function(t){return ln(t,[])}),hn=n(function(t,n){if(p(t)){if(p(n))return t.concat(n);throw new TypeError(pn(n)+" is not an array")}if(w(t)){if(w(n))return t+n;throw new TypeError(pn(n)+" is not a string")}if(null!=t&&dt(t["fantasy-land/concat"]))return t["fantasy-land/concat"](n);if(null!=t&&dt(t.concat))return t.concat(n);throw new TypeError(pn(t)+' does not have a method named "concat" or "fantasy-land/concat"')}),yn=o(function(n){return f($(b,0,D(function(t){return t[0].length},n)),function(){for(var t=0;tt(n)?r:n}),pe=$(r,0),he=o(function(t){return pe(t)/t.length}),ye=o(function(t){var n=t.length;if(0===n)return NaN;var r=2-n%2,e=(n-r)/2;return he(Array.prototype.slice.call(t,0).sort(function(t,n){return t":an(t,n)}function t(n,t){return w(function(t){return Zt(t)+": "+u(n[t])},t.slice().sort())}switch(Object.prototype.toString.call(r)){case"[object Arguments]":return"(function() { return arguments; }("+w(u,r).join(", ")+"))";case"[object Array]":return"["+w(u,r).concat(t(r,cn(function(t){return/^\d+$/.test(t)},D(r)))).join(", ")+"]";case"[object Boolean]":return"object"===f(r)?"new Boolean("+u(r.valueOf())+")":""+r;case"[object Date]":return"new Date("+(isNaN(r.valueOf())?u(NaN):Zt(tn(r)))+")";case"[object Null]":return"null";case"[object Number]":return"object"===f(r)?"new Number("+u(r.valueOf())+")":1/r==-1/0?"-0":r.toString(10);case"[object String]":return"object"===f(r)?"new String("+u(r.valueOf())+")":Zt(r);case"[object Undefined]":return"undefined";default:if("function"==typeof r.toString){var n=""+r;if("[object Object]"!=n)return n}return"{"+t(r,D(r)).join(", ")+"}"}}var sn=o(function(t){return an(t,[])}),fn=n(function(t,n){if(h(t)){if(h(n))return t.concat(n);throw new TypeError(sn(n)+" is not an array")}if(j(t)){if(j(n))return t+n;throw new TypeError(sn(n)+" is not a string")}if(null!=t&&dt(t["fantasy-land/concat"]))return t["fantasy-land/concat"](n);if(null!=t&&dt(t.concat))return t.concat(n);throw new TypeError(sn(t)+' does not have a method named "concat" or "fantasy-land/concat"')}),ln=o(function(n){return s(K(x,0,z(function(t){return t[0].length},n)),function(){for(var t=0;tt(n)?r:n}),he=K(r,0),ye=o(function(t){return he(t)/t.length}),de=o(function(t){var n=t.length;if(0===n)return NaN;var r=2-n%2,e=(n-r)/2;return ye(Array.prototype.slice.call(t,0).sort(function(t,n){return t (b -> a) -> [b] -> [[b]] diff --git a/source/count.js b/source/count.js index 4b444b307..02a0978ca 100644 --- a/source/count.js +++ b/source/count.js @@ -7,6 +7,7 @@ import curry from './curry.js'; * * @func * @memberOf R + * @since v0.28.0 * @category List * @sig (a -> Boolean) -> [a] -> Number * @param {Function} predicate to match items against diff --git a/source/modify.js b/source/modify.js index 25ffd5530..b10e6efad 100644 --- a/source/modify.js +++ b/source/modify.js @@ -11,6 +11,7 @@ import modifyPath from './modifyPath.js'; * * @func * @memberOf R + * @since v0.28.0 * @category Object * @sig Idx -> (v -> v) -> {k: v} -> {k: v} * @param {String|Number} prop The property to be modified. diff --git a/source/modifyPath.js b/source/modifyPath.js index 4760e5644..698e3b6dd 100644 --- a/source/modifyPath.js +++ b/source/modifyPath.js @@ -16,6 +16,7 @@ import _modify from './internal/_modify.js'; * * @func * @memberOf R + * @since v0.28.0 * @category Object * @sig [Idx] -> (v -> v) -> {k: v} -> {k: v} * @param {Array} path The path to be modified. diff --git a/source/on.js b/source/on.js index 787d3e695..c89a54aa2 100644 --- a/source/on.js +++ b/source/on.js @@ -9,6 +9,7 @@ import curryN from './internal/_curryN.js'; * * @func * @memberOf R + * @since v0.28.0 * @category Function * @sig ((a, a) -> b) -> (c -> a) -> c -> c -> b * @param {Function} f a binary function diff --git a/source/partialObject.js b/source/partialObject.js index 85a448452..35d703329 100644 --- a/source/partialObject.js +++ b/source/partialObject.js @@ -8,6 +8,7 @@ import _curry2 from './internal/_curry2.js'; * * @func * @memberOf R + * @since v0.28.0 * @category Function * @sig (({ a, b, c, ..., n }) -> x) -> { a, b, c, ...} -> ({ d, e, f, ..., n } -> x) * @param {Function} f diff --git a/source/promap.js b/source/promap.js index 86805e7c4..cd055d0e0 100644 --- a/source/promap.js +++ b/source/promap.js @@ -15,6 +15,7 @@ import _xpromap from './internal/_xpromap.js'; * * @func * @memberOf R + * @since v0.28.0 * @category Function * @sig (a -> b) -> (c -> d) -> (b -> c) -> (a -> d) * @sig Profunctor p => (a -> b) -> (c -> d) -> p b c -> p a d diff --git a/source/unwind.js b/source/unwind.js index 46ef62da4..b593f2f06 100644 --- a/source/unwind.js +++ b/source/unwind.js @@ -10,6 +10,7 @@ import _assoc from './internal/_assoc.js'; * * @func * @memberOf R + * @since v0.28.0 * @category Object * @sig String -> {k: [v]} -> [{k: v}] * @param {String} key The key to determine which property of the object should be unwind diff --git a/source/whereAny.js b/source/whereAny.js index 7002299fe..0297ec1b8 100644 --- a/source/whereAny.js +++ b/source/whereAny.js @@ -13,6 +13,7 @@ import _has from './internal/_has.js'; * * @func * @memberOf R + * @since v0.28.0 * @category Object * @sig {String: (* -> Boolean)} -> {String: *} -> Boolean * @param {Object} spec