You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

9716 lines
301 KiB

4 years ago
  1. // Ramda v0.27.1
  2. // https://github.com/ramda/ramda
  3. // (c) 2013-2020 Scott Sauyet, Michael Hurley, and David Chambers
  4. // Ramda may be freely distributed under the MIT license.
  5. (function (global, factory) {
  6. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  7. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  8. (global = global || self, factory(global.R = {}));
  9. }(this, function (exports) { 'use strict';
  10. /**
  11. * A function that always returns `false`. Any passed in parameters are ignored.
  12. *
  13. * @func
  14. * @memberOf R
  15. * @since v0.9.0
  16. * @category Function
  17. * @sig * -> Boolean
  18. * @param {*}
  19. * @return {Boolean}
  20. * @see R.T
  21. * @example
  22. *
  23. * R.F(); //=> false
  24. */
  25. var F = function() {return false;};
  26. /**
  27. * A function that always returns `true`. Any passed in parameters are ignored.
  28. *
  29. * @func
  30. * @memberOf R
  31. * @since v0.9.0
  32. * @category Function
  33. * @sig * -> Boolean
  34. * @param {*}
  35. * @return {Boolean}
  36. * @see R.F
  37. * @example
  38. *
  39. * R.T(); //=> true
  40. */
  41. var T = function() {return true;};
  42. /**
  43. * A special placeholder value used to specify "gaps" within curried functions,
  44. * allowing partial application of any combination of arguments, regardless of
  45. * their positions.
  46. *
  47. * If `g` is a curried ternary function and `_` is `R.__`, the following are
  48. * equivalent:
  49. *
  50. * - `g(1, 2, 3)`
  51. * - `g(_, 2, 3)(1)`
  52. * - `g(_, _, 3)(1)(2)`
  53. * - `g(_, _, 3)(1, 2)`
  54. * - `g(_, 2, _)(1, 3)`
  55. * - `g(_, 2)(1)(3)`
  56. * - `g(_, 2)(1, 3)`
  57. * - `g(_, 2)(_, 3)(1)`
  58. *
  59. * @name __
  60. * @constant
  61. * @memberOf R
  62. * @since v0.6.0
  63. * @category Function
  64. * @example
  65. *
  66. * const greet = R.replace('{name}', R.__, 'Hello, {name}!');
  67. * greet('Alice'); //=> 'Hello, Alice!'
  68. */
  69. var __ = {'@@functional/placeholder': true};
  70. function _isPlaceholder(a) {
  71. return a != null &&
  72. typeof a === 'object' &&
  73. a['@@functional/placeholder'] === true;
  74. }
  75. /**
  76. * Optimized internal one-arity curry function.
  77. *
  78. * @private
  79. * @category Function
  80. * @param {Function} fn The function to curry.
  81. * @return {Function} The curried function.
  82. */
  83. function _curry1(fn) {
  84. return function f1(a) {
  85. if (arguments.length === 0 || _isPlaceholder(a)) {
  86. return f1;
  87. } else {
  88. return fn.apply(this, arguments);
  89. }
  90. };
  91. }
  92. /**
  93. * Optimized internal two-arity curry function.
  94. *
  95. * @private
  96. * @category Function
  97. * @param {Function} fn The function to curry.
  98. * @return {Function} The curried function.
  99. */
  100. function _curry2(fn) {
  101. return function f2(a, b) {
  102. switch (arguments.length) {
  103. case 0:
  104. return f2;
  105. case 1:
  106. return _isPlaceholder(a)
  107. ? f2
  108. : _curry1(function(_b) { return fn(a, _b); });
  109. default:
  110. return _isPlaceholder(a) && _isPlaceholder(b)
  111. ? f2
  112. : _isPlaceholder(a)
  113. ? _curry1(function(_a) { return fn(_a, b); })
  114. : _isPlaceholder(b)
  115. ? _curry1(function(_b) { return fn(a, _b); })
  116. : fn(a, b);
  117. }
  118. };
  119. }
  120. /**
  121. * Adds two values.
  122. *
  123. * @func
  124. * @memberOf R
  125. * @since v0.1.0
  126. * @category Math
  127. * @sig Number -> Number -> Number
  128. * @param {Number} a
  129. * @param {Number} b
  130. * @return {Number}
  131. * @see R.subtract
  132. * @example
  133. *
  134. * R.add(2, 3); //=> 5
  135. * R.add(7)(10); //=> 17
  136. */
  137. var add = _curry2(function add(a, b) {
  138. return Number(a) + Number(b);
  139. });
  140. /**
  141. * Private `concat` function to merge two array-like objects.
  142. *
  143. * @private
  144. * @param {Array|Arguments} [set1=[]] An array-like object.
  145. * @param {Array|Arguments} [set2=[]] An array-like object.
  146. * @return {Array} A new, merged array.
  147. * @example
  148. *
  149. * _concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]
  150. */
  151. function _concat(set1, set2) {
  152. set1 = set1 || [];
  153. set2 = set2 || [];
  154. var idx;
  155. var len1 = set1.length;
  156. var len2 = set2.length;
  157. var result = [];
  158. idx = 0;
  159. while (idx < len1) {
  160. result[result.length] = set1[idx];
  161. idx += 1;
  162. }
  163. idx = 0;
  164. while (idx < len2) {
  165. result[result.length] = set2[idx];
  166. idx += 1;
  167. }
  168. return result;
  169. }
  170. function _arity(n, fn) {
  171. /* eslint-disable no-unused-vars */
  172. switch (n) {
  173. case 0: return function() { return fn.apply(this, arguments); };
  174. case 1: return function(a0) { return fn.apply(this, arguments); };
  175. case 2: return function(a0, a1) { return fn.apply(this, arguments); };
  176. case 3: return function(a0, a1, a2) { return fn.apply(this, arguments); };
  177. case 4: return function(a0, a1, a2, a3) { return fn.apply(this, arguments); };
  178. case 5: return function(a0, a1, a2, a3, a4) { return fn.apply(this, arguments); };
  179. case 6: return function(a0, a1, a2, a3, a4, a5) { return fn.apply(this, arguments); };
  180. case 7: return function(a0, a1, a2, a3, a4, a5, a6) { return fn.apply(this, arguments); };
  181. case 8: return function(a0, a1, a2, a3, a4, a5, a6, a7) { return fn.apply(this, arguments); };
  182. case 9: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8) { return fn.apply(this, arguments); };
  183. case 10: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { return fn.apply(this, arguments); };
  184. default: throw new Error('First argument to _arity must be a non-negative integer no greater than ten');
  185. }
  186. }
  187. /**
  188. * Internal curryN function.
  189. *
  190. * @private
  191. * @category Function
  192. * @param {Number} length The arity of the curried function.
  193. * @param {Array} received An array of arguments received thus far.
  194. * @param {Function} fn The function to curry.
  195. * @return {Function} The curried function.
  196. */
  197. function _curryN(length, received, fn) {
  198. return function() {
  199. var combined = [];
  200. var argsIdx = 0;
  201. var left = length;
  202. var combinedIdx = 0;
  203. while (combinedIdx < received.length || argsIdx < arguments.length) {
  204. var result;
  205. if (combinedIdx < received.length &&
  206. (!_isPlaceholder(received[combinedIdx]) ||
  207. argsIdx >= arguments.length)) {
  208. result = received[combinedIdx];
  209. } else {
  210. result = arguments[argsIdx];
  211. argsIdx += 1;
  212. }
  213. combined[combinedIdx] = result;
  214. if (!_isPlaceholder(result)) {
  215. left -= 1;
  216. }
  217. combinedIdx += 1;
  218. }
  219. return left <= 0
  220. ? fn.apply(this, combined)
  221. : _arity(left, _curryN(length, combined, fn));
  222. };
  223. }
  224. /**
  225. * Returns a curried equivalent of the provided function, with the specified
  226. * arity. The curried function has two unusual capabilities. First, its
  227. * arguments needn't be provided one at a time. If `g` is `R.curryN(3, f)`, the
  228. * following are equivalent:
  229. *
  230. * - `g(1)(2)(3)`
  231. * - `g(1)(2, 3)`
  232. * - `g(1, 2)(3)`
  233. * - `g(1, 2, 3)`
  234. *
  235. * Secondly, the special placeholder value [`R.__`](#__) may be used to specify
  236. * "gaps", allowing partial application of any combination of arguments,
  237. * regardless of their positions. If `g` is as above and `_` is [`R.__`](#__),
  238. * the following are equivalent:
  239. *
  240. * - `g(1, 2, 3)`
  241. * - `g(_, 2, 3)(1)`
  242. * - `g(_, _, 3)(1)(2)`
  243. * - `g(_, _, 3)(1, 2)`
  244. * - `g(_, 2)(1)(3)`
  245. * - `g(_, 2)(1, 3)`
  246. * - `g(_, 2)(_, 3)(1)`
  247. *
  248. * @func
  249. * @memberOf R
  250. * @since v0.5.0
  251. * @category Function
  252. * @sig Number -> (* -> a) -> (* -> a)
  253. * @param {Number} length The arity for the returned function.
  254. * @param {Function} fn The function to curry.
  255. * @return {Function} A new, curried function.
  256. * @see R.curry
  257. * @example
  258. *
  259. * const sumArgs = (...args) => R.sum(args);
  260. *
  261. * const curriedAddFourNumbers = R.curryN(4, sumArgs);
  262. * const f = curriedAddFourNumbers(1, 2);
  263. * const g = f(3);
  264. * g(4); //=> 10
  265. */
  266. var curryN = _curry2(function curryN(length, fn) {
  267. if (length === 1) {
  268. return _curry1(fn);
  269. }
  270. return _arity(length, _curryN(length, [], fn));
  271. });
  272. /**
  273. * Creates a new list iteration function from an existing one by adding two new
  274. * parameters to its callback function: the current index, and the entire list.
  275. *
  276. * This would turn, for instance, [`R.map`](#map) function into one that
  277. * more closely resembles `Array.prototype.map`. Note that this will only work
  278. * for functions in which the iteration callback function is the first
  279. * parameter, and where the list is the last parameter. (This latter might be
  280. * unimportant if the list parameter is not used.)
  281. *
  282. * @func
  283. * @memberOf R
  284. * @since v0.15.0
  285. * @category Function
  286. * @category List
  287. * @sig ((a ... -> b) ... -> [a] -> *) -> ((a ..., Int, [a] -> b) ... -> [a] -> *)
  288. * @param {Function} fn A list iteration function that does not pass index or list to its callback
  289. * @return {Function} An altered list iteration function that passes (item, index, list) to its callback
  290. * @example
  291. *
  292. * const mapIndexed = R.addIndex(R.map);
  293. * mapIndexed((val, idx) => idx + '-' + val, ['f', 'o', 'o', 'b', 'a', 'r']);
  294. * //=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r']
  295. */
  296. var addIndex = _curry1(function addIndex(fn) {
  297. return curryN(fn.length, function() {
  298. var idx = 0;
  299. var origFn = arguments[0];
  300. var list = arguments[arguments.length - 1];
  301. var args = Array.prototype.slice.call(arguments, 0);
  302. args[0] = function() {
  303. var result = origFn.apply(this, _concat(arguments, [idx, list]));
  304. idx += 1;
  305. return result;
  306. };
  307. return fn.apply(this, args);
  308. });
  309. });
  310. /**
  311. * Optimized internal three-arity curry function.
  312. *
  313. * @private
  314. * @category Function
  315. * @param {Function} fn The function to curry.
  316. * @return {Function} The curried function.
  317. */
  318. function _curry3(fn) {
  319. return function f3(a, b, c) {
  320. switch (arguments.length) {
  321. case 0:
  322. return f3;
  323. case 1:
  324. return _isPlaceholder(a)
  325. ? f3
  326. : _curry2(function(_b, _c) { return fn(a, _b, _c); });
  327. case 2:
  328. return _isPlaceholder(a) && _isPlaceholder(b)
  329. ? f3
  330. : _isPlaceholder(a)
  331. ? _curry2(function(_a, _c) { return fn(_a, b, _c); })
  332. : _isPlaceholder(b)
  333. ? _curry2(function(_b, _c) { return fn(a, _b, _c); })
  334. : _curry1(function(_c) { return fn(a, b, _c); });
  335. default:
  336. return _isPlaceholder(a) && _isPlaceholder(b) && _isPlaceholder(c)
  337. ? f3
  338. : _isPlaceholder(a) && _isPlaceholder(b)
  339. ? _curry2(function(_a, _b) { return fn(_a, _b, c); })
  340. : _isPlaceholder(a) && _isPlaceholder(c)
  341. ? _curry2(function(_a, _c) { return fn(_a, b, _c); })
  342. : _isPlaceholder(b) && _isPlaceholder(c)
  343. ? _curry2(function(_b, _c) { return fn(a, _b, _c); })
  344. : _isPlaceholder(a)
  345. ? _curry1(function(_a) { return fn(_a, b, c); })
  346. : _isPlaceholder(b)
  347. ? _curry1(function(_b) { return fn(a, _b, c); })
  348. : _isPlaceholder(c)
  349. ? _curry1(function(_c) { return fn(a, b, _c); })
  350. : fn(a, b, c);
  351. }
  352. };
  353. }
  354. /**
  355. * Applies a function to the value at the given index of an array, returning a
  356. * new copy of the array with the element at the given index replaced with the
  357. * result of the function application.
  358. *
  359. * @func
  360. * @memberOf R
  361. * @since v0.14.0
  362. * @category List
  363. * @sig Number -> (a -> a) -> [a] -> [a]
  364. * @param {Number} idx The index.
  365. * @param {Function} fn The function to apply.
  366. * @param {Array|Arguments} list An array-like object whose value
  367. * at the supplied index will be replaced.
  368. * @return {Array} A copy of the supplied array-like object with
  369. * the element at index `idx` replaced with the value
  370. * returned by applying `fn` to the existing element.
  371. * @see R.update
  372. * @example
  373. *
  374. * R.adjust(1, R.toUpper, ['a', 'b', 'c', 'd']); //=> ['a', 'B', 'c', 'd']
  375. * R.adjust(-1, R.toUpper, ['a', 'b', 'c', 'd']); //=> ['a', 'b', 'c', 'D']
  376. * @symb R.adjust(-1, f, [a, b]) = [a, f(b)]
  377. * @symb R.adjust(0, f, [a, b]) = [f(a), b]
  378. */
  379. var adjust = _curry3(function adjust(idx, fn, list) {
  380. if (idx >= list.length || idx < -list.length) {
  381. return list;
  382. }
  383. var start = idx < 0 ? list.length : 0;
  384. var _idx = start + idx;
  385. var _list = _concat(list);
  386. _list[_idx] = fn(list[_idx]);
  387. return _list;
  388. });
  389. /**
  390. * Tests whether or not an object is an array.
  391. *
  392. * @private
  393. * @param {*} val The object to test.
  394. * @return {Boolean} `true` if `val` is an array, `false` otherwise.
  395. * @example
  396. *
  397. * _isArray([]); //=> true
  398. * _isArray(null); //=> false
  399. * _isArray({}); //=> false
  400. */
  401. var _isArray = Array.isArray || function _isArray(val) {
  402. return (val != null &&
  403. val.length >= 0 &&
  404. Object.prototype.toString.call(val) === '[object Array]');
  405. };
  406. function _isTransformer(obj) {
  407. return obj != null && typeof obj['@@transducer/step'] === 'function';
  408. }
  409. /**
  410. * Returns a function that dispatches with different strategies based on the
  411. * object in list position (last argument). If it is an array, executes [fn].
  412. * Otherwise, if it has a function with one of the given method names, it will
  413. * execute that function (functor case). Otherwise, if it is a transformer,
  414. * uses transducer [xf] to return a new transformer (transducer case).
  415. * Otherwise, it will default to executing [fn].
  416. *
  417. * @private
  418. * @param {Array} methodNames properties to check for a custom implementation
  419. * @param {Function} xf transducer to initialize if object is transformer
  420. * @param {Function} fn default ramda implementation
  421. * @return {Function} A function that dispatches on object in list position
  422. */
  423. function _dispatchable(methodNames, xf, fn) {
  424. return function() {
  425. if (arguments.length === 0) {
  426. return fn();
  427. }
  428. var args = Array.prototype.slice.call(arguments, 0);
  429. var obj = args.pop();
  430. if (!_isArray(obj)) {
  431. var idx = 0;
  432. while (idx < methodNames.length) {
  433. if (typeof obj[methodNames[idx]] === 'function') {
  434. return obj[methodNames[idx]].apply(obj, args);
  435. }
  436. idx += 1;
  437. }
  438. if (_isTransformer(obj)) {
  439. var transducer = xf.apply(null, args);
  440. return transducer(obj);
  441. }
  442. }
  443. return fn.apply(this, arguments);
  444. };
  445. }
  446. function _reduced(x) {
  447. return x && x['@@transducer/reduced'] ? x :
  448. {
  449. '@@transducer/value': x,
  450. '@@transducer/reduced': true
  451. };
  452. }
  453. var _xfBase = {
  454. init: function() {
  455. return this.xf['@@transducer/init']();
  456. },
  457. result: function(result) {
  458. return this.xf['@@transducer/result'](result);
  459. }
  460. };
  461. function XAll(f, xf) {
  462. this.xf = xf;
  463. this.f = f;
  464. this.all = true;
  465. }
  466. XAll.prototype['@@transducer/init'] = _xfBase.init;
  467. XAll.prototype['@@transducer/result'] = function(result) {
  468. if (this.all) {
  469. result = this.xf['@@transducer/step'](result, true);
  470. }
  471. return this.xf['@@transducer/result'](result);
  472. };
  473. XAll.prototype['@@transducer/step'] = function(result, input) {
  474. if (!this.f(input)) {
  475. this.all = false;
  476. result = _reduced(this.xf['@@transducer/step'](result, false));
  477. }
  478. return result;
  479. };
  480. var _xall = _curry2(function _xall(f, xf) { return new XAll(f, xf); });
  481. /**
  482. * Returns `true` if all elements of the list match the predicate, `false` if
  483. * there are any that don't.
  484. *
  485. * Dispatches to the `all` method of the second argument, if present.
  486. *
  487. * Acts as a transducer if a transformer is given in list position.
  488. *
  489. * @func
  490. * @memberOf R
  491. * @since v0.1.0
  492. * @category List
  493. * @sig (a -> Boolean) -> [a] -> Boolean
  494. * @param {Function} fn The predicate function.
  495. * @param {Array} list The array to consider.
  496. * @return {Boolean} `true` if the predicate is satisfied by every element, `false`
  497. * otherwise.
  498. * @see R.any, R.none, R.transduce
  499. * @example
  500. *
  501. * const equals3 = R.equals(3);
  502. * R.all(equals3)([3, 3, 3, 3]); //=> true
  503. * R.all(equals3)([3, 3, 1, 3]); //=> false
  504. */
  505. var all = _curry2(_dispatchable(['all'], _xall, function all(fn, list) {
  506. var idx = 0;
  507. while (idx < list.length) {
  508. if (!fn(list[idx])) {
  509. return false;
  510. }
  511. idx += 1;
  512. }
  513. return true;
  514. }));
  515. /**
  516. * Returns the larger of its two arguments.
  517. *
  518. * @func
  519. * @memberOf R
  520. * @since v0.1.0
  521. * @category Relation
  522. * @sig Ord a => a -> a -> a
  523. * @param {*} a
  524. * @param {*} b
  525. * @return {*}
  526. * @see R.maxBy, R.min
  527. * @example
  528. *
  529. * R.max(789, 123); //=> 789
  530. * R.max('a', 'b'); //=> 'b'
  531. */
  532. var max = _curry2(function max(a, b) { return b > a ? b : a; });
  533. function _map(fn, functor) {
  534. var idx = 0;
  535. var len = functor.length;
  536. var result = Array(len);
  537. while (idx < len) {
  538. result[idx] = fn(functor[idx]);
  539. idx += 1;
  540. }
  541. return result;
  542. }
  543. function _isString(x) {
  544. return Object.prototype.toString.call(x) === '[object String]';
  545. }
  546. /**
  547. * Tests whether or not an object is similar to an array.
  548. *
  549. * @private
  550. * @category Type
  551. * @category List
  552. * @sig * -> Boolean
  553. * @param {*} x The object to test.
  554. * @return {Boolean} `true` if `x` has a numeric length property and extreme indices defined; `false` otherwise.
  555. * @example
  556. *
  557. * _isArrayLike([]); //=> true
  558. * _isArrayLike(true); //=> false
  559. * _isArrayLike({}); //=> false
  560. * _isArrayLike({length: 10}); //=> false
  561. * _isArrayLike({0: 'zero', 9: 'nine', length: 10}); //=> true
  562. */
  563. var _isArrayLike = _curry1(function isArrayLike(x) {
  564. if (_isArray(x)) { return true; }
  565. if (!x) { return false; }
  566. if (typeof x !== 'object') { return false; }
  567. if (_isString(x)) { return false; }
  568. if (x.nodeType === 1) { return !!x.length; }
  569. if (x.length === 0) { return true; }
  570. if (x.length > 0) {
  571. return x.hasOwnProperty(0) && x.hasOwnProperty(x.length - 1);
  572. }
  573. return false;
  574. });
  575. function XWrap(fn) {
  576. this.f = fn;
  577. }
  578. XWrap.prototype['@@transducer/init'] = function() {
  579. throw new Error('init not implemented on XWrap');
  580. };
  581. XWrap.prototype['@@transducer/result'] = function(acc) { return acc; };
  582. XWrap.prototype['@@transducer/step'] = function(acc, x) {
  583. return this.f(acc, x);
  584. };
  585. function _xwrap(fn) { return new XWrap(fn); }
  586. /**
  587. * Creates a function that is bound to a context.
  588. * Note: `R.bind` does not provide the additional argument-binding capabilities of
  589. * [Function.prototype.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
  590. *
  591. * @func
  592. * @memberOf R
  593. * @since v0.6.0
  594. * @category Function
  595. * @category Object
  596. * @sig (* -> *) -> {*} -> (* -> *)
  597. * @param {Function} fn The function to bind to context
  598. * @param {Object} thisObj The context to bind `fn` to
  599. * @return {Function} A function that will execute in the context of `thisObj`.
  600. * @see R.partial
  601. * @example
  602. *
  603. * const log = R.bind(console.log, console);
  604. * R.pipe(R.assoc('a', 2), R.tap(log), R.assoc('a', 3))({a: 1}); //=> {a: 3}
  605. * // logs {a: 2}
  606. * @symb R.bind(f, o)(a, b) = f.call(o, a, b)
  607. */
  608. var bind = _curry2(function bind(fn, thisObj) {
  609. return _arity(fn.length, function() {
  610. return fn.apply(thisObj, arguments);
  611. });
  612. });
  613. function _arrayReduce(xf, acc, list) {
  614. var idx = 0;
  615. var len = list.length;
  616. while (idx < len) {
  617. acc = xf['@@transducer/step'](acc, list[idx]);
  618. if (acc && acc['@@transducer/reduced']) {
  619. acc = acc['@@transducer/value'];
  620. break;
  621. }
  622. idx += 1;
  623. }
  624. return xf['@@transducer/result'](acc);
  625. }
  626. function _iterableReduce(xf, acc, iter) {
  627. var step = iter.next();
  628. while (!step.done) {
  629. acc = xf['@@transducer/step'](acc, step.value);
  630. if (acc && acc['@@transducer/reduced']) {
  631. acc = acc['@@transducer/value'];
  632. break;
  633. }
  634. step = iter.next();
  635. }
  636. return xf['@@transducer/result'](acc);
  637. }
  638. function _methodReduce(xf, acc, obj, methodName) {
  639. return xf['@@transducer/result'](obj[methodName](bind(xf['@@transducer/step'], xf), acc));
  640. }
  641. var symIterator = (typeof Symbol !== 'undefined') ? Symbol.iterator : '@@iterator';
  642. function _reduce(fn, acc, list) {
  643. if (typeof fn === 'function') {
  644. fn = _xwrap(fn);
  645. }
  646. if (_isArrayLike(list)) {
  647. return _arrayReduce(fn, acc, list);
  648. }
  649. if (typeof list['fantasy-land/reduce'] === 'function') {
  650. return _methodReduce(fn, acc, list, 'fantasy-land/reduce');
  651. }
  652. if (list[symIterator] != null) {
  653. return _iterableReduce(fn, acc, list[symIterator]());
  654. }
  655. if (typeof list.next === 'function') {
  656. return _iterableReduce(fn, acc, list);
  657. }
  658. if (typeof list.reduce === 'function') {
  659. return _methodReduce(fn, acc, list, 'reduce');
  660. }
  661. throw new TypeError('reduce: list must be array or iterable');
  662. }
  663. function XMap(f, xf) {
  664. this.xf = xf;
  665. this.f = f;
  666. }
  667. XMap.prototype['@@transducer/init'] = _xfBase.init;
  668. XMap.prototype['@@transducer/result'] = _xfBase.result;
  669. XMap.prototype['@@transducer/step'] = function(result, input) {
  670. return this.xf['@@transducer/step'](result, this.f(input));
  671. };
  672. var _xmap = _curry2(function _xmap(f, xf) { return new XMap(f, xf); });
  673. function _has(prop, obj) {
  674. return Object.prototype.hasOwnProperty.call(obj, prop);
  675. }
  676. var toString = Object.prototype.toString;
  677. var _isArguments = (function() {
  678. return toString.call(arguments) === '[object Arguments]' ?
  679. function _isArguments(x) { return toString.call(x) === '[object Arguments]'; } :
  680. function _isArguments(x) { return _has('callee', x); };
  681. }());
  682. // cover IE < 9 keys issues
  683. var hasEnumBug = !({toString: null}).propertyIsEnumerable('toString');
  684. var nonEnumerableProps = [
  685. 'constructor', 'valueOf', 'isPrototypeOf', 'toString',
  686. 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'
  687. ];
  688. // Safari bug
  689. var hasArgsEnumBug = (function() {
  690. return arguments.propertyIsEnumerable('length');
  691. }());
  692. var contains = function contains(list, item) {
  693. var idx = 0;
  694. while (idx < list.length) {
  695. if (list[idx] === item) {
  696. return true;
  697. }
  698. idx += 1;
  699. }
  700. return false;
  701. };
  702. /**
  703. * Returns a list containing the names of all the enumerable own properties of
  704. * the supplied object.
  705. * Note that the order of the output array is not guaranteed to be consistent
  706. * across different JS platforms.
  707. *
  708. * @func
  709. * @memberOf R
  710. * @since v0.1.0
  711. * @category Object
  712. * @sig {k: v} -> [k]
  713. * @param {Object} obj The object to extract properties from
  714. * @return {Array} An array of the object's own properties.
  715. * @see R.keysIn, R.values
  716. * @example
  717. *
  718. * R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c']
  719. */
  720. var keys = typeof Object.keys === 'function' && !hasArgsEnumBug ?
  721. _curry1(function keys(obj) {
  722. return Object(obj) !== obj ? [] : Object.keys(obj);
  723. }) :
  724. _curry1(function keys(obj) {
  725. if (Object(obj) !== obj) {
  726. return [];
  727. }
  728. var prop, nIdx;
  729. var ks = [];
  730. var checkArgsLength = hasArgsEnumBug && _isArguments(obj);
  731. for (prop in obj) {
  732. if (_has(prop, obj) && (!checkArgsLength || prop !== 'length')) {
  733. ks[ks.length] = prop;
  734. }
  735. }
  736. if (hasEnumBug) {
  737. nIdx = nonEnumerableProps.length - 1;
  738. while (nIdx >= 0) {
  739. prop = nonEnumerableProps[nIdx];
  740. if (_has(prop, obj) && !contains(ks, prop)) {
  741. ks[ks.length] = prop;
  742. }
  743. nIdx -= 1;
  744. }
  745. }
  746. return ks;
  747. });
  748. /**
  749. * Takes a function and
  750. * a [functor](https://github.com/fantasyland/fantasy-land#functor),
  751. * applies the function to each of the functor's values, and returns
  752. * a functor of the same shape.
  753. *
  754. * Ramda provides suitable `map` implementations for `Array` and `Object`,
  755. * so this function may be applied to `[1, 2, 3]` or `{x: 1, y: 2, z: 3}`.
  756. *
  757. * Dispatches to the `map` method of the second argument, if present.
  758. *
  759. * Acts as a transducer if a transformer is given in list position.
  760. *
  761. * Also treats functions as functors and will compose them together.
  762. *
  763. * @func
  764. * @memberOf R
  765. * @since v0.1.0
  766. * @category List
  767. * @sig Functor f => (a -> b) -> f a -> f b
  768. * @param {Function} fn The function to be called on every element of the input `list`.
  769. * @param {Array} list The list to be iterated over.
  770. * @return {Array} The new list.
  771. * @see R.transduce, R.addIndex
  772. * @example
  773. *
  774. * const double = x => x * 2;
  775. *
  776. * R.map(double, [1, 2, 3]); //=> [2, 4, 6]
  777. *
  778. * R.map(double, {x: 1, y: 2, z: 3}); //=> {x: 2, y: 4, z: 6}
  779. * @symb R.map(f, [a, b]) = [f(a), f(b)]
  780. * @symb R.map(f, { x: a, y: b }) = { x: f(a), y: f(b) }
  781. * @symb R.map(f, functor_o) = functor_o.map(f)
  782. */
  783. var map = _curry2(_dispatchable(['fantasy-land/map', 'map'], _xmap, function map(fn, functor) {
  784. switch (Object.prototype.toString.call(functor)) {
  785. case '[object Function]':
  786. return curryN(functor.length, function() {
  787. return fn.call(this, functor.apply(this, arguments));
  788. });
  789. case '[object Object]':
  790. return _reduce(function(acc, key) {
  791. acc[key] = fn(functor[key]);
  792. return acc;
  793. }, {}, keys(functor));
  794. default:
  795. return _map(fn, functor);
  796. }
  797. }));
  798. /**
  799. * Determine if the passed argument is an integer.
  800. *
  801. * @private
  802. * @param {*} n
  803. * @category Type
  804. * @return {Boolean}
  805. */
  806. var _isInteger = Number.isInteger || function _isInteger(n) {
  807. return (n << 0) === n;
  808. };
  809. /**
  810. * Returns the nth element of the given list or string. If n is negative the
  811. * element at index length + n is returned.
  812. *
  813. * @func
  814. * @memberOf R
  815. * @since v0.1.0
  816. * @category List
  817. * @sig Number -> [a] -> a | Undefined
  818. * @sig Number -> String -> String
  819. * @param {Number} offset
  820. * @param {*} list
  821. * @return {*}
  822. * @example
  823. *
  824. * const list = ['foo', 'bar', 'baz', 'quux'];
  825. * R.nth(1, list); //=> 'bar'
  826. * R.nth(-1, list); //=> 'quux'
  827. * R.nth(-99, list); //=> undefined
  828. *
  829. * R.nth(2, 'abc'); //=> 'c'
  830. * R.nth(3, 'abc'); //=> ''
  831. * @symb R.nth(-1, [a, b, c]) = c
  832. * @symb R.nth(0, [a, b, c]) = a
  833. * @symb R.nth(1, [a, b, c]) = b
  834. */
  835. var nth = _curry2(function nth(offset, list) {
  836. var idx = offset < 0 ? list.length + offset : offset;
  837. return _isString(list) ? list.charAt(idx) : list[idx];
  838. });
  839. /**
  840. * Retrieves the values at given paths of an object.
  841. *
  842. * @func
  843. * @memberOf R
  844. * @since v0.27.1
  845. * @category Object
  846. * @typedefn Idx = [String | Int]
  847. * @sig [Idx] -> {a} -> [a | Undefined]
  848. * @param {Array} pathsArray The array of paths to be fetched.
  849. * @param {Object} obj The object to retrieve the nested properties from.
  850. * @return {Array} A list consisting of values at paths specified by "pathsArray".
  851. * @see R.path
  852. * @example
  853. *
  854. * R.paths([['a', 'b'], ['p', 0, 'q']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, 3]
  855. * R.paths([['a', 'b'], ['p', 'r']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, undefined]
  856. */
  857. var paths = _curry2(function paths(pathsArray, obj) {
  858. return pathsArray.map(function(paths) {
  859. var val = obj;
  860. var idx = 0;
  861. var p;
  862. while (idx < paths.length) {
  863. if (val == null) {
  864. return;
  865. }
  866. p = paths[idx];
  867. val = _isInteger(p) ? nth(p, val) : val[p];
  868. idx += 1;
  869. }
  870. return val;
  871. });
  872. });
  873. /**
  874. * Retrieve the value at a given path.
  875. *
  876. * @func
  877. * @memberOf R
  878. * @since v0.2.0
  879. * @category Object
  880. * @typedefn Idx = String | Int
  881. * @sig [Idx] -> {a} -> a | Undefined
  882. * @param {Array} path The path to use.
  883. * @param {Object} obj The object to retrieve the nested property from.
  884. * @return {*} The data at `path`.
  885. * @see R.prop, R.nth
  886. * @example
  887. *
  888. * R.path(['a', 'b'], {a: {b: 2}}); //=> 2
  889. * R.path(['a', 'b'], {c: {b: 2}}); //=> undefined
  890. * R.path(['a', 'b', 0], {a: {b: [1, 2, 3]}}); //=> 1
  891. * R.path(['a', 'b', -2], {a: {b: [1, 2, 3]}}); //=> 2
  892. */
  893. var path = _curry2(function path(pathAr, obj) {
  894. return paths([pathAr], obj)[0];
  895. });
  896. /**
  897. * Returns a function that when supplied an object returns the indicated
  898. * property of that object, if it exists.
  899. *
  900. * @func
  901. * @memberOf R
  902. * @since v0.1.0
  903. * @category Object
  904. * @typedefn Idx = String | Int
  905. * @sig Idx -> {s: a} -> a | Undefined
  906. * @param {String|Number} p The property name or array index
  907. * @param {Object} obj The object to query
  908. * @return {*} The value at `obj.p`.
  909. * @see R.path, R.nth
  910. * @example
  911. *
  912. * R.prop('x', {x: 100}); //=> 100
  913. * R.prop('x', {}); //=> undefined
  914. * R.prop(0, [100]); //=> 100
  915. * R.compose(R.inc, R.prop('x'))({ x: 3 }) //=> 4
  916. */
  917. var prop = _curry2(function prop(p, obj) { return path([p], obj); });
  918. /**
  919. * Returns a new list by plucking the same named property off all objects in
  920. * the list supplied.
  921. *
  922. * `pluck` will work on
  923. * any [functor](https://github.com/fantasyland/fantasy-land#functor) in
  924. * addition to arrays, as it is equivalent to `R.map(R.prop(k), f)`.
  925. *
  926. * @func
  927. * @memberOf R
  928. * @since v0.1.0
  929. * @category List
  930. * @sig Functor f => k -> f {k: v} -> f v
  931. * @param {Number|String} key The key name to pluck off of each object.
  932. * @param {Array} f The array or functor to consider.
  933. * @return {Array} The list of values for the given key.
  934. * @see R.props
  935. * @example
  936. *
  937. * var getAges = R.pluck('age');
  938. * getAges([{name: 'fred', age: 29}, {name: 'wilma', age: 27}]); //=> [29, 27]
  939. *
  940. * R.pluck(0, [[1, 2], [3, 4]]); //=> [1, 3]
  941. * R.pluck('val', {a: {val: 3}, b: {val: 5}}); //=> {a: 3, b: 5}
  942. * @symb R.pluck('x', [{x: 1, y: 2}, {x: 3, y: 4}, {x: 5, y: 6}]) = [1, 3, 5]
  943. * @symb R.pluck(0, [[1, 2], [3, 4], [5, 6]]) = [1, 3, 5]
  944. */
  945. var pluck = _curry2(function pluck(p, list) {
  946. return map(prop(p), list);
  947. });
  948. /**
  949. * Returns a single item by iterating through the list, successively calling
  950. * the iterator function and passing it an accumulator value and the current
  951. * value from the array, and then passing the result to the next call.
  952. *
  953. * The iterator function receives two values: *(acc, value)*. It may use
  954. * [`R.reduced`](#reduced) to shortcut the iteration.
  955. *
  956. * The arguments' order of [`reduceRight`](#reduceRight)'s iterator function
  957. * is *(value, acc)*.
  958. *
  959. * Note: `R.reduce` does not skip deleted or unassigned indices (sparse
  960. * arrays), unlike the native `Array.prototype.reduce` method. For more details
  961. * on this behavior, see:
  962. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description
  963. *
  964. * Dispatches to the `reduce` method of the third argument, if present. When
  965. * doing so, it is up to the user to handle the [`R.reduced`](#reduced)
  966. * shortcuting, as this is not implemented by `reduce`.
  967. *
  968. * @func
  969. * @memberOf R
  970. * @since v0.1.0
  971. * @category List
  972. * @sig ((a, b) -> a) -> a -> [b] -> a
  973. * @param {Function} fn The iterator function. Receives two values, the accumulator and the
  974. * current element from the array.
  975. * @param {*} acc The accumulator value.
  976. * @param {Array} list The list to iterate over.
  977. * @return {*} The final, accumulated value.
  978. * @see R.reduced, R.addIndex, R.reduceRight
  979. * @example
  980. *
  981. * R.reduce(R.subtract, 0, [1, 2, 3, 4]) // => ((((0 - 1) - 2) - 3) - 4) = -10
  982. * // - -10
  983. * // / \ / \
  984. * // - 4 -6 4
  985. * // / \ / \
  986. * // - 3 ==> -3 3
  987. * // / \ / \
  988. * // - 2 -1 2
  989. * // / \ / \
  990. * // 0 1 0 1
  991. *
  992. * @symb R.reduce(f, a, [b, c, d]) = f(f(f(a, b), c), d)
  993. */
  994. var reduce = _curry3(_reduce);
  995. /**
  996. * Takes a list of predicates and returns a predicate that returns true for a
  997. * given list of arguments if every one of the provided predicates is satisfied
  998. * by those arguments.
  999. *
  1000. * The function returned is a curried function whose arity matches that of the
  1001. * highest-arity predicate.
  1002. *
  1003. * @func
  1004. * @memberOf R
  1005. * @since v0.9.0
  1006. * @category Logic
  1007. * @sig [(*... -> Boolean)] -> (*... -> Boolean)
  1008. * @param {Array} predicates An array of predicates to check
  1009. * @return {Function} The combined predicate
  1010. * @see R.anyPass
  1011. * @example
  1012. *
  1013. * const isQueen = R.propEq('rank', 'Q');
  1014. * const isSpade = R.propEq('suit', '♠︎');
  1015. * const isQueenOfSpades = R.allPass([isQueen, isSpade]);
  1016. *
  1017. * isQueenOfSpades({rank: 'Q', suit: '♣︎'}); //=> false
  1018. * isQueenOfSpades({rank: 'Q', suit: '♠︎'}); //=> true
  1019. */
  1020. var allPass = _curry1(function allPass(preds) {
  1021. return curryN(reduce(max, 0, pluck('length', preds)), function() {
  1022. var idx = 0;
  1023. var len = preds.length;
  1024. while (idx < len) {
  1025. if (!preds[idx].apply(this, arguments)) {
  1026. return false;
  1027. }
  1028. idx += 1;
  1029. }
  1030. return true;
  1031. });
  1032. });
  1033. /**
  1034. * Returns a function that always returns the given value. Note that for
  1035. * non-primitives the value returned is a reference to the original value.
  1036. *
  1037. * This function is known as `const`, `constant`, or `K` (for K combinator) in
  1038. * other languages and libraries.
  1039. *
  1040. * @func
  1041. * @memberOf R
  1042. * @since v0.1.0
  1043. * @category Function
  1044. * @sig a -> (* -> a)
  1045. * @param {*} val The value to wrap in a function
  1046. * @return {Function} A Function :: * -> val.
  1047. * @example
  1048. *
  1049. * const t = R.always('Tee');
  1050. * t(); //=> 'Tee'
  1051. */
  1052. var always = _curry1(function always(val) {
  1053. return function() {
  1054. return val;
  1055. };
  1056. });
  1057. /**
  1058. * Returns `true` if both arguments are `true`; `false` otherwise.
  1059. *
  1060. * @func
  1061. * @memberOf R
  1062. * @since v0.1.0
  1063. * @category Logic
  1064. * @sig a -> b -> a | b
  1065. * @param {Any} a
  1066. * @param {Any} b
  1067. * @return {Any} the first argument if it is falsy, otherwise the second argument.
  1068. * @see R.both, R.xor
  1069. * @example
  1070. *
  1071. * R.and(true, true); //=> true
  1072. * R.and(true, false); //=> false
  1073. * R.and(false, true); //=> false
  1074. * R.and(false, false); //=> false
  1075. */
  1076. var and = _curry2(function and(a, b) {
  1077. return a && b;
  1078. });
  1079. function XAny(f, xf) {
  1080. this.xf = xf;
  1081. this.f = f;
  1082. this.any = false;
  1083. }
  1084. XAny.prototype['@@transducer/init'] = _xfBase.init;
  1085. XAny.prototype['@@transducer/result'] = function(result) {
  1086. if (!this.any) {
  1087. result = this.xf['@@transducer/step'](result, false);
  1088. }
  1089. return this.xf['@@transducer/result'](result);
  1090. };
  1091. XAny.prototype['@@transducer/step'] = function(result, input) {
  1092. if (this.f(input)) {
  1093. this.any = true;
  1094. result = _reduced(this.xf['@@transducer/step'](result, true));
  1095. }
  1096. return result;
  1097. };
  1098. var _xany = _curry2(function _xany(f, xf) { return new XAny(f, xf); });
  1099. /**
  1100. * Returns `true` if at least one of the elements of the list match the predicate,
  1101. * `false` otherwise.
  1102. *
  1103. * Dispatches to the `any` method of the second argument, if present.
  1104. *
  1105. * Acts as a transducer if a transformer is given in list position.
  1106. *
  1107. * @func
  1108. * @memberOf R
  1109. * @since v0.1.0
  1110. * @category List
  1111. * @sig (a -> Boolean) -> [a] -> Boolean
  1112. * @param {Function} fn The predicate function.
  1113. * @param {Array} list The array to consider.
  1114. * @return {Boolean} `true` if the predicate is satisfied by at least one element, `false`
  1115. * otherwise.
  1116. * @see R.all, R.none, R.transduce
  1117. * @example
  1118. *
  1119. * const lessThan0 = R.flip(R.lt)(0);
  1120. * const lessThan2 = R.flip(R.lt)(2);
  1121. * R.any(lessThan0)([1, 2]); //=> false
  1122. * R.any(lessThan2)([1, 2]); //=> true
  1123. */
  1124. var any = _curry2(_dispatchable(['any'], _xany, function any(fn, list) {
  1125. var idx = 0;
  1126. while (idx < list.length) {
  1127. if (fn(list[idx])) {
  1128. return true;
  1129. }
  1130. idx += 1;
  1131. }
  1132. return false;
  1133. }));
  1134. /**
  1135. * Takes a list of predicates and returns a predicate that returns true for a
  1136. * given list of arguments if at least one of the provided predicates is
  1137. * satisfied by those arguments.
  1138. *
  1139. * The function returned is a curried function whose arity matches that of the
  1140. * highest-arity predicate.
  1141. *
  1142. * @func
  1143. * @memberOf R
  1144. * @since v0.9.0
  1145. * @category Logic
  1146. * @sig [(*... -> Boolean)] -> (*... -> Boolean)
  1147. * @param {Array} predicates An array of predicates to check
  1148. * @return {Function} The combined predicate
  1149. * @see R.allPass
  1150. * @example
  1151. *
  1152. * const isClub = R.propEq('suit', '♣');
  1153. * const isSpade = R.propEq('suit', '♠');
  1154. * const isBlackCard = R.anyPass([isClub, isSpade]);
  1155. *
  1156. * isBlackCard({rank: '10', suit: '♣'}); //=> true
  1157. * isBlackCard({rank: 'Q', suit: '♠'}); //=> true
  1158. * isBlackCard({rank: 'Q', suit: '♦'}); //=> false
  1159. */
  1160. var anyPass = _curry1(function anyPass(preds) {
  1161. return curryN(reduce(max, 0, pluck('length', preds)), function() {
  1162. var idx = 0;
  1163. var len = preds.length;
  1164. while (idx < len) {
  1165. if (preds[idx].apply(this, arguments)) {
  1166. return true;
  1167. }
  1168. idx += 1;
  1169. }
  1170. return false;
  1171. });
  1172. });
  1173. /**
  1174. * ap applies a list of functions to a list of values.
  1175. *
  1176. * Dispatches to the `ap` method of the second argument, if present. Also
  1177. * treats curried functions as applicatives.
  1178. *
  1179. * @func
  1180. * @memberOf R
  1181. * @since v0.3.0
  1182. * @category Function
  1183. * @sig [a -> b] -> [a] -> [b]
  1184. * @sig Apply f => f (a -> b) -> f a -> f b
  1185. * @sig (r -> a -> b) -> (r -> a) -> (r -> b)
  1186. * @param {*} applyF
  1187. * @param {*} applyX
  1188. * @return {*}
  1189. * @example
  1190. *
  1191. * R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6]
  1192. * R.ap([R.concat('tasty '), R.toUpper], ['pizza', 'salad']); //=> ["tasty pizza", "tasty salad", "PIZZA", "SALAD"]
  1193. *
  1194. * // R.ap can also be used as S combinator
  1195. * // when only two functions are passed
  1196. * R.ap(R.concat, R.toUpper)('Ramda') //=> 'RamdaRAMDA'
  1197. * @symb R.ap([f, g], [a, b]) = [f(a), f(b), g(a), g(b)]
  1198. */
  1199. var ap = _curry2(function ap(applyF, applyX) {
  1200. return (
  1201. typeof applyX['fantasy-land/ap'] === 'function'
  1202. ? applyX['fantasy-land/ap'](applyF)
  1203. : typeof applyF.ap === 'function'
  1204. ? applyF.ap(applyX)
  1205. : typeof applyF === 'function'
  1206. ? function(x) { return applyF(x)(applyX(x)); }
  1207. : _reduce(function(acc, f) { return _concat(acc, map(f, applyX)); }, [], applyF)
  1208. );
  1209. });
  1210. function _aperture(n, list) {
  1211. var idx = 0;
  1212. var limit = list.length - (n - 1);
  1213. var acc = new Array(limit >= 0 ? limit : 0);
  1214. while (idx < limit) {
  1215. acc[idx] = Array.prototype.slice.call(list, idx, idx + n);
  1216. idx += 1;
  1217. }
  1218. return acc;
  1219. }
  1220. function XAperture(n, xf) {
  1221. this.xf = xf;
  1222. this.pos = 0;
  1223. this.full = false;
  1224. this.acc = new Array(n);
  1225. }
  1226. XAperture.prototype['@@transducer/init'] = _xfBase.init;
  1227. XAperture.prototype['@@transducer/result'] = function(result) {
  1228. this.acc = null;
  1229. return this.xf['@@transducer/result'](result);
  1230. };
  1231. XAperture.prototype['@@transducer/step'] = function(result, input) {
  1232. this.store(input);
  1233. return this.full ? this.xf['@@transducer/step'](result, this.getCopy()) : result;
  1234. };
  1235. XAperture.prototype.store = function(input) {
  1236. this.acc[this.pos] = input;
  1237. this.pos += 1;
  1238. if (this.pos === this.acc.length) {
  1239. this.pos = 0;
  1240. this.full = true;
  1241. }
  1242. };
  1243. XAperture.prototype.getCopy = function() {
  1244. return _concat(Array.prototype.slice.call(this.acc, this.pos),
  1245. Array.prototype.slice.call(this.acc, 0, this.pos)
  1246. );
  1247. };
  1248. var _xaperture = _curry2(function _xaperture(n, xf) { return new XAperture(n, xf); });
  1249. /**
  1250. * Returns a new list, composed of n-tuples of consecutive elements. If `n` is
  1251. * greater than the length of the list, an empty list is returned.
  1252. *
  1253. * Acts as a transducer if a transformer is given in list position.
  1254. *
  1255. * @func
  1256. * @memberOf R
  1257. * @since v0.12.0
  1258. * @category List
  1259. * @sig Number -> [a] -> [[a]]
  1260. * @param {Number} n The size of the tuples to create
  1261. * @param {Array} list The list to split into `n`-length tuples
  1262. * @return {Array} The resulting list of `n`-length tuples
  1263. * @see R.transduce
  1264. * @example
  1265. *
  1266. * R.aperture(2, [1, 2, 3, 4, 5]); //=> [[1, 2], [2, 3], [3, 4], [4, 5]]
  1267. * R.aperture(3, [1, 2, 3, 4, 5]); //=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
  1268. * R.aperture(7, [1, 2, 3, 4, 5]); //=> []
  1269. */
  1270. var aperture = _curry2(_dispatchable([], _xaperture, _aperture));
  1271. /**
  1272. * Returns a new list containing the contents of the given list, followed by
  1273. * the given element.
  1274. *
  1275. * @func
  1276. * @memberOf R
  1277. * @since v0.1.0
  1278. * @category List
  1279. * @sig a -> [a] -> [a]
  1280. * @param {*} el The element to add to the end of the new list.
  1281. * @param {Array} list The list of elements to add a new item to.
  1282. * list.
  1283. * @return {Array} A new list containing the elements of the old list followed by `el`.
  1284. * @see R.prepend
  1285. * @example
  1286. *
  1287. * R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests']
  1288. * R.append('tests', []); //=> ['tests']
  1289. * R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']]
  1290. */
  1291. var append = _curry2(function append(el, list) {
  1292. return _concat(list, [el]);
  1293. });
  1294. /**
  1295. * Applies function `fn` to the argument list `args`. This is useful for
  1296. * creating a fixed-arity function from a variadic function. `fn` should be a
  1297. * bound function if context is significant.
  1298. *
  1299. * @func
  1300. * @memberOf R
  1301. * @since v0.7.0
  1302. * @category Function
  1303. * @sig (*... -> a) -> [*] -> a
  1304. * @param {Function} fn The function which will be called with `args`
  1305. * @param {Array} args The arguments to call `fn` with
  1306. * @return {*} result The result, equivalent to `fn(...args)`
  1307. * @see R.call, R.unapply
  1308. * @example
  1309. *
  1310. * const nums = [1, 2, 3, -99, 42, 6, 7];
  1311. * R.apply(Math.max, nums); //=> 42
  1312. * @symb R.apply(f, [a, b, c]) = f(a, b, c)
  1313. */
  1314. var apply = _curry2(function apply(fn, args) {
  1315. return fn.apply(this, args);
  1316. });
  1317. /**
  1318. * Returns a list of all the enumerable own properties of the supplied object.
  1319. * Note that the order of the output array is not guaranteed across different
  1320. * JS platforms.
  1321. *
  1322. * @func
  1323. * @memberOf R
  1324. * @since v0.1.0
  1325. * @category Object
  1326. * @sig {k: v} -> [v]
  1327. * @param {Object} obj The object to extract values from
  1328. * @return {Array} An array of the values of the object's own properties.
  1329. * @see R.valuesIn, R.keys
  1330. * @example
  1331. *
  1332. * R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3]
  1333. */
  1334. var values = _curry1(function values(obj) {
  1335. var props = keys(obj);
  1336. var len = props.length;
  1337. var vals = [];
  1338. var idx = 0;
  1339. while (idx < len) {
  1340. vals[idx] = obj[props[idx]];
  1341. idx += 1;
  1342. }
  1343. return vals;
  1344. });
  1345. // Use custom mapValues function to avoid issues with specs that include a "map" key and R.map
  1346. // delegating calls to .map
  1347. function mapValues(fn, obj) {
  1348. return keys(obj).reduce(function(acc, key) {
  1349. acc[key] = fn(obj[key]);
  1350. return acc;
  1351. }, {});
  1352. }
  1353. /**
  1354. * Given a spec object recursively mapping properties to functions, creates a
  1355. * function producing an object of the same structure, by mapping each property
  1356. * to the result of calling its associated function with the supplied arguments.
  1357. *
  1358. * @func
  1359. * @memberOf R
  1360. * @since v0.20.0
  1361. * @category Function
  1362. * @sig {k: ((a, b, ..., m) -> v)} -> ((a, b, ..., m) -> {k: v})
  1363. * @param {Object} spec an object recursively mapping properties to functions for
  1364. * producing the values for these properties.
  1365. * @return {Function} A function that returns an object of the same structure
  1366. * as `spec', with each property set to the value returned by calling its
  1367. * associated function with the supplied arguments.
  1368. * @see R.converge, R.juxt
  1369. * @example
  1370. *
  1371. * const getMetrics = R.applySpec({
  1372. * sum: R.add,
  1373. * nested: { mul: R.multiply }
  1374. * });
  1375. * getMetrics(2, 4); // => { sum: 6, nested: { mul: 8 } }
  1376. * @symb R.applySpec({ x: f, y: { z: g } })(a, b) = { x: f(a, b), y: { z: g(a, b) } }
  1377. */
  1378. var applySpec = _curry1(function applySpec(spec) {
  1379. spec = mapValues(
  1380. function(v) { return typeof v == 'function' ? v : applySpec(v); },
  1381. spec
  1382. );
  1383. return curryN(
  1384. reduce(max, 0, pluck('length', values(spec))),
  1385. function() {
  1386. var args = arguments;
  1387. return mapValues(function(f) { return apply(f, args); }, spec);
  1388. });
  1389. });
  1390. /**
  1391. * Takes a value and applies a function to it.
  1392. *
  1393. * This function is also known as the `thrush` combinator.
  1394. *
  1395. * @func
  1396. * @memberOf R
  1397. * @since v0.25.0
  1398. * @category Function
  1399. * @sig a -> (a -> b) -> b
  1400. * @param {*} x The value
  1401. * @param {Function} f The function to apply
  1402. * @return {*} The result of applying `f` to `x`
  1403. * @example
  1404. *
  1405. * const t42 = R.applyTo(42);
  1406. * t42(R.identity); //=> 42
  1407. * t42(R.add(1)); //=> 43
  1408. */
  1409. var applyTo = _curry2(function applyTo(x, f) { return f(x); });
  1410. /**
  1411. * Makes an ascending comparator function out of a function that returns a value
  1412. * that can be compared with `<` and `>`.
  1413. *
  1414. * @func
  1415. * @memberOf R
  1416. * @since v0.23.0
  1417. * @category Function
  1418. * @sig Ord b => (a -> b) -> a -> a -> Number
  1419. * @param {Function} fn A function of arity one that returns a value that can be compared
  1420. * @param {*} a The first item to be compared.
  1421. * @param {*} b The second item to be compared.
  1422. * @return {Number} `-1` if fn(a) < fn(b), `1` if fn(b) < fn(a), otherwise `0`
  1423. * @see R.descend
  1424. * @example
  1425. *
  1426. * const byAge = R.ascend(R.prop('age'));
  1427. * const people = [
  1428. * { name: 'Emma', age: 70 },
  1429. * { name: 'Peter', age: 78 },
  1430. * { name: 'Mikhail', age: 62 },
  1431. * ];
  1432. * const peopleByYoungestFirst = R.sort(byAge, people);
  1433. * //=> [{ name: 'Mikhail', age: 62 },{ name: 'Emma', age: 70 }, { name: 'Peter', age: 78 }]
  1434. */
  1435. var ascend = _curry3(function ascend(fn, a, b) {
  1436. var aa = fn(a);
  1437. var bb = fn(b);
  1438. return aa < bb ? -1 : aa > bb ? 1 : 0;
  1439. });
  1440. /**
  1441. * Makes a shallow clone of an object, setting or overriding the specified
  1442. * property with the given value. Note that this copies and flattens prototype
  1443. * properties onto the new object as well. All non-primitive properties are
  1444. * copied by reference.
  1445. *
  1446. * @func
  1447. * @memberOf R
  1448. * @since v0.8.0
  1449. * @category Object
  1450. * @sig String -> a -> {k: v} -> {k: v}
  1451. * @param {String} prop The property name to set
  1452. * @param {*} val The new value
  1453. * @param {Object} obj The object to clone
  1454. * @return {Object} A new object equivalent to the original except for the changed property.
  1455. * @see R.dissoc, R.pick
  1456. * @example
  1457. *
  1458. * R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3}
  1459. */
  1460. var assoc = _curry3(function assoc(prop, val, obj) {
  1461. var result = {};
  1462. for (var p in obj) {
  1463. result[p] = obj[p];
  1464. }
  1465. result[prop] = val;
  1466. return result;
  1467. });
  1468. /**
  1469. * Checks if the input value is `null` or `undefined`.
  1470. *
  1471. * @func
  1472. * @memberOf R
  1473. * @since v0.9.0
  1474. * @category Type
  1475. * @sig * -> Boolean
  1476. * @param {*} x The value to test.
  1477. * @return {Boolean} `true` if `x` is `undefined` or `null`, otherwise `false`.
  1478. * @example
  1479. *
  1480. * R.isNil(null); //=> true
  1481. * R.isNil(undefined); //=> true
  1482. * R.isNil(0); //=> false
  1483. * R.isNil([]); //=> false
  1484. */
  1485. var isNil = _curry1(function isNil(x) { return x == null; });
  1486. /**
  1487. * Makes a shallow clone of an object, setting or overriding the nodes required
  1488. * to create the given path, and placing the specific value at the tail end of
  1489. * that path. Note that this copies and flattens prototype properties onto the
  1490. * new object as well. All non-primitive properties are copied by reference.
  1491. *
  1492. * @func
  1493. * @memberOf R
  1494. * @since v0.8.0
  1495. * @category Object
  1496. * @typedefn Idx = String | Int
  1497. * @sig [Idx] -> a -> {a} -> {a}
  1498. * @param {Array} path the path to set
  1499. * @param {*} val The new value
  1500. * @param {Object} obj The object to clone
  1501. * @return {Object} A new object equivalent to the original except along the specified path.
  1502. * @see R.dissocPath
  1503. * @example
  1504. *
  1505. * R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}}
  1506. *
  1507. * // Any missing or non-object keys in path will be overridden
  1508. * R.assocPath(['a', 'b', 'c'], 42, {a: 5}); //=> {a: {b: {c: 42}}}
  1509. */
  1510. var assocPath = _curry3(function assocPath(path, val, obj) {
  1511. if (path.length === 0) {
  1512. return val;
  1513. }
  1514. var idx = path[0];
  1515. if (path.length > 1) {
  1516. var nextObj = (!isNil(obj) && _has(idx, obj)) ? obj[idx] : _isInteger(path[1]) ? [] : {};
  1517. val = assocPath(Array.prototype.slice.call(path, 1), val, nextObj);
  1518. }
  1519. if (_isInteger(idx) && _isArray(obj)) {
  1520. var arr = [].concat(obj);
  1521. arr[idx] = val;
  1522. return arr;
  1523. } else {
  1524. return assoc(idx, val, obj);
  1525. }
  1526. });
  1527. /**
  1528. * Wraps a function of any arity (including nullary) in a function that accepts
  1529. * exactly `n` parameters. Any extraneous parameters will not be passed to the
  1530. * supplied function.
  1531. *
  1532. * @func
  1533. * @memberOf R
  1534. * @since v0.1.0
  1535. * @category Function
  1536. * @sig Number -> (* -> a) -> (* -> a)
  1537. * @param {Number} n The desired arity of the new function.
  1538. * @param {Function} fn The function to wrap.
  1539. * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
  1540. * arity `n`.
  1541. * @see R.binary, R.unary
  1542. * @example
  1543. *
  1544. * const takesTwoArgs = (a, b) => [a, b];
  1545. *
  1546. * takesTwoArgs.length; //=> 2
  1547. * takesTwoArgs(1, 2); //=> [1, 2]
  1548. *
  1549. * const takesOneArg = R.nAry(1, takesTwoArgs);
  1550. * takesOneArg.length; //=> 1
  1551. * // Only `n` arguments are passed to the wrapped function
  1552. * takesOneArg(1, 2); //=> [1, undefined]
  1553. * @symb R.nAry(0, f)(a, b) = f()
  1554. * @symb R.nAry(1, f)(a, b) = f(a)
  1555. * @symb R.nAry(2, f)(a, b) = f(a, b)
  1556. */
  1557. var nAry = _curry2(function nAry(n, fn) {
  1558. switch (n) {
  1559. case 0: return function() {return fn.call(this);};
  1560. case 1: return function(a0) {return fn.call(this, a0);};
  1561. case 2: return function(a0, a1) {return fn.call(this, a0, a1);};
  1562. case 3: return function(a0, a1, a2) {return fn.call(this, a0, a1, a2);};
  1563. case 4: return function(a0, a1, a2, a3) {return fn.call(this, a0, a1, a2, a3);};
  1564. case 5: return function(a0, a1, a2, a3, a4) {return fn.call(this, a0, a1, a2, a3, a4);};
  1565. case 6: return function(a0, a1, a2, a3, a4, a5) {return fn.call(this, a0, a1, a2, a3, a4, a5);};
  1566. case 7: return function(a0, a1, a2, a3, a4, a5, a6) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6);};
  1567. case 8: return function(a0, a1, a2, a3, a4, a5, a6, a7) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7);};
  1568. 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);};
  1569. 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);};
  1570. default: throw new Error('First argument to nAry must be a non-negative integer no greater than ten');
  1571. }
  1572. });
  1573. /**
  1574. * Wraps a function of any arity (including nullary) in a function that accepts
  1575. * exactly 2 parameters. Any extraneous parameters will not be passed to the
  1576. * supplied function.
  1577. *
  1578. * @func
  1579. * @memberOf R
  1580. * @since v0.2.0
  1581. * @category Function
  1582. * @sig (* -> c) -> (a, b -> c)
  1583. * @param {Function} fn The function to wrap.
  1584. * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
  1585. * arity 2.
  1586. * @see R.nAry, R.unary
  1587. * @example
  1588. *
  1589. * const takesThreeArgs = function(a, b, c) {
  1590. * return [a, b, c];
  1591. * };
  1592. * takesThreeArgs.length; //=> 3
  1593. * takesThreeArgs(1, 2, 3); //=> [1, 2, 3]
  1594. *
  1595. * const takesTwoArgs = R.binary(takesThreeArgs);
  1596. * takesTwoArgs.length; //=> 2
  1597. * // Only 2 arguments are passed to the wrapped function
  1598. * takesTwoArgs(1, 2, 3); //=> [1, 2, undefined]
  1599. * @symb R.binary(f)(a, b, c) = f(a, b)
  1600. */
  1601. var binary = _curry1(function binary(fn) {
  1602. return nAry(2, fn);
  1603. });
  1604. function _isFunction(x) {
  1605. var type = Object.prototype.toString.call(x);
  1606. return type === '[object Function]' ||
  1607. type === '[object AsyncFunction]' ||
  1608. type === '[object GeneratorFunction]' ||
  1609. type === '[object AsyncGeneratorFunction]';
  1610. }
  1611. /**
  1612. * "lifts" a function to be the specified arity, so that it may "map over" that
  1613. * many lists, Functions or other objects that satisfy the [FantasyLand Apply spec](https://github.com/fantasyland/fantasy-land#apply).
  1614. *
  1615. * @func
  1616. * @memberOf R
  1617. * @since v0.7.0
  1618. * @category Function
  1619. * @sig Number -> (*... -> *) -> ([*]... -> [*])
  1620. * @param {Function} fn The function to lift into higher context
  1621. * @return {Function} The lifted function.
  1622. * @see R.lift, R.ap
  1623. * @example
  1624. *
  1625. * const madd3 = R.liftN(3, (...args) => R.sum(args));
  1626. * madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7]
  1627. */
  1628. var liftN = _curry2(function liftN(arity, fn) {
  1629. var lifted = curryN(arity, fn);
  1630. return curryN(arity, function() {
  1631. return _reduce(ap, map(lifted, arguments[0]), Array.prototype.slice.call(arguments, 1));
  1632. });
  1633. });
  1634. /**
  1635. * "lifts" a function of arity > 1 so that it may "map over" a list, Function or other
  1636. * object that satisfies the [FantasyLand Apply spec](https://github.com/fantasyland/fantasy-land#apply).
  1637. *
  1638. * @func
  1639. * @memberOf R
  1640. * @since v0.7.0
  1641. * @category Function
  1642. * @sig (*... -> *) -> ([*]... -> [*])
  1643. * @param {Function} fn The function to lift into higher context
  1644. * @return {Function} The lifted function.
  1645. * @see R.liftN
  1646. * @example
  1647. *
  1648. * const madd3 = R.lift((a, b, c) => a + b + c);
  1649. *
  1650. * madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7]
  1651. *
  1652. * const madd5 = R.lift((a, b, c, d, e) => a + b + c + d + e);
  1653. *
  1654. * madd5([1,2], [3], [4, 5], [6], [7, 8]); //=> [21, 22, 22, 23, 22, 23, 23, 24]
  1655. */
  1656. var lift = _curry1(function lift(fn) {
  1657. return liftN(fn.length, fn);
  1658. });
  1659. /**
  1660. * A function which calls the two provided functions and returns the `&&`
  1661. * of the results.
  1662. * It returns the result of the first function if it is false-y and the result
  1663. * of the second function otherwise. Note that this is short-circuited,
  1664. * meaning that the second function will not be invoked if the first returns a
  1665. * false-y value.
  1666. *
  1667. * In addition to functions, `R.both` also accepts any fantasy-land compatible
  1668. * applicative functor.
  1669. *
  1670. * @func
  1671. * @memberOf R
  1672. * @since v0.12.0
  1673. * @category Logic
  1674. * @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean)
  1675. * @param {Function} f A predicate
  1676. * @param {Function} g Another predicate
  1677. * @return {Function} a function that applies its arguments to `f` and `g` and `&&`s their outputs together.
  1678. * @see R.and
  1679. * @example
  1680. *
  1681. * const gt10 = R.gt(R.__, 10)
  1682. * const lt20 = R.lt(R.__, 20)
  1683. * const f = R.both(gt10, lt20);
  1684. * f(15); //=> true
  1685. * f(30); //=> false
  1686. *
  1687. * R.both(Maybe.Just(false), Maybe.Just(55)); // => Maybe.Just(false)
  1688. * R.both([false, false, 'a'], [11]); //=> [false, false, 11]
  1689. */
  1690. var both = _curry2(function both(f, g) {
  1691. return _isFunction(f) ?
  1692. function _both() {
  1693. return f.apply(this, arguments) && g.apply(this, arguments);
  1694. } :
  1695. lift(and)(f, g);
  1696. });
  1697. /**
  1698. * Returns a curried equivalent of the provided function. The curried function
  1699. * has two unusual capabilities. First, its arguments needn't be provided one
  1700. * at a time. If `f` is a ternary function and `g` is `R.curry(f)`, the
  1701. * following are equivalent:
  1702. *
  1703. * - `g(1)(2)(3)`
  1704. * - `g(1)(2, 3)`
  1705. * - `g(1, 2)(3)`
  1706. * - `g(1, 2, 3)`
  1707. *
  1708. * Secondly, the special placeholder value [`R.__`](#__) may be used to specify
  1709. * "gaps", allowing partial application of any combination of arguments,
  1710. * regardless of their positions. If `g` is as above and `_` is [`R.__`](#__),
  1711. * the following are equivalent:
  1712. *
  1713. * - `g(1, 2, 3)`
  1714. * - `g(_, 2, 3)(1)`
  1715. * - `g(_, _, 3)(1)(2)`
  1716. * - `g(_, _, 3)(1, 2)`
  1717. * - `g(_, 2)(1)(3)`
  1718. * - `g(_, 2)(1, 3)`
  1719. * - `g(_, 2)(_, 3)(1)`
  1720. *
  1721. * @func
  1722. * @memberOf R
  1723. * @since v0.1.0
  1724. * @category Function
  1725. * @sig (* -> a) -> (* -> a)
  1726. * @param {Function} fn The function to curry.
  1727. * @return {Function} A new, curried function.
  1728. * @see R.curryN, R.partial
  1729. * @example
  1730. *
  1731. * const addFourNumbers = (a, b, c, d) => a + b + c + d;
  1732. *
  1733. * const curriedAddFourNumbers = R.curry(addFourNumbers);
  1734. * const f = curriedAddFourNumbers(1, 2);
  1735. * const g = f(3);
  1736. * g(4); //=> 10
  1737. */
  1738. var curry = _curry1(function curry(fn) {
  1739. return curryN(fn.length, fn);
  1740. });
  1741. /**
  1742. * Returns the result of calling its first argument with the remaining
  1743. * arguments. This is occasionally useful as a converging function for
  1744. * [`R.converge`](#converge): the first branch can produce a function while the
  1745. * remaining branches produce values to be passed to that function as its
  1746. * arguments.
  1747. *
  1748. * @func
  1749. * @memberOf R
  1750. * @since v0.9.0
  1751. * @category Function
  1752. * @sig (*... -> a),*... -> a
  1753. * @param {Function} fn The function to apply to the remaining arguments.
  1754. * @param {...*} args Any number of positional arguments.
  1755. * @return {*}
  1756. * @see R.apply
  1757. * @example
  1758. *
  1759. * R.call(R.add, 1, 2); //=> 3
  1760. *
  1761. * const indentN = R.pipe(R.repeat(' '),
  1762. * R.join(''),
  1763. * R.replace(/^(?!$)/gm));
  1764. *
  1765. * const format = R.converge(R.call, [
  1766. * R.pipe(R.prop('indent'), indentN),
  1767. * R.prop('value')
  1768. * ]);
  1769. *
  1770. * format({indent: 2, value: 'foo\nbar\nbaz\n'}); //=> ' foo\n bar\n baz\n'
  1771. * @symb R.call(f, a, b) = f(a, b)
  1772. */
  1773. var call = curry(function call(fn) {
  1774. return fn.apply(this, Array.prototype.slice.call(arguments, 1));
  1775. });
  1776. /**
  1777. * `_makeFlat` is a helper function that returns a one-level or fully recursive
  1778. * function based on the flag passed in.
  1779. *
  1780. * @private
  1781. */
  1782. function _makeFlat(recursive) {
  1783. return function flatt(list) {
  1784. var value, jlen, j;
  1785. var result = [];
  1786. var idx = 0;
  1787. var ilen = list.length;
  1788. while (idx < ilen) {
  1789. if (_isArrayLike(list[idx])) {
  1790. value = recursive ? flatt(list[idx]) : list[idx];
  1791. j = 0;
  1792. jlen = value.length;
  1793. while (j < jlen) {
  1794. result[result.length] = value[j];
  1795. j += 1;
  1796. }
  1797. } else {
  1798. result[result.length] = list[idx];
  1799. }
  1800. idx += 1;
  1801. }
  1802. return result;
  1803. };
  1804. }
  1805. function _forceReduced(x) {
  1806. return {
  1807. '@@transducer/value': x,
  1808. '@@transducer/reduced': true
  1809. };
  1810. }
  1811. var preservingReduced = function(xf) {
  1812. return {
  1813. '@@transducer/init': _xfBase.init,
  1814. '@@transducer/result': function(result) {
  1815. return xf['@@transducer/result'](result);
  1816. },
  1817. '@@transducer/step': function(result, input) {
  1818. var ret = xf['@@transducer/step'](result, input);
  1819. return ret['@@transducer/reduced'] ? _forceReduced(ret) : ret;
  1820. }
  1821. };
  1822. };
  1823. var _flatCat = function _xcat(xf) {
  1824. var rxf = preservingReduced(xf);
  1825. return {
  1826. '@@transducer/init': _xfBase.init,
  1827. '@@transducer/result': function(result) {
  1828. return rxf['@@transducer/result'](result);
  1829. },
  1830. '@@transducer/step': function(result, input) {
  1831. return !_isArrayLike(input) ? _reduce(rxf, result, [input]) : _reduce(rxf, result, input);
  1832. }
  1833. };
  1834. };
  1835. var _xchain = _curry2(function _xchain(f, xf) {
  1836. return map(f, _flatCat(xf));
  1837. });
  1838. /**
  1839. * `chain` maps a function over a list and concatenates the results. `chain`
  1840. * is also known as `flatMap` in some libraries.
  1841. *
  1842. * Dispatches to the `chain` method of the second argument, if present,
  1843. * according to the [FantasyLand Chain spec](https://github.com/fantasyland/fantasy-land#chain).
  1844. *
  1845. * If second argument is a function, `chain(f, g)(x)` is equivalent to `f(g(x), x)`.
  1846. *
  1847. * Acts as a transducer if a transformer is given in list position.
  1848. *
  1849. * @func
  1850. * @memberOf R
  1851. * @since v0.3.0
  1852. * @category List
  1853. * @sig Chain m => (a -> m b) -> m a -> m b
  1854. * @param {Function} fn The function to map with
  1855. * @param {Array} list The list to map over
  1856. * @return {Array} The result of flat-mapping `list` with `fn`
  1857. * @example
  1858. *
  1859. * const duplicate = n => [n, n];
  1860. * R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3]
  1861. *
  1862. * R.chain(R.append, R.head)([1, 2, 3]); //=> [1, 2, 3, 1]
  1863. */
  1864. var chain = _curry2(_dispatchable(['fantasy-land/chain', 'chain'], _xchain, function chain(fn, monad) {
  1865. if (typeof monad === 'function') {
  1866. return function(x) { return fn(monad(x))(x); };
  1867. }
  1868. return _makeFlat(false)(map(fn, monad));
  1869. }));
  1870. /**
  1871. * Restricts a number to be within a range.
  1872. *
  1873. * Also works for other ordered types such as Strings and Dates.
  1874. *
  1875. * @func
  1876. * @memberOf R
  1877. * @since v0.20.0
  1878. * @category Relation
  1879. * @sig Ord a => a -> a -> a -> a
  1880. * @param {Number} minimum The lower limit of the clamp (inclusive)
  1881. * @param {Number} maximum The upper limit of the clamp (inclusive)
  1882. * @param {Number} value Value to be clamped
  1883. * @return {Number} Returns `minimum` when `val < minimum`, `maximum` when `val > maximum`, returns `val` otherwise
  1884. * @example
  1885. *
  1886. * R.clamp(1, 10, -5) // => 1
  1887. * R.clamp(1, 10, 15) // => 10
  1888. * R.clamp(1, 10, 4) // => 4
  1889. */
  1890. var clamp = _curry3(function clamp(min, max, value) {
  1891. if (min > max) {
  1892. throw new Error('min must not be greater than max in clamp(min, max, value)');
  1893. }
  1894. return value < min
  1895. ? min
  1896. : value > max
  1897. ? max
  1898. : value;
  1899. });
  1900. function _cloneRegExp(pattern) {
  1901. return new RegExp(pattern.source, (pattern.global ? 'g' : '') +
  1902. (pattern.ignoreCase ? 'i' : '') +
  1903. (pattern.multiline ? 'm' : '') +
  1904. (pattern.sticky ? 'y' : '') +
  1905. (pattern.unicode ? 'u' : ''));
  1906. }
  1907. /**
  1908. * Gives a single-word string description of the (native) type of a value,
  1909. * returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not
  1910. * attempt to distinguish user Object types any further, reporting them all as
  1911. * 'Object'.
  1912. *
  1913. * @func
  1914. * @memberOf R
  1915. * @since v0.8.0
  1916. * @category Type
  1917. * @sig (* -> {*}) -> String
  1918. * @param {*} val The value to test
  1919. * @return {String}
  1920. * @example
  1921. *
  1922. * R.type({}); //=> "Object"
  1923. * R.type(1); //=> "Number"
  1924. * R.type(false); //=> "Boolean"
  1925. * R.type('s'); //=> "String"
  1926. * R.type(null); //=> "Null"
  1927. * R.type([]); //=> "Array"
  1928. * R.type(/[A-z]/); //=> "RegExp"
  1929. * R.type(() => {}); //=> "Function"
  1930. * R.type(undefined); //=> "Undefined"
  1931. */
  1932. var type = _curry1(function type(val) {
  1933. return val === null
  1934. ? 'Null'
  1935. : val === undefined
  1936. ? 'Undefined'
  1937. : Object.prototype.toString.call(val).slice(8, -1);
  1938. });
  1939. /**
  1940. * Copies an object.
  1941. *
  1942. * @private
  1943. * @param {*} value The value to be copied
  1944. * @param {Array} refFrom Array containing the source references
  1945. * @param {Array} refTo Array containing the copied source references
  1946. * @param {Boolean} deep Whether or not to perform deep cloning.
  1947. * @return {*} The copied value.
  1948. */
  1949. function _clone(value, refFrom, refTo, deep) {
  1950. var copy = function copy(copiedValue) {
  1951. var len = refFrom.length;
  1952. var idx = 0;
  1953. while (idx < len) {
  1954. if (value === refFrom[idx]) {
  1955. return refTo[idx];
  1956. }
  1957. idx += 1;
  1958. }
  1959. refFrom[idx + 1] = value;
  1960. refTo[idx + 1] = copiedValue;
  1961. for (var key in value) {
  1962. copiedValue[key] = deep ?
  1963. _clone(value[key], refFrom, refTo, true) : value[key];
  1964. }
  1965. return copiedValue;
  1966. };
  1967. switch (type(value)) {
  1968. case 'Object': return copy({});
  1969. case 'Array': return copy([]);
  1970. case 'Date': return new Date(value.valueOf());
  1971. case 'RegExp': return _cloneRegExp(value);
  1972. default: return value;
  1973. }
  1974. }
  1975. /**
  1976. * Creates a deep copy of the value which may contain (nested) `Array`s and
  1977. * `Object`s, `Number`s, `String`s, `Boolean`s and `Date`s. `Function`s are
  1978. * assigned by reference rather than copied
  1979. *
  1980. * Dispatches to a `clone` method if present.
  1981. *
  1982. * @func
  1983. * @memberOf R
  1984. * @since v0.1.0
  1985. * @category Object
  1986. * @sig {*} -> {*}
  1987. * @param {*} value The object or array to clone
  1988. * @return {*} A deeply cloned copy of `val`
  1989. * @example
  1990. *
  1991. * const objects = [{}, {}, {}];
  1992. * const objectsClone = R.clone(objects);
  1993. * objects === objectsClone; //=> false
  1994. * objects[0] === objectsClone[0]; //=> false
  1995. */
  1996. var clone = _curry1(function clone(value) {
  1997. return value != null && typeof value.clone === 'function' ?
  1998. value.clone() :
  1999. _clone(value, [], [], true);
  2000. });
  2001. /**
  2002. * Makes a comparator function out of a function that reports whether the first
  2003. * element is less than the second.
  2004. *
  2005. * @func
  2006. * @memberOf R
  2007. * @since v0.1.0
  2008. * @category Function
  2009. * @sig ((a, b) -> Boolean) -> ((a, b) -> Number)
  2010. * @param {Function} pred A predicate function of arity two which will return `true` if the first argument
  2011. * is less than the second, `false` otherwise
  2012. * @return {Function} A Function :: a -> b -> Int that returns `-1` if a < b, `1` if b < a, otherwise `0`
  2013. * @example
  2014. *
  2015. * const byAge = R.comparator((a, b) => a.age < b.age);
  2016. * const people = [
  2017. * { name: 'Emma', age: 70 },
  2018. * { name: 'Peter', age: 78 },
  2019. * { name: 'Mikhail', age: 62 },
  2020. * ];
  2021. * const peopleByIncreasingAge = R.sort(byAge, people);
  2022. * //=> [{ name: 'Mikhail', age: 62 },{ name: 'Emma', age: 70 }, { name: 'Peter', age: 78 }]
  2023. */
  2024. var comparator = _curry1(function comparator(pred) {
  2025. return function(a, b) {
  2026. return pred(a, b) ? -1 : pred(b, a) ? 1 : 0;
  2027. };
  2028. });
  2029. /**
  2030. * A function that returns the `!` of its argument. It will return `true` when
  2031. * passed false-y value, and `false` when passed a truth-y one.
  2032. *
  2033. * @func
  2034. * @memberOf R
  2035. * @since v0.1.0
  2036. * @category Logic
  2037. * @sig * -> Boolean
  2038. * @param {*} a any value
  2039. * @return {Boolean} the logical inverse of passed argument.
  2040. * @see R.complement
  2041. * @example
  2042. *
  2043. * R.not(true); //=> false
  2044. * R.not(false); //=> true
  2045. * R.not(0); //=> true
  2046. * R.not(1); //=> false
  2047. */
  2048. var not = _curry1(function not(a) {
  2049. return !a;
  2050. });
  2051. /**
  2052. * Takes a function `f` and returns a function `g` such that if called with the same arguments
  2053. * when `f` returns a "truthy" value, `g` returns `false` and when `f` returns a "falsy" value `g` returns `true`.
  2054. *
  2055. * `R.complement` may be applied to any functor
  2056. *
  2057. * @func
  2058. * @memberOf R
  2059. * @since v0.12.0
  2060. * @category Logic
  2061. * @sig (*... -> *) -> (*... -> Boolean)
  2062. * @param {Function} f
  2063. * @return {Function}
  2064. * @see R.not
  2065. * @example
  2066. *
  2067. * const isNotNil = R.complement(R.isNil);
  2068. * isNil(null); //=> true
  2069. * isNotNil(null); //=> false
  2070. * isNil(7); //=> false
  2071. * isNotNil(7); //=> true
  2072. */
  2073. var complement = lift(not);
  2074. function _pipe(f, g) {
  2075. return function() {
  2076. return g.call(this, f.apply(this, arguments));
  2077. };
  2078. }
  2079. /**
  2080. * This checks whether a function has a [methodname] function. If it isn't an
  2081. * array it will execute that function otherwise it will default to the ramda
  2082. * implementation.
  2083. *
  2084. * @private
  2085. * @param {Function} fn ramda implemtation
  2086. * @param {String} methodname property to check for a custom implementation
  2087. * @return {Object} Whatever the return value of the method is.
  2088. */
  2089. function _checkForMethod(methodname, fn) {
  2090. return function() {
  2091. var length = arguments.length;
  2092. if (length === 0) {
  2093. return fn();
  2094. }
  2095. var obj = arguments[length - 1];
  2096. return (_isArray(obj) || typeof obj[methodname] !== 'function') ?
  2097. fn.apply(this, arguments) :
  2098. obj[methodname].apply(obj, Array.prototype.slice.call(arguments, 0, length - 1));
  2099. };
  2100. }
  2101. /**
  2102. * Returns the elements of the given list or string (or object with a `slice`
  2103. * method) from `fromIndex` (inclusive) to `toIndex` (exclusive).
  2104. *
  2105. * Dispatches to the `slice` method of the third argument, if present.
  2106. *
  2107. * @func
  2108. * @memberOf R
  2109. * @since v0.1.4
  2110. * @category List
  2111. * @sig Number -> Number -> [a] -> [a]
  2112. * @sig Number -> Number -> String -> String
  2113. * @param {Number} fromIndex The start index (inclusive).
  2114. * @param {Number} toIndex The end index (exclusive).
  2115. * @param {*} list
  2116. * @return {*}
  2117. * @example
  2118. *
  2119. * R.slice(1, 3, ['a', 'b', 'c', 'd']); //=> ['b', 'c']
  2120. * R.slice(1, Infinity, ['a', 'b', 'c', 'd']); //=> ['b', 'c', 'd']
  2121. * R.slice(0, -1, ['a', 'b', 'c', 'd']); //=> ['a', 'b', 'c']
  2122. * R.slice(-3, -1, ['a', 'b', 'c', 'd']); //=> ['b', 'c']
  2123. * R.slice(0, 3, 'ramda'); //=> 'ram'
  2124. */
  2125. var slice = _curry3(_checkForMethod('slice', function slice(fromIndex, toIndex, list) {
  2126. return Array.prototype.slice.call(list, fromIndex, toIndex);
  2127. }));
  2128. /**
  2129. * Returns all but the first element of the given list or string (or object
  2130. * with a `tail` method).
  2131. *
  2132. * Dispatches to the `slice` method of the first argument, if present.
  2133. *
  2134. * @func
  2135. * @memberOf R
  2136. * @since v0.1.0
  2137. * @category List
  2138. * @sig [a] -> [a]
  2139. * @sig String -> String
  2140. * @param {*} list
  2141. * @return {*}
  2142. * @see R.head, R.init, R.last
  2143. * @example
  2144. *
  2145. * R.tail([1, 2, 3]); //=> [2, 3]
  2146. * R.tail([1, 2]); //=> [2]
  2147. * R.tail([1]); //=> []
  2148. * R.tail([]); //=> []
  2149. *
  2150. * R.tail('abc'); //=> 'bc'
  2151. * R.tail('ab'); //=> 'b'
  2152. * R.tail('a'); //=> ''
  2153. * R.tail(''); //=> ''
  2154. */
  2155. var tail = _curry1(_checkForMethod('tail', slice(1, Infinity)));
  2156. /**
  2157. * Performs left-to-right function composition. The first argument may have
  2158. * any arity; the remaining arguments must be unary.
  2159. *
  2160. * In some libraries this function is named `sequence`.
  2161. *
  2162. * **Note:** The result of pipe is not automatically curried.
  2163. *
  2164. * @func
  2165. * @memberOf R
  2166. * @since v0.1.0
  2167. * @category Function
  2168. * @sig (((a, b, ..., n) -> o), (o -> p), ..., (x -> y), (y -> z)) -> ((a, b, ..., n) -> z)
  2169. * @param {...Function} functions
  2170. * @return {Function}
  2171. * @see R.compose
  2172. * @example
  2173. *
  2174. * const f = R.pipe(Math.pow, R.negate, R.inc);
  2175. *
  2176. * f(3, 4); // -(3^4) + 1
  2177. * @symb R.pipe(f, g, h)(a, b) = h(g(f(a, b)))
  2178. */
  2179. function pipe() {
  2180. if (arguments.length === 0) {
  2181. throw new Error('pipe requires at least one argument');
  2182. }
  2183. return _arity(
  2184. arguments[0].length,
  2185. reduce(_pipe, arguments[0], tail(arguments))
  2186. );
  2187. }
  2188. /**
  2189. * Returns a new list or string with the elements or characters in reverse
  2190. * order.
  2191. *
  2192. * @func
  2193. * @memberOf R
  2194. * @since v0.1.0
  2195. * @category List
  2196. * @sig [a] -> [a]
  2197. * @sig String -> String
  2198. * @param {Array|String} list
  2199. * @return {Array|String}
  2200. * @example
  2201. *
  2202. * R.reverse([1, 2, 3]); //=> [3, 2, 1]
  2203. * R.reverse([1, 2]); //=> [2, 1]
  2204. * R.reverse([1]); //=> [1]
  2205. * R.reverse([]); //=> []
  2206. *
  2207. * R.reverse('abc'); //=> 'cba'
  2208. * R.reverse('ab'); //=> 'ba'
  2209. * R.reverse('a'); //=> 'a'
  2210. * R.reverse(''); //=> ''
  2211. */
  2212. var reverse = _curry1(function reverse(list) {
  2213. return _isString(list)
  2214. ? list.split('').reverse().join('')
  2215. : Array.prototype.slice.call(list, 0).reverse();
  2216. });
  2217. /**
  2218. * Performs right-to-left function composition. The last argument may have
  2219. * any arity; the remaining arguments must be unary.
  2220. *
  2221. * **Note:** The result of compose is not automatically curried.
  2222. *
  2223. * @func
  2224. * @memberOf R
  2225. * @since v0.1.0
  2226. * @category Function
  2227. * @sig ((y -> z), (x -> y), ..., (o -> p), ((a, b, ..., n) -> o)) -> ((a, b, ..., n) -> z)
  2228. * @param {...Function} ...functions The functions to compose
  2229. * @return {Function}
  2230. * @see R.pipe
  2231. * @example
  2232. *
  2233. * const classyGreeting = (firstName, lastName) => "The name's " + lastName + ", " + firstName + " " + lastName
  2234. * const yellGreeting = R.compose(R.toUpper, classyGreeting);
  2235. * yellGreeting('James', 'Bond'); //=> "THE NAME'S BOND, JAMES BOND"
  2236. *
  2237. * R.compose(Math.abs, R.add(1), R.multiply(2))(-4) //=> 7
  2238. *
  2239. * @symb R.compose(f, g, h)(a, b) = f(g(h(a, b)))
  2240. */
  2241. function compose() {
  2242. if (arguments.length === 0) {
  2243. throw new Error('compose requires at least one argument');
  2244. }
  2245. return pipe.apply(this, reverse(arguments));
  2246. }
  2247. /**
  2248. * Returns the right-to-left Kleisli composition of the provided functions,
  2249. * each of which must return a value of a type supported by [`chain`](#chain).
  2250. *
  2251. * `R.composeK(h, g, f)` is equivalent to `R.compose(R.chain(h), R.chain(g), f)`.
  2252. *
  2253. * @func
  2254. * @memberOf R
  2255. * @since v0.16.0
  2256. * @category Function
  2257. * @sig Chain m => ((y -> m z), (x -> m y), ..., (a -> m b)) -> (a -> m z)
  2258. * @param {...Function} ...functions The functions to compose
  2259. * @return {Function}
  2260. * @see R.pipeK
  2261. * @deprecated since v0.26.0
  2262. * @example
  2263. *
  2264. * // get :: String -> Object -> Maybe *
  2265. * const get = R.curry((propName, obj) => Maybe(obj[propName]))
  2266. *
  2267. * // getStateCode :: Maybe String -> Maybe String
  2268. * const getStateCode = R.composeK(
  2269. * R.compose(Maybe.of, R.toUpper),
  2270. * get('state'),
  2271. * get('address'),
  2272. * get('user'),
  2273. * );
  2274. * getStateCode({"user":{"address":{"state":"ny"}}}); //=> Maybe.Just("NY")
  2275. * getStateCode({}); //=> Maybe.Nothing()
  2276. * @symb R.composeK(f, g, h)(a) = R.chain(f, R.chain(g, h(a)))
  2277. */
  2278. function composeK() {
  2279. if (arguments.length === 0) {
  2280. throw new Error('composeK requires at least one argument');
  2281. }
  2282. var init = Array.prototype.slice.call(arguments);
  2283. var last = init.pop();
  2284. return compose(compose.apply(this, map(chain, init)), last);
  2285. }
  2286. function _pipeP(f, g) {
  2287. return function() {
  2288. var ctx = this;
  2289. return f.apply(ctx, arguments).then(function(x) {
  2290. return g.call(ctx, x);
  2291. });
  2292. };
  2293. }
  2294. /**
  2295. * Performs left-to-right composition of one or more Promise-returning
  2296. * functions. The first argument may have any arity; the remaining arguments
  2297. * must be unary.
  2298. *
  2299. * @func
  2300. * @memberOf R
  2301. * @since v0.10.0
  2302. * @category Function
  2303. * @sig ((a -> Promise b), (b -> Promise c), ..., (y -> Promise z)) -> (a -> Promise z)
  2304. * @param {...Function} functions
  2305. * @return {Function}
  2306. * @see R.composeP
  2307. * @deprecated since v0.26.0
  2308. * @example
  2309. *
  2310. * // followersForUser :: String -> Promise [User]
  2311. * const followersForUser = R.pipeP(db.getUserById, db.getFollowers);
  2312. */
  2313. function pipeP() {
  2314. if (arguments.length === 0) {
  2315. throw new Error('pipeP requires at least one argument');
  2316. }
  2317. return _arity(
  2318. arguments[0].length,
  2319. reduce(_pipeP, arguments[0], tail(arguments))
  2320. );
  2321. }
  2322. /**
  2323. * Performs right-to-left composition of one or more Promise-returning
  2324. * functions. The last arguments may have any arity; the remaining
  2325. * arguments must be unary.
  2326. *
  2327. * @func
  2328. * @memberOf R
  2329. * @since v0.10.0
  2330. * @category Function
  2331. * @sig ((y -> Promise z), (x -> Promise y), ..., (a -> Promise b)) -> (a -> Promise z)
  2332. * @param {...Function} functions The functions to compose
  2333. * @return {Function}
  2334. * @see R.pipeP
  2335. * @deprecated since v0.26.0
  2336. * @example
  2337. *
  2338. * const db = {
  2339. * users: {
  2340. * JOE: {
  2341. * name: 'Joe',
  2342. * followers: ['STEVE', 'SUZY']
  2343. * }
  2344. * }
  2345. * }
  2346. *
  2347. * // We'll pretend to do a db lookup which returns a promise
  2348. * const lookupUser = (userId) => Promise.resolve(db.users[userId])
  2349. * const lookupFollowers = (user) => Promise.resolve(user.followers)
  2350. * lookupUser('JOE').then(lookupFollowers)
  2351. *
  2352. * // followersForUser :: String -> Promise [UserId]
  2353. * const followersForUser = R.composeP(lookupFollowers, lookupUser);
  2354. * followersForUser('JOE').then(followers => console.log('Followers:', followers))
  2355. * // Followers: ["STEVE","SUZY"]
  2356. */
  2357. function composeP() {
  2358. if (arguments.length === 0) {
  2359. throw new Error('composeP requires at least one argument');
  2360. }
  2361. return pipeP.apply(this, reverse(arguments));
  2362. }
  2363. /**
  2364. * Returns the first element of the given list or string. In some libraries
  2365. * this function is named `first`.
  2366. *
  2367. * @func
  2368. * @memberOf R
  2369. * @since v0.1.0
  2370. * @category List
  2371. * @sig [a] -> a | Undefined
  2372. * @sig String -> String
  2373. * @param {Array|String} list
  2374. * @return {*}
  2375. * @see R.tail, R.init, R.last
  2376. * @example
  2377. *
  2378. * R.head(['fi', 'fo', 'fum']); //=> 'fi'
  2379. * R.head([]); //=> undefined
  2380. *
  2381. * R.head('abc'); //=> 'a'
  2382. * R.head(''); //=> ''
  2383. */
  2384. var head = nth(0);
  2385. function _identity(x) { return x; }
  2386. /**
  2387. * A function that does nothing but return the parameter supplied to it. Good
  2388. * as a default or placeholder function.
  2389. *
  2390. * @func
  2391. * @memberOf R
  2392. * @since v0.1.0
  2393. * @category Function
  2394. * @sig a -> a
  2395. * @param {*} x The value to return.
  2396. * @return {*} The input value, `x`.
  2397. * @example
  2398. *
  2399. * R.identity(1); //=> 1
  2400. *
  2401. * const obj = {};
  2402. * R.identity(obj) === obj; //=> true
  2403. * @symb R.identity(a) = a
  2404. */
  2405. var identity = _curry1(_identity);
  2406. /**
  2407. * Performs left-to-right function composition using transforming function. The first argument may have
  2408. * any arity; the remaining arguments must be unary.
  2409. *
  2410. * **Note:** The result of pipeWith is not automatically curried. Transforming function is not used on the
  2411. * first argument.
  2412. *
  2413. * @func
  2414. * @memberOf R
  2415. * @since v0.26.0
  2416. * @category Function
  2417. * @sig ((* -> *), [((a, b, ..., n) -> o), (o -> p), ..., (x -> y), (y -> z)]) -> ((a, b, ..., n) -> z)
  2418. * @param {...Function} functions
  2419. * @return {Function}
  2420. * @see R.composeWith, R.pipe
  2421. * @example
  2422. *
  2423. * const pipeWhileNotNil = R.pipeWith((f, res) => R.isNil(res) ? res : f(res));
  2424. * const f = pipeWhileNotNil([Math.pow, R.negate, R.inc])
  2425. *
  2426. * f(3, 4); // -(3^4) + 1
  2427. * @symb R.pipeWith(f)([g, h, i])(...args) = f(i, f(h, g(...args)))
  2428. */
  2429. var pipeWith = _curry2(function pipeWith(xf, list) {
  2430. if (list.length <= 0) {
  2431. return identity;
  2432. }
  2433. var headList = head(list);
  2434. var tailList = tail(list);
  2435. return _arity(headList.length, function() {
  2436. return _reduce(
  2437. function(result, f) {
  2438. return xf.call(this, f, result);
  2439. },
  2440. headList.apply(this, arguments),
  2441. tailList
  2442. );
  2443. });
  2444. });
  2445. /**
  2446. * Performs right-to-left function composition using transforming function. The last argument may have
  2447. * any arity; the remaining arguments must be unary.
  2448. *
  2449. * **Note:** The result of compose is not automatically curried. Transforming function is not used on the
  2450. * last argument.
  2451. *
  2452. * @func
  2453. * @memberOf R
  2454. * @since v0.26.0
  2455. * @category Function
  2456. * @sig ((* -> *), [(y -> z), (x -> y), ..., (o -> p), ((a, b, ..., n) -> o)]) -> ((a, b, ..., n) -> z)
  2457. * @param {...Function} ...functions The functions to compose
  2458. * @return {Function}
  2459. * @see R.compose, R.pipeWith
  2460. * @example
  2461. *
  2462. * const composeWhileNotNil = R.composeWith((f, res) => R.isNil(res) ? res : f(res));
  2463. *
  2464. * composeWhileNotNil([R.inc, R.prop('age')])({age: 1}) //=> 2
  2465. * composeWhileNotNil([R.inc, R.prop('age')])({}) //=> undefined
  2466. *
  2467. * @symb R.composeWith(f)([g, h, i])(...args) = f(g, f(h, i(...args)))
  2468. */
  2469. var composeWith = _curry2(function composeWith(xf, list) {
  2470. return pipeWith.apply(this, [xf, reverse(list)]);
  2471. });
  2472. function _arrayFromIterator(iter) {
  2473. var list = [];
  2474. var next;
  2475. while (!(next = iter.next()).done) {
  2476. list.push(next.value);
  2477. }
  2478. return list;
  2479. }
  2480. function _includesWith(pred, x, list) {
  2481. var idx = 0;
  2482. var len = list.length;
  2483. while (idx < len) {
  2484. if (pred(x, list[idx])) {
  2485. return true;
  2486. }
  2487. idx += 1;
  2488. }
  2489. return false;
  2490. }
  2491. function _functionName(f) {
  2492. // String(x => x) evaluates to "x => x", so the pattern may not match.
  2493. var match = String(f).match(/^function (\w*)/);
  2494. return match == null ? '' : match[1];
  2495. }
  2496. // Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  2497. function _objectIs(a, b) {
  2498. // SameValue algorithm
  2499. if (a === b) { // Steps 1-5, 7-10
  2500. // Steps 6.b-6.e: +0 != -0
  2501. return a !== 0 || 1 / a === 1 / b;
  2502. } else {
  2503. // Step 6.a: NaN == NaN
  2504. return a !== a && b !== b;
  2505. }
  2506. }
  2507. var _objectIs$1 = typeof Object.is === 'function' ? Object.is : _objectIs;
  2508. /**
  2509. * private _uniqContentEquals function.
  2510. * That function is checking equality of 2 iterator contents with 2 assumptions
  2511. * - iterators lengths are the same
  2512. * - iterators values are unique
  2513. *
  2514. * false-positive result will be returned for comparision of, e.g.
  2515. * - [1,2,3] and [1,2,3,4]
  2516. * - [1,1,1] and [1,2,3]
  2517. * */
  2518. function _uniqContentEquals(aIterator, bIterator, stackA, stackB) {
  2519. var a = _arrayFromIterator(aIterator);
  2520. var b = _arrayFromIterator(bIterator);
  2521. function eq(_a, _b) {
  2522. return _equals(_a, _b, stackA.slice(), stackB.slice());
  2523. }
  2524. // if *a* array contains any element that is not included in *b*
  2525. return !_includesWith(function(b, aItem) {
  2526. return !_includesWith(eq, aItem, b);
  2527. }, b, a);
  2528. }
  2529. function _equals(a, b, stackA, stackB) {
  2530. if (_objectIs$1(a, b)) {
  2531. return true;
  2532. }
  2533. var typeA = type(a);
  2534. if (typeA !== type(b)) {
  2535. return false;
  2536. }
  2537. if (a == null || b == null) {
  2538. return false;
  2539. }
  2540. if (typeof a['fantasy-land/equals'] === 'function' || typeof b['fantasy-land/equals'] === 'function') {
  2541. return typeof a['fantasy-land/equals'] === 'function' && a['fantasy-land/equals'](b) &&
  2542. typeof b['fantasy-land/equals'] === 'function' && b['fantasy-land/equals'](a);
  2543. }
  2544. if (typeof a.equals === 'function' || typeof b.equals === 'function') {
  2545. return typeof a.equals === 'function' && a.equals(b) &&
  2546. typeof b.equals === 'function' && b.equals(a);
  2547. }
  2548. switch (typeA) {
  2549. case 'Arguments':
  2550. case 'Array':
  2551. case 'Object':
  2552. if (typeof a.constructor === 'function' &&
  2553. _functionName(a.constructor) === 'Promise') {
  2554. return a === b;
  2555. }
  2556. break;
  2557. case 'Boolean':
  2558. case 'Number':
  2559. case 'String':
  2560. if (!(typeof a === typeof b && _objectIs$1(a.valueOf(), b.valueOf()))) {
  2561. return false;
  2562. }
  2563. break;
  2564. case 'Date':
  2565. if (!_objectIs$1(a.valueOf(), b.valueOf())) {
  2566. return false;
  2567. }
  2568. break;
  2569. case 'Error':
  2570. return a.name === b.name && a.message === b.message;
  2571. case 'RegExp':
  2572. if (!(a.source === b.source &&
  2573. a.global === b.global &&
  2574. a.ignoreCase === b.ignoreCase &&
  2575. a.multiline === b.multiline &&
  2576. a.sticky === b.sticky &&
  2577. a.unicode === b.unicode)) {
  2578. return false;
  2579. }
  2580. break;
  2581. }
  2582. var idx = stackA.length - 1;
  2583. while (idx >= 0) {
  2584. if (stackA[idx] === a) {
  2585. return stackB[idx] === b;
  2586. }
  2587. idx -= 1;
  2588. }
  2589. switch (typeA) {
  2590. case 'Map':
  2591. if (a.size !== b.size) {
  2592. return false;
  2593. }
  2594. return _uniqContentEquals(a.entries(), b.entries(), stackA.concat([a]), stackB.concat([b]));
  2595. case 'Set':
  2596. if (a.size !== b.size) {
  2597. return false;
  2598. }
  2599. return _uniqContentEquals(a.values(), b.values(), stackA.concat([a]), stackB.concat([b]));
  2600. case 'Arguments':
  2601. case 'Array':
  2602. case 'Object':
  2603. case 'Boolean':
  2604. case 'Number':
  2605. case 'String':
  2606. case 'Date':
  2607. case 'Error':
  2608. case 'RegExp':
  2609. case 'Int8Array':
  2610. case 'Uint8Array':
  2611. case 'Uint8ClampedArray':
  2612. case 'Int16Array':
  2613. case 'Uint16Array':
  2614. case 'Int32Array':
  2615. case 'Uint32Array':
  2616. case 'Float32Array':
  2617. case 'Float64Array':
  2618. case 'ArrayBuffer':
  2619. break;
  2620. default:
  2621. // Values of other types are only equal if identical.
  2622. return false;
  2623. }
  2624. var keysA = keys(a);
  2625. if (keysA.length !== keys(b).length) {
  2626. return false;
  2627. }
  2628. var extendedStackA = stackA.concat([a]);
  2629. var extendedStackB = stackB.concat([b]);
  2630. idx = keysA.length - 1;
  2631. while (idx >= 0) {
  2632. var key = keysA[idx];
  2633. if (!(_has(key, b) && _equals(b[key], a[key], extendedStackA, extendedStackB))) {
  2634. return false;
  2635. }
  2636. idx -= 1;
  2637. }
  2638. return true;
  2639. }
  2640. /**
  2641. * Returns `true` if its arguments are equivalent, `false` otherwise. Handles
  2642. * cyclical data structures.
  2643. *
  2644. * Dispatches symmetrically to the `equals` methods of both arguments, if
  2645. * present.
  2646. *
  2647. * @func
  2648. * @memberOf R
  2649. * @since v0.15.0
  2650. * @category Relation
  2651. * @sig a -> b -> Boolean
  2652. * @param {*} a
  2653. * @param {*} b
  2654. * @return {Boolean}
  2655. * @example
  2656. *
  2657. * R.equals(1, 1); //=> true
  2658. * R.equals(1, '1'); //=> false
  2659. * R.equals([1, 2, 3], [1, 2, 3]); //=> true
  2660. *
  2661. * const a = {}; a.v = a;
  2662. * const b = {}; b.v = b;
  2663. * R.equals(a, b); //=> true
  2664. */
  2665. var equals = _curry2(function equals(a, b) {
  2666. return _equals(a, b, [], []);
  2667. });
  2668. function _indexOf(list, a, idx) {
  2669. var inf, item;
  2670. // Array.prototype.indexOf doesn't exist below IE9
  2671. if (typeof list.indexOf === 'function') {
  2672. switch (typeof a) {
  2673. case 'number':
  2674. if (a === 0) {
  2675. // manually crawl the list to distinguish between +0 and -0
  2676. inf = 1 / a;
  2677. while (idx < list.length) {
  2678. item = list[idx];
  2679. if (item === 0 && 1 / item === inf) {
  2680. return idx;
  2681. }
  2682. idx += 1;
  2683. }
  2684. return -1;
  2685. } else if (a !== a) {
  2686. // NaN
  2687. while (idx < list.length) {
  2688. item = list[idx];
  2689. if (typeof item === 'number' && item !== item) {
  2690. return idx;
  2691. }
  2692. idx += 1;
  2693. }
  2694. return -1;
  2695. }
  2696. // non-zero numbers can utilise Set
  2697. return list.indexOf(a, idx);
  2698. // all these types can utilise Set
  2699. case 'string':
  2700. case 'boolean':
  2701. case 'function':
  2702. case 'undefined':
  2703. return list.indexOf(a, idx);
  2704. case 'object':
  2705. if (a === null) {
  2706. // null can utilise Set
  2707. return list.indexOf(a, idx);
  2708. }
  2709. }
  2710. }
  2711. // anything else not covered above, defer to R.equals
  2712. while (idx < list.length) {
  2713. if (equals(list[idx], a)) {
  2714. return idx;
  2715. }
  2716. idx += 1;
  2717. }
  2718. return -1;
  2719. }
  2720. function _includes(a, list) {
  2721. return _indexOf(list, a, 0) >= 0;
  2722. }
  2723. function _quote(s) {
  2724. var escaped = s
  2725. .replace(/\\/g, '\\\\')
  2726. .replace(/[\b]/g, '\\b') // \b matches word boundary; [\b] matches backspace
  2727. .replace(/\f/g, '\\f')
  2728. .replace(/\n/g, '\\n')
  2729. .replace(/\r/g, '\\r')
  2730. .replace(/\t/g, '\\t')
  2731. .replace(/\v/g, '\\v')
  2732. .replace(/\0/g, '\\0');
  2733. return '"' + escaped.replace(/"/g, '\\"') + '"';
  2734. }
  2735. /**
  2736. * Polyfill from <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString>.
  2737. */
  2738. var pad = function pad(n) { return (n < 10 ? '0' : '') + n; };
  2739. var _toISOString = typeof Date.prototype.toISOString === 'function' ?
  2740. function _toISOString(d) {
  2741. return d.toISOString();
  2742. } :
  2743. function _toISOString(d) {
  2744. return (
  2745. d.getUTCFullYear() + '-' +
  2746. pad(d.getUTCMonth() + 1) + '-' +
  2747. pad(d.getUTCDate()) + 'T' +
  2748. pad(d.getUTCHours()) + ':' +
  2749. pad(d.getUTCMinutes()) + ':' +
  2750. pad(d.getUTCSeconds()) + '.' +
  2751. (d.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z'
  2752. );
  2753. };
  2754. function _complement(f) {
  2755. return function() {
  2756. return !f.apply(this, arguments);
  2757. };
  2758. }
  2759. function _filter(fn, list) {
  2760. var idx = 0;
  2761. var len = list.length;
  2762. var result = [];
  2763. while (idx < len) {
  2764. if (fn(list[idx])) {
  2765. result[result.length] = list[idx];
  2766. }
  2767. idx += 1;
  2768. }
  2769. return result;
  2770. }
  2771. function _isObject(x) {
  2772. return Object.prototype.toString.call(x) === '[object Object]';
  2773. }
  2774. function XFilter(f, xf) {
  2775. this.xf = xf;
  2776. this.f = f;
  2777. }
  2778. XFilter.prototype['@@transducer/init'] = _xfBase.init;
  2779. XFilter.prototype['@@transducer/result'] = _xfBase.result;
  2780. XFilter.prototype['@@transducer/step'] = function(result, input) {
  2781. return this.f(input) ? this.xf['@@transducer/step'](result, input) : result;
  2782. };
  2783. var _xfilter = _curry2(function _xfilter(f, xf) { return new XFilter(f, xf); });
  2784. /**
  2785. * Takes a predicate and a `Filterable`, and returns a new filterable of the
  2786. * same type containing the members of the given filterable which satisfy the
  2787. * given predicate. Filterable objects include plain objects or any object
  2788. * that has a filter method such as `Array`.
  2789. *
  2790. * Dispatches to the `filter` method of the second argument, if present.
  2791. *
  2792. * Acts as a transducer if a transformer is given in list position.
  2793. *
  2794. * @func
  2795. * @memberOf R
  2796. * @since v0.1.0
  2797. * @category List
  2798. * @sig Filterable f => (a -> Boolean) -> f a -> f a
  2799. * @param {Function} pred
  2800. * @param {Array} filterable
  2801. * @return {Array} Filterable
  2802. * @see R.reject, R.transduce, R.addIndex
  2803. * @example
  2804. *
  2805. * const isEven = n => n % 2 === 0;
  2806. *
  2807. * R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4]
  2808. *
  2809. * R.filter(isEven, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4}
  2810. */
  2811. var filter = _curry2(_dispatchable(['filter'], _xfilter, function(pred, filterable) {
  2812. return (
  2813. _isObject(filterable) ?
  2814. _reduce(function(acc, key) {
  2815. if (pred(filterable[key])) {
  2816. acc[key] = filterable[key];
  2817. }
  2818. return acc;
  2819. }, {}, keys(filterable)) :
  2820. // else
  2821. _filter(pred, filterable)
  2822. );
  2823. }));
  2824. /**
  2825. * The complement of [`filter`](#filter).
  2826. *
  2827. * Acts as a transducer if a transformer is given in list position. Filterable
  2828. * objects include plain objects or any object that has a filter method such
  2829. * as `Array`.
  2830. *
  2831. * @func
  2832. * @memberOf R
  2833. * @since v0.1.0
  2834. * @category List
  2835. * @sig Filterable f => (a -> Boolean) -> f a -> f a
  2836. * @param {Function} pred
  2837. * @param {Array} filterable
  2838. * @return {Array}
  2839. * @see R.filter, R.transduce, R.addIndex
  2840. * @example
  2841. *
  2842. * const isOdd = (n) => n % 2 === 1;
  2843. *
  2844. * R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4]
  2845. *
  2846. * R.reject(isOdd, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4}
  2847. */
  2848. var reject = _curry2(function reject(pred, filterable) {
  2849. return filter(_complement(pred), filterable);
  2850. });
  2851. function _toString(x, seen) {
  2852. var recur = function recur(y) {
  2853. var xs = seen.concat([x]);
  2854. return _includes(y, xs) ? '<Circular>' : _toString(y, xs);
  2855. };
  2856. // mapPairs :: (Object, [String]) -> [String]
  2857. var mapPairs = function(obj, keys$$1) {
  2858. return _map(function(k) { return _quote(k) + ': ' + recur(obj[k]); }, keys$$1.slice().sort());
  2859. };
  2860. switch (Object.prototype.toString.call(x)) {
  2861. case '[object Arguments]':
  2862. return '(function() { return arguments; }(' + _map(recur, x).join(', ') + '))';
  2863. case '[object Array]':
  2864. return '[' + _map(recur, x).concat(mapPairs(x, reject(function(k) { return /^\d+$/.test(k); }, keys(x)))).join(', ') + ']';
  2865. case '[object Boolean]':
  2866. return typeof x === 'object' ? 'new Boolean(' + recur(x.valueOf()) + ')' : x.toString();
  2867. case '[object Date]':
  2868. return 'new Date(' + (isNaN(x.valueOf()) ? recur(NaN) : _quote(_toISOString(x))) + ')';
  2869. case '[object Null]':
  2870. return 'null';
  2871. case '[object Number]':
  2872. return typeof x === 'object' ? 'new Number(' + recur(x.valueOf()) + ')' : 1 / x === -Infinity ? '-0' : x.toString(10);
  2873. case '[object String]':
  2874. return typeof x === 'object' ? 'new String(' + recur(x.valueOf()) + ')' : _quote(x);
  2875. case '[object Undefined]':
  2876. return 'undefined';
  2877. default:
  2878. if (typeof x.toString === 'function') {
  2879. var repr = x.toString();
  2880. if (repr !== '[object Object]') {
  2881. return repr;
  2882. }
  2883. }
  2884. return '{' + mapPairs(x, keys(x)).join(', ') + '}';
  2885. }
  2886. }
  2887. /**
  2888. * Returns the string representation of the given value. `eval`'ing the output
  2889. * should result in a value equivalent to the input value. Many of the built-in
  2890. * `toString` methods do not satisfy this requirement.
  2891. *
  2892. * If the given value is an `[object Object]` with a `toString` method other
  2893. * than `Object.prototype.toString`, this method is invoked with no arguments
  2894. * to produce the return value. This means user-defined constructor functions
  2895. * can provide a suitable `toString` method. For example:
  2896. *
  2897. * function Point(x, y) {
  2898. * this.x = x;
  2899. * this.y = y;
  2900. * }
  2901. *
  2902. * Point.prototype.toString = function() {
  2903. * return 'new Point(' + this.x + ', ' + this.y + ')';
  2904. * };
  2905. *
  2906. * R.toString(new Point(1, 2)); //=> 'new Point(1, 2)'
  2907. *
  2908. * @func
  2909. * @memberOf R
  2910. * @since v0.14.0
  2911. * @category String
  2912. * @sig * -> String
  2913. * @param {*} val
  2914. * @return {String}
  2915. * @example
  2916. *
  2917. * R.toString(42); //=> '42'
  2918. * R.toString('abc'); //=> '"abc"'
  2919. * R.toString([1, 2, 3]); //=> '[1, 2, 3]'
  2920. * R.toString({foo: 1, bar: 2, baz: 3}); //=> '{"bar": 2, "baz": 3, "foo": 1}'
  2921. * R.toString(new Date('2001-02-03T04:05:06Z')); //=> 'new Date("2001-02-03T04:05:06.000Z")'
  2922. */
  2923. var toString$1 = _curry1(function toString(val) { return _toString(val, []); });
  2924. /**
  2925. * Returns the result of concatenating the given lists or strings.
  2926. *
  2927. * Note: `R.concat` expects both arguments to be of the same type,
  2928. * unlike the native `Array.prototype.concat` method. It will throw
  2929. * an error if you `concat` an Array with a non-Array value.
  2930. *
  2931. * Dispatches to the `concat` method of the first argument, if present.
  2932. * Can also concatenate two members of a [fantasy-land
  2933. * compatible semigroup](https://github.com/fantasyland/fantasy-land#semigroup).
  2934. *
  2935. * @func
  2936. * @memberOf R
  2937. * @since v0.1.0
  2938. * @category List
  2939. * @sig [a] -> [a] -> [a]
  2940. * @sig String -> String -> String
  2941. * @param {Array|String} firstList The first list
  2942. * @param {Array|String} secondList The second list
  2943. * @return {Array|String} A list consisting of the elements of `firstList` followed by the elements of
  2944. * `secondList`.
  2945. *
  2946. * @example
  2947. *
  2948. * R.concat('ABC', 'DEF'); // 'ABCDEF'
  2949. * R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]
  2950. * R.concat([], []); //=> []
  2951. */
  2952. var concat = _curry2(function concat(a, b) {
  2953. if (_isArray(a)) {
  2954. if (_isArray(b)) {
  2955. return a.concat(b);
  2956. }
  2957. throw new TypeError(toString$1(b) + ' is not an array');
  2958. }
  2959. if (_isString(a)) {
  2960. if (_isString(b)) {
  2961. return a + b;
  2962. }
  2963. throw new TypeError(toString$1(b) + ' is not a string');
  2964. }
  2965. if (a != null && _isFunction(a['fantasy-land/concat'])) {
  2966. return a['fantasy-land/concat'](b);
  2967. }
  2968. if (a != null && _isFunction(a.concat)) {
  2969. return a.concat(b);
  2970. }
  2971. throw new TypeError(toString$1(a) + ' does not have a method named "concat" or "fantasy-land/concat"');
  2972. });
  2973. /**
  2974. * Returns a function, `fn`, which encapsulates `if/else, if/else, ...` logic.
  2975. * `R.cond` takes a list of [predicate, transformer] pairs. All of the arguments
  2976. * to `fn` are applied to each of the predicates in turn until one returns a
  2977. * "truthy" value, at which point `fn` returns the result of applying its
  2978. * arguments to the corresponding transformer. If none of the predicates
  2979. * matches, `fn` returns undefined.
  2980. *
  2981. * @func
  2982. * @memberOf R
  2983. * @since v0.6.0
  2984. * @category Logic
  2985. * @sig [[(*... -> Boolean),(*... -> *)]] -> (*... -> *)
  2986. * @param {Array} pairs A list of [predicate, transformer]
  2987. * @return {Function}
  2988. * @see R.ifElse, R.unless, R.when
  2989. * @example
  2990. *
  2991. * const fn = R.cond([
  2992. * [R.equals(0), R.always('water freezes at 0°C')],
  2993. * [R.equals(100), R.always('water boils at 100°C')],
  2994. * [R.T, temp => 'nothing special happens at ' + temp + '°C']
  2995. * ]);
  2996. * fn(0); //=> 'water freezes at 0°C'
  2997. * fn(50); //=> 'nothing special happens at 50°C'
  2998. * fn(100); //=> 'water boils at 100°C'
  2999. */
  3000. var cond = _curry1(function cond(pairs) {
  3001. var arity = reduce(
  3002. max,
  3003. 0,
  3004. map(function(pair) { return pair[0].length; }, pairs)
  3005. );
  3006. return _arity(arity, function() {
  3007. var idx = 0;
  3008. while (idx < pairs.length) {
  3009. if (pairs[idx][0].apply(this, arguments)) {
  3010. return pairs[idx][1].apply(this, arguments);
  3011. }
  3012. idx += 1;
  3013. }
  3014. });
  3015. });
  3016. /**
  3017. * Wraps a constructor function inside a curried function that can be called
  3018. * with the same arguments and returns the same type. The arity of the function
  3019. * returned is specified to allow using variadic constructor functions.
  3020. *
  3021. * @func
  3022. * @memberOf R
  3023. * @since v0.4.0
  3024. * @category Function
  3025. * @sig Number -> (* -> {*}) -> (* -> {*})
  3026. * @param {Number} n The arity of the constructor function.
  3027. * @param {Function} Fn The constructor function to wrap.
  3028. * @return {Function} A wrapped, curried constructor function.
  3029. * @example
  3030. *
  3031. * // Variadic Constructor function
  3032. * function Salad() {
  3033. * this.ingredients = arguments;
  3034. * }
  3035. *
  3036. * Salad.prototype.recipe = function() {
  3037. * const instructions = R.map(ingredient => 'Add a dollop of ' + ingredient, this.ingredients);
  3038. * return R.join('\n', instructions);
  3039. * };
  3040. *
  3041. * const ThreeLayerSalad = R.constructN(3, Salad);
  3042. *
  3043. * // Notice we no longer need the 'new' keyword, and the constructor is curried for 3 arguments.
  3044. * const salad = ThreeLayerSalad('Mayonnaise')('Potato Chips')('Ketchup');
  3045. *
  3046. * console.log(salad.recipe());
  3047. * // Add a dollop of Mayonnaise
  3048. * // Add a dollop of Potato Chips
  3049. * // Add a dollop of Ketchup
  3050. */
  3051. var constructN = _curry2(function constructN(n, Fn) {
  3052. if (n > 10) {
  3053. throw new Error('Constructor with greater than ten arguments');
  3054. }
  3055. if (n === 0) {
  3056. return function() { return new Fn(); };
  3057. }
  3058. return curry(nAry(n, function($0, $1, $2, $3, $4, $5, $6, $7, $8, $9) {
  3059. switch (arguments.length) {
  3060. case 1: return new Fn($0);
  3061. case 2: return new Fn($0, $1);
  3062. case 3: return new Fn($0, $1, $2);
  3063. case 4: return new Fn($0, $1, $2, $3);
  3064. case 5: return new Fn($0, $1, $2, $3, $4);
  3065. case 6: return new Fn($0, $1, $2, $3, $4, $5);
  3066. case 7: return new Fn($0, $1, $2, $3, $4, $5, $6);
  3067. case 8: return new Fn($0, $1, $2, $3, $4, $5, $6, $7);
  3068. case 9: return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8);
  3069. case 10: return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8, $9);
  3070. }
  3071. }));
  3072. });
  3073. /**
  3074. * Wraps a constructor function inside a curried function that can be called
  3075. * with the same arguments and returns the same type.
  3076. *
  3077. * @func
  3078. * @memberOf R
  3079. * @since v0.1.0
  3080. * @category Function
  3081. * @sig (* -> {*}) -> (* -> {*})
  3082. * @param {Function} fn The constructor function to wrap.
  3083. * @return {Function} A wrapped, curried constructor function.
  3084. * @see R.invoker
  3085. * @example
  3086. *
  3087. * // Constructor function
  3088. * function Animal(kind) {
  3089. * this.kind = kind;
  3090. * };
  3091. * Animal.prototype.sighting = function() {
  3092. * return "It's a " + this.kind + "!";
  3093. * }
  3094. *
  3095. * const AnimalConstructor = R.construct(Animal)
  3096. *
  3097. * // Notice we no longer need the 'new' keyword:
  3098. * AnimalConstructor('Pig'); //=> {"kind": "Pig", "sighting": function (){...}};
  3099. *
  3100. * const animalTypes = ["Lion", "Tiger", "Bear"];
  3101. * const animalSighting = R.invoker(0, 'sighting');
  3102. * const sightNewAnimal = R.compose(animalSighting, AnimalConstructor);
  3103. * R.map(sightNewAnimal, animalTypes); //=> ["It's a Lion!", "It's a Tiger!", "It's a Bear!"]
  3104. */
  3105. var construct = _curry1(function construct(Fn) {
  3106. return constructN(Fn.length, Fn);
  3107. });
  3108. /**
  3109. * Returns `true` if the specified value is equal, in [`R.equals`](#equals)
  3110. * terms, to at least one element of the given list; `false` otherwise.
  3111. * Works also with strings.
  3112. *
  3113. * @func
  3114. * @memberOf R
  3115. * @since v0.1.0
  3116. * @category List
  3117. * @sig a -> [a] -> Boolean
  3118. * @param {Object} a The item to compare against.
  3119. * @param {Array} list The array to consider.
  3120. * @return {Boolean} `true` if an equivalent item is in the list, `false` otherwise.
  3121. * @see R.includes
  3122. * @deprecated since v0.26.0
  3123. * @example
  3124. *
  3125. * R.contains(3, [1, 2, 3]); //=> true
  3126. * R.contains(4, [1, 2, 3]); //=> false
  3127. * R.contains({ name: 'Fred' }, [{ name: 'Fred' }]); //=> true
  3128. * R.contains([42], [[42]]); //=> true
  3129. * R.contains('ba', 'banana'); //=>true
  3130. */
  3131. var contains$1 = _curry2(_includes);
  3132. /**
  3133. * Accepts a converging function and a list of branching functions and returns
  3134. * a new function. The arity of the new function is the same as the arity of
  3135. * the longest branching function. When invoked, this new function is applied
  3136. * to some arguments, and each branching function is applied to those same
  3137. * arguments. The results of each branching function are passed as arguments
  3138. * to the converging function to produce the return value.
  3139. *
  3140. * @func
  3141. * @memberOf R
  3142. * @since v0.4.2
  3143. * @category Function
  3144. * @sig ((x1, x2, ...) -> z) -> [((a, b, ...) -> x1), ((a, b, ...) -> x2), ...] -> (a -> b -> ... -> z)
  3145. * @param {Function} after A function. `after` will be invoked with the return values of
  3146. * `fn1` and `fn2` as its arguments.
  3147. * @param {Array} functions A list of functions.
  3148. * @return {Function} A new function.
  3149. * @see R.useWith
  3150. * @example
  3151. *
  3152. * const average = R.converge(R.divide, [R.sum, R.length])
  3153. * average([1, 2, 3, 4, 5, 6, 7]) //=> 4
  3154. *
  3155. * const strangeConcat = R.converge(R.concat, [R.toUpper, R.toLower])
  3156. * strangeConcat("Yodel") //=> "YODELyodel"
  3157. *
  3158. * @symb R.converge(f, [g, h])(a, b) = f(g(a, b), h(a, b))
  3159. */
  3160. var converge = _curry2(function converge(after, fns) {
  3161. return curryN(reduce(max, 0, pluck('length', fns)), function() {
  3162. var args = arguments;
  3163. var context = this;
  3164. return after.apply(context, _map(function(fn) {
  3165. return fn.apply(context, args);
  3166. }, fns));
  3167. });
  3168. });
  3169. function XReduceBy(valueFn, valueAcc, keyFn, xf) {
  3170. this.valueFn = valueFn;
  3171. this.valueAcc = valueAcc;
  3172. this.keyFn = keyFn;
  3173. this.xf = xf;
  3174. this.inputs = {};
  3175. }
  3176. XReduceBy.prototype['@@transducer/init'] = _xfBase.init;
  3177. XReduceBy.prototype['@@transducer/result'] = function(result) {
  3178. var key;
  3179. for (key in this.inputs) {
  3180. if (_has(key, this.inputs)) {
  3181. result = this.xf['@@transducer/step'](result, this.inputs[key]);
  3182. if (result['@@transducer/reduced']) {
  3183. result = result['@@transducer/value'];
  3184. break;
  3185. }
  3186. }
  3187. }
  3188. this.inputs = null;
  3189. return this.xf['@@transducer/result'](result);
  3190. };
  3191. XReduceBy.prototype['@@transducer/step'] = function(result, input) {
  3192. var key = this.keyFn(input);
  3193. this.inputs[key] = this.inputs[key] || [key, this.valueAcc];
  3194. this.inputs[key][1] = this.valueFn(this.inputs[key][1], input);
  3195. return result;
  3196. };
  3197. var _xreduceBy = _curryN(4, [],
  3198. function _xreduceBy(valueFn, valueAcc, keyFn, xf) {
  3199. return new XReduceBy(valueFn, valueAcc, keyFn, xf);
  3200. }
  3201. );
  3202. /**
  3203. * Groups the elements of the list according to the result of calling
  3204. * the String-returning function `keyFn` on each element and reduces the elements
  3205. * of each group to a single value via the reducer function `valueFn`.
  3206. *
  3207. * This function is basically a more general [`groupBy`](#groupBy) function.
  3208. *
  3209. * Acts as a transducer if a transformer is given in list position.
  3210. *
  3211. * @func
  3212. * @memberOf R
  3213. * @since v0.20.0
  3214. * @category List
  3215. * @sig ((a, b) -> a) -> a -> (b -> String) -> [b] -> {String: a}
  3216. * @param {Function} valueFn The function that reduces the elements of each group to a single
  3217. * value. Receives two values, accumulator for a particular group and the current element.
  3218. * @param {*} acc The (initial) accumulator value for each group.
  3219. * @param {Function} keyFn The function that maps the list's element into a key.
  3220. * @param {Array} list The array to group.
  3221. * @return {Object} An object with the output of `keyFn` for keys, mapped to the output of
  3222. * `valueFn` for elements which produced that key when passed to `keyFn`.
  3223. * @see R.groupBy, R.reduce
  3224. * @example
  3225. *
  3226. * const groupNames = (acc, {name}) => acc.concat(name)
  3227. * const toGrade = ({score}) =>
  3228. * score < 65 ? 'F' :
  3229. * score < 70 ? 'D' :
  3230. * score < 80 ? 'C' :
  3231. * score < 90 ? 'B' : 'A'
  3232. *
  3233. * var students = [
  3234. * {name: 'Abby', score: 83},
  3235. * {name: 'Bart', score: 62},
  3236. * {name: 'Curt', score: 88},
  3237. * {name: 'Dora', score: 92},
  3238. * ]
  3239. *
  3240. * reduceBy(groupNames, [], toGrade, students)
  3241. * //=> {"A": ["Dora"], "B": ["Abby", "Curt"], "F": ["Bart"]}
  3242. */
  3243. var reduceBy = _curryN(4, [], _dispatchable([], _xreduceBy,
  3244. function reduceBy(valueFn, valueAcc, keyFn, list) {
  3245. return _reduce(function(acc, elt) {
  3246. var key = keyFn(elt);
  3247. acc[key] = valueFn(_has(key, acc) ? acc[key] : _clone(valueAcc, [], [], false), elt);
  3248. return acc;
  3249. }, {}, list);
  3250. }));
  3251. /**
  3252. * Counts the elements of a list according to how many match each value of a
  3253. * key generated by the supplied function. Returns an object mapping the keys
  3254. * produced by `fn` to the number of occurrences in the list. Note that all
  3255. * keys are coerced to strings because of how JavaScript objects work.
  3256. *
  3257. * Acts as a transducer if a transformer is given in list position.
  3258. *
  3259. * @func
  3260. * @memberOf R
  3261. * @since v0.1.0
  3262. * @category Relation
  3263. * @sig (a -> String) -> [a] -> {*}
  3264. * @param {Function} fn The function used to map values to keys.
  3265. * @param {Array} list The list to count elements from.
  3266. * @return {Object} An object mapping keys to number of occurrences in the list.
  3267. * @example
  3268. *
  3269. * const numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2];
  3270. * R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1}
  3271. *
  3272. * const letters = ['a', 'b', 'A', 'a', 'B', 'c'];
  3273. * R.countBy(R.toLower)(letters); //=> {'a': 3, 'b': 2, 'c': 1}
  3274. */
  3275. var countBy = reduceBy(function(acc, elem) { return acc + 1; }, 0);
  3276. /**
  3277. * Decrements its argument.
  3278. *
  3279. * @func
  3280. * @memberOf R
  3281. * @since v0.9.0
  3282. * @category Math
  3283. * @sig Number -> Number
  3284. * @param {Number} n
  3285. * @return {Number} n - 1
  3286. * @see R.inc
  3287. * @example
  3288. *
  3289. * R.dec(42); //=> 41
  3290. */
  3291. var dec = add(-1);
  3292. /**
  3293. * Returns the second argument if it is not `null`, `undefined` or `NaN`;
  3294. * otherwise the first argument is returned.
  3295. *
  3296. * @func
  3297. * @memberOf R
  3298. * @since v0.10.0
  3299. * @category Logic
  3300. * @sig a -> b -> a | b
  3301. * @param {a} default The default value.
  3302. * @param {b} val `val` will be returned instead of `default` unless `val` is `null`, `undefined` or `NaN`.
  3303. * @return {*} The second value if it is not `null`, `undefined` or `NaN`, otherwise the default value
  3304. * @example
  3305. *
  3306. * const defaultTo42 = R.defaultTo(42);
  3307. *
  3308. * defaultTo42(null); //=> 42
  3309. * defaultTo42(undefined); //=> 42
  3310. * defaultTo42(false); //=> false
  3311. * defaultTo42('Ramda'); //=> 'Ramda'
  3312. * // parseInt('string') results in NaN
  3313. * defaultTo42(parseInt('string')); //=> 42
  3314. */
  3315. var defaultTo = _curry2(function defaultTo(d, v) {
  3316. return v == null || v !== v ? d : v;
  3317. });
  3318. /**
  3319. * Makes a descending comparator function out of a function that returns a value
  3320. * that can be compared with `<` and `>`.
  3321. *
  3322. * @func
  3323. * @memberOf R
  3324. * @since v0.23.0
  3325. * @category Function
  3326. * @sig Ord b => (a -> b) -> a -> a -> Number
  3327. * @param {Function} fn A function of arity one that returns a value that can be compared
  3328. * @param {*} a The first item to be compared.
  3329. * @param {*} b The second item to be compared.
  3330. * @return {Number} `-1` if fn(a) > fn(b), `1` if fn(b) > fn(a), otherwise `0`
  3331. * @see R.ascend
  3332. * @example
  3333. *
  3334. * const byAge = R.descend(R.prop('age'));
  3335. * const people = [
  3336. * { name: 'Emma', age: 70 },
  3337. * { name: 'Peter', age: 78 },
  3338. * { name: 'Mikhail', age: 62 },
  3339. * ];
  3340. * const peopleByOldestFirst = R.sort(byAge, people);
  3341. * //=> [{ name: 'Peter', age: 78 }, { name: 'Emma', age: 70 }, { name: 'Mikhail', age: 62 }]
  3342. */
  3343. var descend = _curry3(function descend(fn, a, b) {
  3344. var aa = fn(a);
  3345. var bb = fn(b);
  3346. return aa > bb ? -1 : aa < bb ? 1 : 0;
  3347. });
  3348. function _Set() {
  3349. /* globals Set */
  3350. this._nativeSet = typeof Set === 'function' ? new Set() : null;
  3351. this._items = {};
  3352. }
  3353. // until we figure out why jsdoc chokes on this
  3354. // @param item The item to add to the Set
  3355. // @returns {boolean} true if the item did not exist prior, otherwise false
  3356. //
  3357. _Set.prototype.add = function(item) {
  3358. return !hasOrAdd(item, true, this);
  3359. };
  3360. //
  3361. // @param item The item to check for existence in the Set
  3362. // @returns {boolean} true if the item exists in the Set, otherwise false
  3363. //
  3364. _Set.prototype.has = function(item) {
  3365. return hasOrAdd(item, false, this);
  3366. };
  3367. //
  3368. // Combines the logic for checking whether an item is a member of the set and
  3369. // for adding a new item to the set.
  3370. //
  3371. // @param item The item to check or add to the Set instance.
  3372. // @param shouldAdd If true, the item will be added to the set if it doesn't
  3373. // already exist.
  3374. // @param set The set instance to check or add to.
  3375. // @return {boolean} true if the item already existed, otherwise false.
  3376. //
  3377. function hasOrAdd(item, shouldAdd, set) {
  3378. var type = typeof item;
  3379. var prevSize, newSize;
  3380. switch (type) {
  3381. case 'string':
  3382. case 'number':
  3383. // distinguish between +0 and -0
  3384. if (item === 0 && 1 / item === -Infinity) {
  3385. if (set._items['-0']) {
  3386. return true;
  3387. } else {
  3388. if (shouldAdd) {
  3389. set._items['-0'] = true;
  3390. }
  3391. return false;
  3392. }
  3393. }
  3394. // these types can all utilise the native Set
  3395. if (set._nativeSet !== null) {
  3396. if (shouldAdd) {
  3397. prevSize = set._nativeSet.size;
  3398. set._nativeSet.add(item);
  3399. newSize = set._nativeSet.size;
  3400. return newSize === prevSize;
  3401. } else {
  3402. return set._nativeSet.has(item);
  3403. }
  3404. } else {
  3405. if (!(type in set._items)) {
  3406. if (shouldAdd) {
  3407. set._items[type] = {};
  3408. set._items[type][item] = true;
  3409. }
  3410. return false;
  3411. } else if (item in set._items[type]) {
  3412. return true;
  3413. } else {
  3414. if (shouldAdd) {
  3415. set._items[type][item] = true;
  3416. }
  3417. return false;
  3418. }
  3419. }
  3420. case 'boolean':
  3421. // set._items['boolean'] holds a two element array
  3422. // representing [ falseExists, trueExists ]
  3423. if (type in set._items) {
  3424. var bIdx = item ? 1 : 0;
  3425. if (set._items[type][bIdx]) {
  3426. return true;
  3427. } else {
  3428. if (shouldAdd) {
  3429. set._items[type][bIdx] = true;
  3430. }
  3431. return false;
  3432. }
  3433. } else {
  3434. if (shouldAdd) {
  3435. set._items[type] = item ? [false, true] : [true, false];
  3436. }
  3437. return false;
  3438. }
  3439. case 'function':
  3440. // compare functions for reference equality
  3441. if (set._nativeSet !== null) {
  3442. if (shouldAdd) {
  3443. prevSize = set._nativeSet.size;
  3444. set._nativeSet.add(item);
  3445. newSize = set._nativeSet.size;
  3446. return newSize === prevSize;
  3447. } else {
  3448. return set._nativeSet.has(item);
  3449. }
  3450. } else {
  3451. if (!(type in set._items)) {
  3452. if (shouldAdd) {
  3453. set._items[type] = [item];
  3454. }
  3455. return false;
  3456. }
  3457. if (!_includes(item, set._items[type])) {
  3458. if (shouldAdd) {
  3459. set._items[type].push(item);
  3460. }
  3461. return false;
  3462. }
  3463. return true;
  3464. }
  3465. case 'undefined':
  3466. if (set._items[type]) {
  3467. return true;
  3468. } else {
  3469. if (shouldAdd) {
  3470. set._items[type] = true;
  3471. }
  3472. return false;
  3473. }
  3474. case 'object':
  3475. if (item === null) {
  3476. if (!set._items['null']) {
  3477. if (shouldAdd) {
  3478. set._items['null'] = true;
  3479. }
  3480. return false;
  3481. }
  3482. return true;
  3483. }
  3484. /* falls through */
  3485. default:
  3486. // reduce the search size of heterogeneous sets by creating buckets
  3487. // for each type.
  3488. type = Object.prototype.toString.call(item);
  3489. if (!(type in set._items)) {
  3490. if (shouldAdd) {
  3491. set._items[type] = [item];
  3492. }
  3493. return false;
  3494. }
  3495. // scan through all previously applied items
  3496. if (!_includes(item, set._items[type])) {
  3497. if (shouldAdd) {
  3498. set._items[type].push(item);
  3499. }
  3500. return false;
  3501. }
  3502. return true;
  3503. }
  3504. }
  3505. /**
  3506. * Finds the set (i.e. no duplicates) of all elements in the first list not
  3507. * contained in the second list. Objects and Arrays are compared in terms of
  3508. * value equality, not reference equality.
  3509. *
  3510. * @func
  3511. * @memberOf R
  3512. * @since v0.1.0
  3513. * @category Relation
  3514. * @sig [*] -> [*] -> [*]
  3515. * @param {Array} list1 The first list.
  3516. * @param {Array} list2 The second list.
  3517. * @return {Array} The elements in `list1` that are not in `list2`.
  3518. * @see R.differenceWith, R.symmetricDifference, R.symmetricDifferenceWith, R.without
  3519. * @example
  3520. *
  3521. * R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2]
  3522. * R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5]
  3523. * R.difference([{a: 1}, {b: 2}], [{a: 1}, {c: 3}]) //=> [{b: 2}]
  3524. */
  3525. var difference = _curry2(function difference(first, second) {
  3526. var out = [];
  3527. var idx = 0;
  3528. var firstLen = first.length;
  3529. var secondLen = second.length;
  3530. var toFilterOut = new _Set();
  3531. for (var i = 0; i < secondLen; i += 1) {
  3532. toFilterOut.add(second[i]);
  3533. }
  3534. while (idx < firstLen) {
  3535. if (toFilterOut.add(first[idx])) {
  3536. out[out.length] = first[idx];
  3537. }
  3538. idx += 1;
  3539. }
  3540. return out;
  3541. });
  3542. /**
  3543. * Finds the set (i.e. no duplicates) of all elements in the first list not
  3544. * contained in the second list. Duplication is determined according to the
  3545. * value returned by applying the supplied predicate to two list elements.
  3546. *
  3547. * @func
  3548. * @memberOf R
  3549. * @since v0.1.0
  3550. * @category Relation
  3551. * @sig ((a, a) -> Boolean) -> [a] -> [a] -> [a]
  3552. * @param {Function} pred A predicate used to test whether two items are equal.
  3553. * @param {Array} list1 The first list.
  3554. * @param {Array} list2 The second list.
  3555. * @return {Array} The elements in `list1` that are not in `list2`.
  3556. * @see R.difference, R.symmetricDifference, R.symmetricDifferenceWith
  3557. * @example
  3558. *
  3559. * const cmp = (x, y) => x.a === y.a;
  3560. * const l1 = [{a: 1}, {a: 2}, {a: 3}];
  3561. * const l2 = [{a: 3}, {a: 4}];
  3562. * R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}]
  3563. */
  3564. var differenceWith = _curry3(function differenceWith(pred, first, second) {
  3565. var out = [];
  3566. var idx = 0;
  3567. var firstLen = first.length;
  3568. while (idx < firstLen) {
  3569. if (!_includesWith(pred, first[idx], second) &&
  3570. !_includesWith(pred, first[idx], out)) {
  3571. out.push(first[idx]);
  3572. }
  3573. idx += 1;
  3574. }
  3575. return out;
  3576. });
  3577. /**
  3578. * Returns a new object that does not contain a `prop` property.
  3579. *
  3580. * @func
  3581. * @memberOf R
  3582. * @since v0.10.0
  3583. * @category Object
  3584. * @sig String -> {k: v} -> {k: v}
  3585. * @param {String} prop The name of the property to dissociate
  3586. * @param {Object} obj The object to clone
  3587. * @return {Object} A new object equivalent to the original but without the specified property
  3588. * @see R.assoc, R.omit
  3589. * @example
  3590. *
  3591. * R.dissoc('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3}
  3592. */
  3593. var dissoc = _curry2(function dissoc(prop, obj) {
  3594. var result = {};
  3595. for (var p in obj) {
  3596. result[p] = obj[p];
  3597. }
  3598. delete result[prop];
  3599. return result;
  3600. });
  3601. /**
  3602. * Removes the sub-list of `list` starting at index `start` and containing
  3603. * `count` elements. _Note that this is not destructive_: it returns a copy of
  3604. * the list with the changes.
  3605. * <small>No lists have been harmed in the application of this function.</small>
  3606. *
  3607. * @func
  3608. * @memberOf R
  3609. * @since v0.2.2
  3610. * @category List
  3611. * @sig Number -> Number -> [a] -> [a]
  3612. * @param {Number} start The position to start removing elements
  3613. * @param {Number} count The number of elements to remove
  3614. * @param {Array} list The list to remove from
  3615. * @return {Array} A new Array with `count` elements from `start` removed.
  3616. * @see R.without
  3617. * @example
  3618. *
  3619. * R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8]
  3620. */
  3621. var remove = _curry3(function remove(start, count, list) {
  3622. var result = Array.prototype.slice.call(list, 0);
  3623. result.splice(start, count);
  3624. return result;
  3625. });
  3626. /**
  3627. * Returns a new copy of the array with the element at the provided index
  3628. * replaced with the given value.
  3629. *
  3630. * @func
  3631. * @memberOf R
  3632. * @since v0.14.0
  3633. * @category List
  3634. * @sig Number -> a -> [a] -> [a]
  3635. * @param {Number} idx The index to update.
  3636. * @param {*} x The value to exist at the given index of the returned array.
  3637. * @param {Array|Arguments} list The source array-like object to be updated.
  3638. * @return {Array} A copy of `list` with the value at index `idx` replaced with `x`.
  3639. * @see R.adjust
  3640. * @example
  3641. *
  3642. * R.update(1, '_', ['a', 'b', 'c']); //=> ['a', '_', 'c']
  3643. * R.update(-1, '_', ['a', 'b', 'c']); //=> ['a', 'b', '_']
  3644. * @symb R.update(-1, a, [b, c]) = [b, a]
  3645. * @symb R.update(0, a, [b, c]) = [a, c]
  3646. * @symb R.update(1, a, [b, c]) = [b, a]
  3647. */
  3648. var update = _curry3(function update(idx, x, list) {
  3649. return adjust(idx, always(x), list);
  3650. });
  3651. /**
  3652. * Makes a shallow clone of an object, omitting the property at the given path.
  3653. * Note that this copies and flattens prototype properties onto the new object
  3654. * as well. All non-primitive properties are copied by reference.
  3655. *
  3656. * @func
  3657. * @memberOf R
  3658. * @since v0.11.0
  3659. * @category Object
  3660. * @typedefn Idx = String | Int
  3661. * @sig [Idx] -> {k: v} -> {k: v}
  3662. * @param {Array} path The path to the value to omit
  3663. * @param {Object} obj The object to clone
  3664. * @return {Object} A new object without the property at path
  3665. * @see R.assocPath
  3666. * @example
  3667. *
  3668. * R.dissocPath(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}}
  3669. */
  3670. var dissocPath = _curry2(function dissocPath(path, obj) {
  3671. switch (path.length) {
  3672. case 0:
  3673. return obj;
  3674. case 1:
  3675. return _isInteger(path[0]) && _isArray(obj) ? remove(path[0], 1, obj) : dissoc(path[0], obj);
  3676. default:
  3677. var head = path[0];
  3678. var tail = Array.prototype.slice.call(path, 1);
  3679. if (obj[head] == null) {
  3680. return obj;
  3681. } else if (_isInteger(head) && _isArray(obj)) {
  3682. return update(head, dissocPath(tail, obj[head]), obj);
  3683. } else {
  3684. return assoc(head, dissocPath(tail, obj[head]), obj);
  3685. }
  3686. }
  3687. });
  3688. /**
  3689. * Divides two numbers. Equivalent to `a / b`.
  3690. *
  3691. * @func
  3692. * @memberOf R
  3693. * @since v0.1.0
  3694. * @category Math
  3695. * @sig Number -> Number -> Number
  3696. * @param {Number} a The first value.
  3697. * @param {Number} b The second value.
  3698. * @return {Number} The result of `a / b`.
  3699. * @see R.multiply
  3700. * @example
  3701. *
  3702. * R.divide(71, 100); //=> 0.71
  3703. *
  3704. * const half = R.divide(R.__, 2);
  3705. * half(42); //=> 21
  3706. *
  3707. * const reciprocal = R.divide(1);
  3708. * reciprocal(4); //=> 0.25
  3709. */
  3710. var divide = _curry2(function divide(a, b) { return a / b; });
  3711. function XDrop(n, xf) {
  3712. this.xf = xf;
  3713. this.n = n;
  3714. }
  3715. XDrop.prototype['@@transducer/init'] = _xfBase.init;
  3716. XDrop.prototype['@@transducer/result'] = _xfBase.result;
  3717. XDrop.prototype['@@transducer/step'] = function(result, input) {
  3718. if (this.n > 0) {
  3719. this.n -= 1;
  3720. return result;
  3721. }
  3722. return this.xf['@@transducer/step'](result, input);
  3723. };
  3724. var _xdrop = _curry2(function _xdrop(n, xf) { return new XDrop(n, xf); });
  3725. /**
  3726. * Returns all but the first `n` elements of the given list, string, or
  3727. * transducer/transformer (or object with a `drop` method).
  3728. *
  3729. * Dispatches to the `drop` method of the second argument, if present.
  3730. *
  3731. * @func
  3732. * @memberOf R
  3733. * @since v0.1.0
  3734. * @category List
  3735. * @sig Number -> [a] -> [a]
  3736. * @sig Number -> String -> String
  3737. * @param {Number} n
  3738. * @param {*} list
  3739. * @return {*} A copy of list without the first `n` elements
  3740. * @see R.take, R.transduce, R.dropLast, R.dropWhile
  3741. * @example
  3742. *
  3743. * R.drop(1, ['foo', 'bar', 'baz']); //=> ['bar', 'baz']
  3744. * R.drop(2, ['foo', 'bar', 'baz']); //=> ['baz']
  3745. * R.drop(3, ['foo', 'bar', 'baz']); //=> []
  3746. * R.drop(4, ['foo', 'bar', 'baz']); //=> []
  3747. * R.drop(3, 'ramda'); //=> 'da'
  3748. */
  3749. var drop = _curry2(_dispatchable(['drop'], _xdrop, function drop(n, xs) {
  3750. return slice(Math.max(0, n), Infinity, xs);
  3751. }));
  3752. function XTake(n, xf) {
  3753. this.xf = xf;
  3754. this.n = n;
  3755. this.i = 0;
  3756. }
  3757. XTake.prototype['@@transducer/init'] = _xfBase.init;
  3758. XTake.prototype['@@transducer/result'] = _xfBase.result;
  3759. XTake.prototype['@@transducer/step'] = function(result, input) {
  3760. this.i += 1;
  3761. var ret = this.n === 0 ? result : this.xf['@@transducer/step'](result, input);
  3762. return this.n >= 0 && this.i >= this.n ? _reduced(ret) : ret;
  3763. };
  3764. var _xtake = _curry2(function _xtake(n, xf) { return new XTake(n, xf); });
  3765. /**
  3766. * Returns the first `n` elements of the given list, string, or
  3767. * transducer/transformer (or object with a `take` method).
  3768. *
  3769. * Dispatches to the `take` method of the second argument, if present.
  3770. *
  3771. * @func
  3772. * @memberOf R
  3773. * @since v0.1.0
  3774. * @category List
  3775. * @sig Number -> [a] -> [a]
  3776. * @sig Number -> String -> String
  3777. * @param {Number} n
  3778. * @param {*} list
  3779. * @return {*}
  3780. * @see R.drop
  3781. * @example
  3782. *
  3783. * R.take(1, ['foo', 'bar', 'baz']); //=> ['foo']
  3784. * R.take(2, ['foo', 'bar', 'baz']); //=> ['foo', 'bar']
  3785. * R.take(3, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz']
  3786. * R.take(4, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz']
  3787. * R.take(3, 'ramda'); //=> 'ram'
  3788. *
  3789. * const personnel = [
  3790. * 'Dave Brubeck',
  3791. * 'Paul Desmond',
  3792. * 'Eugene Wright',
  3793. * 'Joe Morello',
  3794. * 'Gerry Mulligan',
  3795. * 'Bob Bates',
  3796. * 'Joe Dodge',
  3797. * 'Ron Crotty'
  3798. * ];
  3799. *
  3800. * const takeFive = R.take(5);
  3801. * takeFive(personnel);
  3802. * //=> ['Dave Brubeck', 'Paul Desmond', 'Eugene Wright', 'Joe Morello', 'Gerry Mulligan']
  3803. * @symb R.take(-1, [a, b]) = [a, b]
  3804. * @symb R.take(0, [a, b]) = []
  3805. * @symb R.take(1, [a, b]) = [a]
  3806. * @symb R.take(2, [a, b]) = [a, b]
  3807. */
  3808. var take = _curry2(_dispatchable(['take'], _xtake, function take(n, xs) {
  3809. return slice(0, n < 0 ? Infinity : n, xs);
  3810. }));
  3811. function dropLast(n, xs) {
  3812. return take(n < xs.length ? xs.length - n : 0, xs);
  3813. }
  3814. function XDropLast(n, xf) {
  3815. this.xf = xf;
  3816. this.pos = 0;
  3817. this.full = false;
  3818. this.acc = new Array(n);
  3819. }
  3820. XDropLast.prototype['@@transducer/init'] = _xfBase.init;
  3821. XDropLast.prototype['@@transducer/result'] = function(result) {
  3822. this.acc = null;
  3823. return this.xf['@@transducer/result'](result);
  3824. };
  3825. XDropLast.prototype['@@transducer/step'] = function(result, input) {
  3826. if (this.full) {
  3827. result = this.xf['@@transducer/step'](result, this.acc[this.pos]);
  3828. }
  3829. this.store(input);
  3830. return result;
  3831. };
  3832. XDropLast.prototype.store = function(input) {
  3833. this.acc[this.pos] = input;
  3834. this.pos += 1;
  3835. if (this.pos === this.acc.length) {
  3836. this.pos = 0;
  3837. this.full = true;
  3838. }
  3839. };
  3840. var _xdropLast = _curry2(function _xdropLast(n, xf) { return new XDropLast(n, xf); });
  3841. /**
  3842. * Returns a list containing all but the last `n` elements of the given `list`.
  3843. *
  3844. * Acts as a transducer if a transformer is given in list position.
  3845. *
  3846. * @func
  3847. * @memberOf R
  3848. * @since v0.16.0
  3849. * @category List
  3850. * @sig Number -> [a] -> [a]
  3851. * @sig Number -> String -> String
  3852. * @param {Number} n The number of elements of `list` to skip.
  3853. * @param {Array} list The list of elements to consider.
  3854. * @return {Array} A copy of the list with only the first `list.length - n` elements
  3855. * @see R.takeLast, R.drop, R.dropWhile, R.dropLastWhile
  3856. * @example
  3857. *
  3858. * R.dropLast(1, ['foo', 'bar', 'baz']); //=> ['foo', 'bar']
  3859. * R.dropLast(2, ['foo', 'bar', 'baz']); //=> ['foo']
  3860. * R.dropLast(3, ['foo', 'bar', 'baz']); //=> []
  3861. * R.dropLast(4, ['foo', 'bar', 'baz']); //=> []
  3862. * R.dropLast(3, 'ramda'); //=> 'ra'
  3863. */
  3864. var dropLast$1 = _curry2(_dispatchable([], _xdropLast, dropLast));
  3865. function dropLastWhile(pred, xs) {
  3866. var idx = xs.length - 1;
  3867. while (idx >= 0 && pred(xs[idx])) {
  3868. idx -= 1;
  3869. }
  3870. return slice(0, idx + 1, xs);
  3871. }
  3872. function XDropLastWhile(fn, xf) {
  3873. this.f = fn;
  3874. this.retained = [];
  3875. this.xf = xf;
  3876. }
  3877. XDropLastWhile.prototype['@@transducer/init'] = _xfBase.init;
  3878. XDropLastWhile.prototype['@@transducer/result'] = function(result) {
  3879. this.retained = null;
  3880. return this.xf['@@transducer/result'](result);
  3881. };
  3882. XDropLastWhile.prototype['@@transducer/step'] = function(result, input) {
  3883. return this.f(input)
  3884. ? this.retain(result, input)
  3885. : this.flush(result, input);
  3886. };
  3887. XDropLastWhile.prototype.flush = function(result, input) {
  3888. result = _reduce(
  3889. this.xf['@@transducer/step'],
  3890. result,
  3891. this.retained
  3892. );
  3893. this.retained = [];
  3894. return this.xf['@@transducer/step'](result, input);
  3895. };
  3896. XDropLastWhile.prototype.retain = function(result, input) {
  3897. this.retained.push(input);
  3898. return result;
  3899. };
  3900. var _xdropLastWhile = _curry2(function _xdropLastWhile(fn, xf) { return new XDropLastWhile(fn, xf); });
  3901. /**
  3902. * Returns a new list excluding all the tailing elements of a given list which
  3903. * satisfy the supplied predicate function. It passes each value from the right
  3904. * to the supplied predicate function, skipping elements until the predicate
  3905. * function returns a `falsy` value. The predicate function is applied to one argument:
  3906. * *(value)*.
  3907. *
  3908. * Acts as a transducer if a transformer is given in list position.
  3909. *
  3910. * @func
  3911. * @memberOf R
  3912. * @since v0.16.0
  3913. * @category List
  3914. * @sig (a -> Boolean) -> [a] -> [a]
  3915. * @sig (a -> Boolean) -> String -> String
  3916. * @param {Function} predicate The function to be called on each element
  3917. * @param {Array} xs The collection to iterate over.
  3918. * @return {Array} A new array without any trailing elements that return `falsy` values from the `predicate`.
  3919. * @see R.takeLastWhile, R.addIndex, R.drop, R.dropWhile
  3920. * @example
  3921. *
  3922. * const lteThree = x => x <= 3;
  3923. *
  3924. * R.dropLastWhile(lteThree, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3, 4]
  3925. *
  3926. * R.dropLastWhile(x => x !== 'd' , 'Ramda'); //=> 'Ramd'
  3927. */
  3928. var dropLastWhile$1 = _curry2(_dispatchable([], _xdropLastWhile, dropLastWhile));
  3929. function XDropRepeatsWith(pred, xf) {
  3930. this.xf = xf;
  3931. this.pred = pred;
  3932. this.lastValue = undefined;
  3933. this.seenFirstValue = false;
  3934. }
  3935. XDropRepeatsWith.prototype['@@transducer/init'] = _xfBase.init;
  3936. XDropRepeatsWith.prototype['@@transducer/result'] = _xfBase.result;
  3937. XDropRepeatsWith.prototype['@@transducer/step'] = function(result, input) {
  3938. var sameAsLast = false;
  3939. if (!this.seenFirstValue) {
  3940. this.seenFirstValue = true;
  3941. } else if (this.pred(this.lastValue, input)) {
  3942. sameAsLast = true;
  3943. }
  3944. this.lastValue = input;
  3945. return sameAsLast ? result : this.xf['@@transducer/step'](result, input);
  3946. };
  3947. var _xdropRepeatsWith = _curry2(function _xdropRepeatsWith(pred, xf) { return new XDropRepeatsWith(pred, xf); });
  3948. /**
  3949. * Returns the last element of the given list or string.
  3950. *
  3951. * @func
  3952. * @memberOf R
  3953. * @since v0.1.4
  3954. * @category List
  3955. * @sig [a] -> a | Undefined
  3956. * @sig String -> String
  3957. * @param {*} list
  3958. * @return {*}
  3959. * @see R.init, R.head, R.tail
  3960. * @example
  3961. *
  3962. * R.last(['fi', 'fo', 'fum']); //=> 'fum'
  3963. * R.last([]); //=> undefined
  3964. *
  3965. * R.last('abc'); //=> 'c'
  3966. * R.last(''); //=> ''
  3967. */
  3968. var last = nth(-1);
  3969. /**
  3970. * Returns a new list without any consecutively repeating elements. Equality is
  3971. * determined by applying the supplied predicate to each pair of consecutive elements. The
  3972. * first element in a series of equal elements will be preserved.
  3973. *
  3974. * Acts as a transducer if a transformer is given in list position.
  3975. *
  3976. * @func
  3977. * @memberOf R
  3978. * @since v0.14.0
  3979. * @category List
  3980. * @sig ((a, a) -> Boolean) -> [a] -> [a]
  3981. * @param {Function} pred A predicate used to test whether two items are equal.
  3982. * @param {Array} list The array to consider.
  3983. * @return {Array} `list` without repeating elements.
  3984. * @see R.transduce
  3985. * @example
  3986. *
  3987. * const l = [1, -1, 1, 3, 4, -4, -4, -5, 5, 3, 3];
  3988. * R.dropRepeatsWith(R.eqBy(Math.abs), l); //=> [1, 3, 4, -5, 3]
  3989. */
  3990. var dropRepeatsWith = _curry2(_dispatchable([], _xdropRepeatsWith, function dropRepeatsWith(pred, list) {
  3991. var result = [];
  3992. var idx = 1;
  3993. var len = list.length;
  3994. if (len !== 0) {
  3995. result[0] = list[0];
  3996. while (idx < len) {
  3997. if (!pred(last(result), list[idx])) {
  3998. result[result.length] = list[idx];
  3999. }
  4000. idx += 1;
  4001. }
  4002. }
  4003. return result;
  4004. }));
  4005. /**
  4006. * Returns a new list without any consecutively repeating elements.
  4007. * [`R.equals`](#equals) is used to determine equality.
  4008. *
  4009. * Acts as a transducer if a transformer is given in list position.
  4010. *
  4011. * @func
  4012. * @memberOf R
  4013. * @since v0.14.0
  4014. * @category List
  4015. * @sig [a] -> [a]
  4016. * @param {Array} list The array to consider.
  4017. * @return {Array} `list` without repeating elements.
  4018. * @see R.transduce
  4019. * @example
  4020. *
  4021. * R.dropRepeats([1, 1, 1, 2, 3, 4, 4, 2, 2]); //=> [1, 2, 3, 4, 2]
  4022. */
  4023. var dropRepeats = _curry1(
  4024. _dispatchable([], _xdropRepeatsWith(equals), dropRepeatsWith(equals))
  4025. );
  4026. function XDropWhile(f, xf) {
  4027. this.xf = xf;
  4028. this.f = f;
  4029. }
  4030. XDropWhile.prototype['@@transducer/init'] = _xfBase.init;
  4031. XDropWhile.prototype['@@transducer/result'] = _xfBase.result;
  4032. XDropWhile.prototype['@@transducer/step'] = function(result, input) {
  4033. if (this.f) {
  4034. if (this.f(input)) {
  4035. return result;
  4036. }
  4037. this.f = null;
  4038. }
  4039. return this.xf['@@transducer/step'](result, input);
  4040. };
  4041. var _xdropWhile = _curry2(function _xdropWhile(f, xf) { return new XDropWhile(f, xf); });
  4042. /**
  4043. * Returns a new list excluding the leading elements of a given list which
  4044. * satisfy the supplied predicate function. It passes each value to the supplied
  4045. * predicate function, skipping elements while the predicate function returns
  4046. * `true`. The predicate function is applied to one argument: *(value)*.
  4047. *
  4048. * Dispatches to the `dropWhile` method of the second argument, if present.
  4049. *
  4050. * Acts as a transducer if a transformer is given in list position.
  4051. *
  4052. * @func
  4053. * @memberOf R
  4054. * @since v0.9.0
  4055. * @category List
  4056. * @sig (a -> Boolean) -> [a] -> [a]
  4057. * @sig (a -> Boolean) -> String -> String
  4058. * @param {Function} fn The function called per iteration.
  4059. * @param {Array} xs The collection to iterate over.
  4060. * @return {Array} A new array.
  4061. * @see R.takeWhile, R.transduce, R.addIndex
  4062. * @example
  4063. *
  4064. * const lteTwo = x => x <= 2;
  4065. *
  4066. * R.dropWhile(lteTwo, [1, 2, 3, 4, 3, 2, 1]); //=> [3, 4, 3, 2, 1]
  4067. *
  4068. * R.dropWhile(x => x !== 'd' , 'Ramda'); //=> 'da'
  4069. */
  4070. var dropWhile = _curry2(_dispatchable(['dropWhile'], _xdropWhile, function dropWhile(pred, xs) {
  4071. var idx = 0;
  4072. var len = xs.length;
  4073. while (idx < len && pred(xs[idx])) {
  4074. idx += 1;
  4075. }
  4076. return slice(idx, Infinity, xs);
  4077. }));
  4078. /**
  4079. * Returns `true` if one or both of its arguments are `true`. Returns `false`
  4080. * if both arguments are `false`.
  4081. *
  4082. * @func
  4083. * @memberOf R
  4084. * @since v0.1.0
  4085. * @category Logic
  4086. * @sig a -> b -> a | b
  4087. * @param {Any} a
  4088. * @param {Any} b
  4089. * @return {Any} the first argument if truthy, otherwise the second argument.
  4090. * @see R.either, R.xor
  4091. * @example
  4092. *
  4093. * R.or(true, true); //=> true
  4094. * R.or(true, false); //=> true
  4095. * R.or(false, true); //=> true
  4096. * R.or(false, false); //=> false
  4097. */
  4098. var or = _curry2(function or(a, b) {
  4099. return a || b;
  4100. });
  4101. /**
  4102. * A function wrapping calls to the two functions in an `||` operation,
  4103. * returning the result of the first function if it is truth-y and the result
  4104. * of the second function otherwise. Note that this is short-circuited,
  4105. * meaning that the second function will not be invoked if the first returns a
  4106. * truth-y value.
  4107. *
  4108. * In addition to functions, `R.either` also accepts any fantasy-land compatible
  4109. * applicative functor.
  4110. *
  4111. * @func
  4112. * @memberOf R
  4113. * @since v0.12.0
  4114. * @category Logic
  4115. * @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean)
  4116. * @param {Function} f a predicate
  4117. * @param {Function} g another predicate
  4118. * @return {Function} a function that applies its arguments to `f` and `g` and `||`s their outputs together.
  4119. * @see R.or
  4120. * @example
  4121. *
  4122. * const gt10 = x => x > 10;
  4123. * const even = x => x % 2 === 0;
  4124. * const f = R.either(gt10, even);
  4125. * f(101); //=> true
  4126. * f(8); //=> true
  4127. *
  4128. * R.either(Maybe.Just(false), Maybe.Just(55)); // => Maybe.Just(55)
  4129. * R.either([false, false, 'a'], [11]) // => [11, 11, "a"]
  4130. */
  4131. var either = _curry2(function either(f, g) {
  4132. return _isFunction(f) ?
  4133. function _either() {
  4134. return f.apply(this, arguments) || g.apply(this, arguments);
  4135. } :
  4136. lift(or)(f, g);
  4137. });
  4138. /**
  4139. * Returns the empty value of its argument's type. Ramda defines the empty
  4140. * value of Array (`[]`), Object (`{}`), String (`''`), and Arguments. Other
  4141. * types are supported if they define `<Type>.empty`,
  4142. * `<Type>.prototype.empty` or implement the
  4143. * [FantasyLand Monoid spec](https://github.com/fantasyland/fantasy-land#monoid).
  4144. *
  4145. * Dispatches to the `empty` method of the first argument, if present.
  4146. *
  4147. * @func
  4148. * @memberOf R
  4149. * @since v0.3.0
  4150. * @category Function
  4151. * @sig a -> a
  4152. * @param {*} x
  4153. * @return {*}
  4154. * @example
  4155. *
  4156. * R.empty(Just(42)); //=> Nothing()
  4157. * R.empty([1, 2, 3]); //=> []
  4158. * R.empty('unicorns'); //=> ''
  4159. * R.empty({x: 1, y: 2}); //=> {}
  4160. */
  4161. var empty = _curry1(function empty(x) {
  4162. return (
  4163. (x != null && typeof x['fantasy-land/empty'] === 'function')
  4164. ? x['fantasy-land/empty']()
  4165. : (x != null && x.constructor != null && typeof x.constructor['fantasy-land/empty'] === 'function')
  4166. ? x.constructor['fantasy-land/empty']()
  4167. : (x != null && typeof x.empty === 'function')
  4168. ? x.empty()
  4169. : (x != null && x.constructor != null && typeof x.constructor.empty === 'function')
  4170. ? x.constructor.empty()
  4171. : _isArray(x)
  4172. ? []
  4173. : _isString(x)
  4174. ? ''
  4175. : _isObject(x)
  4176. ? {}
  4177. : _isArguments(x)
  4178. ? (function() { return arguments; }())
  4179. : void 0 // else
  4180. );
  4181. });
  4182. /**
  4183. * Returns a new list containing the last `n` elements of the given list.
  4184. * If `n > list.length`, returns a list of `list.length` elements.
  4185. *
  4186. * @func
  4187. * @memberOf R
  4188. * @since v0.16.0
  4189. * @category List
  4190. * @sig Number -> [a] -> [a]
  4191. * @sig Number -> String -> String
  4192. * @param {Number} n The number of elements to return.
  4193. * @param {Array} xs The collection to consider.
  4194. * @return {Array}
  4195. * @see R.dropLast
  4196. * @example
  4197. *
  4198. * R.takeLast(1, ['foo', 'bar', 'baz']); //=> ['baz']
  4199. * R.takeLast(2, ['foo', 'bar', 'baz']); //=> ['bar', 'baz']
  4200. * R.takeLast(3, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz']
  4201. * R.takeLast(4, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz']
  4202. * R.takeLast(3, 'ramda'); //=> 'mda'
  4203. */
  4204. var takeLast = _curry2(function takeLast(n, xs) {
  4205. return drop(n >= 0 ? xs.length - n : 0, xs);
  4206. });
  4207. /**
  4208. * Checks if a list ends with the provided sublist.
  4209. *
  4210. * Similarly, checks if a string ends with the provided substring.
  4211. *
  4212. * @func
  4213. * @memberOf R
  4214. * @since v0.24.0
  4215. * @category List
  4216. * @sig [a] -> [a] -> Boolean
  4217. * @sig String -> String -> Boolean
  4218. * @param {*} suffix
  4219. * @param {*} list
  4220. * @return {Boolean}
  4221. * @see R.startsWith
  4222. * @example
  4223. *
  4224. * R.endsWith('c', 'abc') //=> true
  4225. * R.endsWith('b', 'abc') //=> false
  4226. * R.endsWith(['c'], ['a', 'b', 'c']) //=> true
  4227. * R.endsWith(['b'], ['a', 'b', 'c']) //=> false
  4228. */
  4229. var endsWith = _curry2(function(suffix, list) {
  4230. return equals(takeLast(suffix.length, list), suffix);
  4231. });
  4232. /**
  4233. * Takes a function and two values in its domain and returns `true` if the
  4234. * values map to the same value in the codomain; `false` otherwise.
  4235. *
  4236. * @func
  4237. * @memberOf R
  4238. * @since v0.18.0
  4239. * @category Relation
  4240. * @sig (a -> b) -> a -> a -> Boolean
  4241. * @param {Function} f
  4242. * @param {*} x
  4243. * @param {*} y
  4244. * @return {Boolean}
  4245. * @example
  4246. *
  4247. * R.eqBy(Math.abs, 5, -5); //=> true
  4248. */
  4249. var eqBy = _curry3(function eqBy(f, x, y) {
  4250. return equals(f(x), f(y));
  4251. });
  4252. /**
  4253. * Reports whether two objects have the same value, in [`R.equals`](#equals)
  4254. * terms, for the specified property. Useful as a curried predicate.
  4255. *
  4256. * @func
  4257. * @memberOf R
  4258. * @since v0.1.0
  4259. * @category Object
  4260. * @sig k -> {k: v} -> {k: v} -> Boolean
  4261. * @param {String} prop The name of the property to compare
  4262. * @param {Object} obj1
  4263. * @param {Object} obj2
  4264. * @return {Boolean}
  4265. *
  4266. * @example
  4267. *
  4268. * const o1 = { a: 1, b: 2, c: 3, d: 4 };
  4269. * const o2 = { a: 10, b: 20, c: 3, d: 40 };
  4270. * R.eqProps('a', o1, o2); //=> false
  4271. * R.eqProps('c', o1, o2); //=> true
  4272. */
  4273. var eqProps = _curry3(function eqProps(prop, obj1, obj2) {
  4274. return equals(obj1[prop], obj2[prop]);
  4275. });
  4276. /**
  4277. * Creates a new object by recursively evolving a shallow copy of `object`,
  4278. * according to the `transformation` functions. All non-primitive properties
  4279. * are copied by reference.
  4280. *
  4281. * A `transformation` function will not be invoked if its corresponding key
  4282. * does not exist in the evolved object.
  4283. *
  4284. * @func
  4285. * @memberOf R
  4286. * @since v0.9.0
  4287. * @category Object
  4288. * @sig {k: (v -> v)} -> {k: v} -> {k: v}
  4289. * @param {Object} transformations The object specifying transformation functions to apply
  4290. * to the object.
  4291. * @param {Object} object The object to be transformed.
  4292. * @return {Object} The transformed object.
  4293. * @example
  4294. *
  4295. * const tomato = {firstName: ' Tomato ', data: {elapsed: 100, remaining: 1400}, id:123};
  4296. * const transformations = {
  4297. * firstName: R.trim,
  4298. * lastName: R.trim, // Will not get invoked.
  4299. * data: {elapsed: R.add(1), remaining: R.add(-1)}
  4300. * };
  4301. * R.evolve(transformations, tomato); //=> {firstName: 'Tomato', data: {elapsed: 101, remaining: 1399}, id:123}
  4302. */
  4303. var evolve = _curry2(function evolve(transformations, object) {
  4304. var result = object instanceof Array ? [] : {};
  4305. var transformation, key, type;
  4306. for (key in object) {
  4307. transformation = transformations[key];
  4308. type = typeof transformation;
  4309. result[key] = type === 'function'
  4310. ? transformation(object[key])
  4311. : transformation && type === 'object'
  4312. ? evolve(transformation, object[key])
  4313. : object[key];
  4314. }
  4315. return result;
  4316. });
  4317. function XFind(f, xf) {
  4318. this.xf = xf;
  4319. this.f = f;
  4320. this.found = false;
  4321. }
  4322. XFind.prototype['@@transducer/init'] = _xfBase.init;
  4323. XFind.prototype['@@transducer/result'] = function(result) {
  4324. if (!this.found) {
  4325. result = this.xf['@@transducer/step'](result, void 0);
  4326. }
  4327. return this.xf['@@transducer/result'](result);
  4328. };
  4329. XFind.prototype['@@transducer/step'] = function(result, input) {
  4330. if (this.f(input)) {
  4331. this.found = true;
  4332. result = _reduced(this.xf['@@transducer/step'](result, input));
  4333. }
  4334. return result;
  4335. };
  4336. var _xfind = _curry2(function _xfind(f, xf) { return new XFind(f, xf); });
  4337. /**
  4338. * Returns the first element of the list which matches the predicate, or
  4339. * `undefined` if no element matches.
  4340. *
  4341. * Dispatches to the `find` method of the second argument, if present.
  4342. *
  4343. * Acts as a transducer if a transformer is given in list position.
  4344. *
  4345. * @func
  4346. * @memberOf R
  4347. * @since v0.1.0
  4348. * @category List
  4349. * @sig (a -> Boolean) -> [a] -> a | undefined
  4350. * @param {Function} fn The predicate function used to determine if the element is the
  4351. * desired one.
  4352. * @param {Array} list The array to consider.
  4353. * @return {Object} The element found, or `undefined`.
  4354. * @see R.transduce
  4355. * @example
  4356. *
  4357. * const xs = [{a: 1}, {a: 2}, {a: 3}];
  4358. * R.find(R.propEq('a', 2))(xs); //=> {a: 2}
  4359. * R.find(R.propEq('a', 4))(xs); //=> undefined
  4360. */
  4361. var find = _curry2(_dispatchable(['find'], _xfind, function find(fn, list) {
  4362. var idx = 0;
  4363. var len = list.length;
  4364. while (idx < len) {
  4365. if (fn(list[idx])) {
  4366. return list[idx];
  4367. }
  4368. idx += 1;
  4369. }
  4370. }));
  4371. function XFindIndex(f, xf) {
  4372. this.xf = xf;
  4373. this.f = f;
  4374. this.idx = -1;
  4375. this.found = false;
  4376. }
  4377. XFindIndex.prototype['@@transducer/init'] = _xfBase.init;
  4378. XFindIndex.prototype['@@transducer/result'] = function(result) {
  4379. if (!this.found) {
  4380. result = this.xf['@@transducer/step'](result, -1);
  4381. }
  4382. return this.xf['@@transducer/result'](result);
  4383. };
  4384. XFindIndex.prototype['@@transducer/step'] = function(result, input) {
  4385. this.idx += 1;
  4386. if (this.f(input)) {
  4387. this.found = true;
  4388. result = _reduced(this.xf['@@transducer/step'](result, this.idx));
  4389. }
  4390. return result;
  4391. };
  4392. var _xfindIndex = _curry2(function _xfindIndex(f, xf) { return new XFindIndex(f, xf); });
  4393. /**
  4394. * Returns the index of the first element of the list which matches the
  4395. * predicate, or `-1` if no element matches.
  4396. *
  4397. * Acts as a transducer if a transformer is given in list position.
  4398. *
  4399. * @func
  4400. * @memberOf R
  4401. * @since v0.1.1
  4402. * @category List
  4403. * @sig (a -> Boolean) -> [a] -> Number
  4404. * @param {Function} fn The predicate function used to determine if the element is the
  4405. * desired one.
  4406. * @param {Array} list The array to consider.
  4407. * @return {Number} The index of the element found, or `-1`.
  4408. * @see R.transduce
  4409. * @example
  4410. *
  4411. * const xs = [{a: 1}, {a: 2}, {a: 3}];
  4412. * R.findIndex(R.propEq('a', 2))(xs); //=> 1
  4413. * R.findIndex(R.propEq('a', 4))(xs); //=> -1
  4414. */
  4415. var findIndex = _curry2(_dispatchable([], _xfindIndex, function findIndex(fn, list) {
  4416. var idx = 0;
  4417. var len = list.length;
  4418. while (idx < len) {
  4419. if (fn(list[idx])) {
  4420. return idx;
  4421. }
  4422. idx += 1;
  4423. }
  4424. return -1;
  4425. }));
  4426. function XFindLast(f, xf) {
  4427. this.xf = xf;
  4428. this.f = f;
  4429. }
  4430. XFindLast.prototype['@@transducer/init'] = _xfBase.init;
  4431. XFindLast.prototype['@@transducer/result'] = function(result) {
  4432. return this.xf['@@transducer/result'](this.xf['@@transducer/step'](result, this.last));
  4433. };
  4434. XFindLast.prototype['@@transducer/step'] = function(result, input) {
  4435. if (this.f(input)) {
  4436. this.last = input;
  4437. }
  4438. return result;
  4439. };
  4440. var _xfindLast = _curry2(function _xfindLast(f, xf) { return new XFindLast(f, xf); });
  4441. /**
  4442. * Returns the last element of the list which matches the predicate, or
  4443. * `undefined` if no element matches.
  4444. *
  4445. * Acts as a transducer if a transformer is given in list position.
  4446. *
  4447. * @func
  4448. * @memberOf R
  4449. * @since v0.1.1
  4450. * @category List
  4451. * @sig (a -> Boolean) -> [a] -> a | undefined
  4452. * @param {Function} fn The predicate function used to determine if the element is the
  4453. * desired one.
  4454. * @param {Array} list The array to consider.
  4455. * @return {Object} The element found, or `undefined`.
  4456. * @see R.transduce
  4457. * @example
  4458. *
  4459. * const xs = [{a: 1, b: 0}, {a:1, b: 1}];
  4460. * R.findLast(R.propEq('a', 1))(xs); //=> {a: 1, b: 1}
  4461. * R.findLast(R.propEq('a', 4))(xs); //=> undefined
  4462. */
  4463. var findLast = _curry2(_dispatchable([], _xfindLast, function findLast(fn, list) {
  4464. var idx = list.length - 1;
  4465. while (idx >= 0) {
  4466. if (fn(list[idx])) {
  4467. return list[idx];
  4468. }
  4469. idx -= 1;
  4470. }
  4471. }));
  4472. function XFindLastIndex(f, xf) {
  4473. this.xf = xf;
  4474. this.f = f;
  4475. this.idx = -1;
  4476. this.lastIdx = -1;
  4477. }
  4478. XFindLastIndex.prototype['@@transducer/init'] = _xfBase.init;
  4479. XFindLastIndex.prototype['@@transducer/result'] = function(result) {
  4480. return this.xf['@@transducer/result'](this.xf['@@transducer/step'](result, this.lastIdx));
  4481. };
  4482. XFindLastIndex.prototype['@@transducer/step'] = function(result, input) {
  4483. this.idx += 1;
  4484. if (this.f(input)) {
  4485. this.lastIdx = this.idx;
  4486. }
  4487. return result;
  4488. };
  4489. var _xfindLastIndex = _curry2(function _xfindLastIndex(f, xf) { return new XFindLastIndex(f, xf); });
  4490. /**
  4491. * Returns the index of the last element of the list which matches the
  4492. * predicate, or `-1` if no element matches.
  4493. *
  4494. * Acts as a transducer if a transformer is given in list position.
  4495. *
  4496. * @func
  4497. * @memberOf R
  4498. * @since v0.1.1
  4499. * @category List
  4500. * @sig (a -> Boolean) -> [a] -> Number
  4501. * @param {Function} fn The predicate function used to determine if the element is the
  4502. * desired one.
  4503. * @param {Array} list The array to consider.
  4504. * @return {Number} The index of the element found, or `-1`.
  4505. * @see R.transduce
  4506. * @example
  4507. *
  4508. * const xs = [{a: 1, b: 0}, {a:1, b: 1}];
  4509. * R.findLastIndex(R.propEq('a', 1))(xs); //=> 1
  4510. * R.findLastIndex(R.propEq('a', 4))(xs); //=> -1
  4511. */
  4512. var findLastIndex = _curry2(_dispatchable([], _xfindLastIndex, function findLastIndex(fn, list) {
  4513. var idx = list.length - 1;
  4514. while (idx >= 0) {
  4515. if (fn(list[idx])) {
  4516. return idx;
  4517. }
  4518. idx -= 1;
  4519. }
  4520. return -1;
  4521. }));
  4522. /**
  4523. * Returns a new list by pulling every item out of it (and all its sub-arrays)
  4524. * and putting them in a new array, depth-first.
  4525. *
  4526. * @func
  4527. * @memberOf R
  4528. * @since v0.1.0
  4529. * @category List
  4530. * @sig [a] -> [b]
  4531. * @param {Array} list The array to consider.
  4532. * @return {Array} The flattened list.
  4533. * @see R.unnest
  4534. * @example
  4535. *
  4536. * R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]);
  4537. * //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
  4538. */
  4539. var flatten = _curry1(_makeFlat(true));
  4540. /**
  4541. * Returns a new function much like the supplied one, except that the first two
  4542. * arguments' order is reversed.
  4543. *
  4544. * @func
  4545. * @memberOf R
  4546. * @since v0.1.0
  4547. * @category Function
  4548. * @sig ((a, b, c, ...) -> z) -> (b -> a -> c -> ... -> z)
  4549. * @param {Function} fn The function to invoke with its first two parameters reversed.
  4550. * @return {*} The result of invoking `fn` with its first two parameters' order reversed.
  4551. * @example
  4552. *
  4553. * const mergeThree = (a, b, c) => [].concat(a, b, c);
  4554. *
  4555. * mergeThree(1, 2, 3); //=> [1, 2, 3]
  4556. *
  4557. * R.flip(mergeThree)(1, 2, 3); //=> [2, 1, 3]
  4558. * @symb R.flip(f)(a, b, c) = f(b, a, c)
  4559. */
  4560. var flip = _curry1(function flip(fn) {
  4561. return curryN(fn.length, function(a, b) {
  4562. var args = Array.prototype.slice.call(arguments, 0);
  4563. args[0] = b;
  4564. args[1] = a;
  4565. return fn.apply(this, args);
  4566. });
  4567. });
  4568. /**
  4569. * Iterate over an input `list`, calling a provided function `fn` for each
  4570. * element in the list.
  4571. *
  4572. * `fn` receives one argument: *(value)*.
  4573. *
  4574. * Note: `R.forEach` does not skip deleted or unassigned indices (sparse
  4575. * arrays), unlike the native `Array.prototype.forEach` method. For more
  4576. * details on this behavior, see:
  4577. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description
  4578. *
  4579. * Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns
  4580. * the original array. In some libraries this function is named `each`.
  4581. *
  4582. * Dispatches to the `forEach` method of the second argument, if present.
  4583. *
  4584. * @func
  4585. * @memberOf R
  4586. * @since v0.1.1
  4587. * @category List
  4588. * @sig (a -> *) -> [a] -> [a]
  4589. * @param {Function} fn The function to invoke. Receives one argument, `value`.
  4590. * @param {Array} list The list to iterate over.
  4591. * @return {Array} The original list.
  4592. * @see R.addIndex
  4593. * @example
  4594. *
  4595. * const printXPlusFive = x => console.log(x + 5);
  4596. * R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3]
  4597. * // logs 6
  4598. * // logs 7
  4599. * // logs 8
  4600. * @symb R.forEach(f, [a, b, c]) = [a, b, c]
  4601. */
  4602. var forEach = _curry2(_checkForMethod('forEach', function forEach(fn, list) {
  4603. var len = list.length;
  4604. var idx = 0;
  4605. while (idx < len) {
  4606. fn(list[idx]);
  4607. idx += 1;
  4608. }
  4609. return list;
  4610. }));
  4611. /**
  4612. * Iterate over an input `object`, calling a provided function `fn` for each
  4613. * key and value in the object.
  4614. *
  4615. * `fn` receives three argument: *(value, key, obj)*.
  4616. *
  4617. * @func
  4618. * @memberOf R
  4619. * @since v0.23.0
  4620. * @category Object
  4621. * @sig ((a, String, StrMap a) -> Any) -> StrMap a -> StrMap a
  4622. * @param {Function} fn The function to invoke. Receives three argument, `value`, `key`, `obj`.
  4623. * @param {Object} obj The object to iterate over.
  4624. * @return {Object} The original object.
  4625. * @example
  4626. *
  4627. * const printKeyConcatValue = (value, key) => console.log(key + ':' + value);
  4628. * R.forEachObjIndexed(printKeyConcatValue, {x: 1, y: 2}); //=> {x: 1, y: 2}
  4629. * // logs x:1
  4630. * // logs y:2
  4631. * @symb R.forEachObjIndexed(f, {x: a, y: b}) = {x: a, y: b}
  4632. */
  4633. var forEachObjIndexed = _curry2(function forEachObjIndexed(fn, obj) {
  4634. var keyList = keys(obj);
  4635. var idx = 0;
  4636. while (idx < keyList.length) {
  4637. var key = keyList[idx];
  4638. fn(obj[key], key, obj);
  4639. idx += 1;
  4640. }
  4641. return obj;
  4642. });
  4643. /**
  4644. * Creates a new object from a list key-value pairs. If a key appears in
  4645. * multiple pairs, the rightmost pair is included in the object.
  4646. *
  4647. * @func
  4648. * @memberOf R
  4649. * @since v0.3.0
  4650. * @category List
  4651. * @sig [[k,v]] -> {k: v}
  4652. * @param {Array} pairs An array of two-element arrays that will be the keys and values of the output object.
  4653. * @return {Object} The object made by pairing up `keys` and `values`.
  4654. * @see R.toPairs, R.pair
  4655. * @example
  4656. *
  4657. * R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3}
  4658. */
  4659. var fromPairs = _curry1(function fromPairs(pairs) {
  4660. var result = {};
  4661. var idx = 0;
  4662. while (idx < pairs.length) {
  4663. result[pairs[idx][0]] = pairs[idx][1];
  4664. idx += 1;
  4665. }
  4666. return result;
  4667. });
  4668. /**
  4669. * Splits a list into sub-lists stored in an object, based on the result of
  4670. * calling a String-returning function on each element, and grouping the
  4671. * results according to values returned.
  4672. *
  4673. * Dispatches to the `groupBy` method of the second argument, if present.
  4674. *
  4675. * Acts as a transducer if a transformer is given in list position.
  4676. *
  4677. * @func
  4678. * @memberOf R
  4679. * @since v0.1.0
  4680. * @category List
  4681. * @sig (a -> String) -> [a] -> {String: [a]}
  4682. * @param {Function} fn Function :: a -> String
  4683. * @param {Array} list The array to group
  4684. * @return {Object} An object with the output of `fn` for keys, mapped to arrays of elements
  4685. * that produced that key when passed to `fn`.
  4686. * @see R.reduceBy, R.transduce
  4687. * @example
  4688. *
  4689. * const byGrade = R.groupBy(function(student) {
  4690. * const score = student.score;
  4691. * return score < 65 ? 'F' :
  4692. * score < 70 ? 'D' :
  4693. * score < 80 ? 'C' :
  4694. * score < 90 ? 'B' : 'A';
  4695. * });
  4696. * const students = [{name: 'Abby', score: 84},
  4697. * {name: 'Eddy', score: 58},
  4698. * // ...
  4699. * {name: 'Jack', score: 69}];
  4700. * byGrade(students);
  4701. * // {
  4702. * // 'A': [{name: 'Dianne', score: 99}],
  4703. * // 'B': [{name: 'Abby', score: 84}]
  4704. * // // ...,
  4705. * // 'F': [{name: 'Eddy', score: 58}]
  4706. * // }
  4707. */
  4708. var groupBy = _curry2(_checkForMethod('groupBy', reduceBy(function(acc, item) {
  4709. if (acc == null) {
  4710. acc = [];
  4711. }
  4712. acc.push(item);
  4713. return acc;
  4714. }, null)));
  4715. /**
  4716. * Takes a list and returns a list of lists where each sublist's elements are
  4717. * all satisfied pairwise comparison according to the provided function.
  4718. * Only adjacent elements are passed to the comparison function.
  4719. *
  4720. * @func
  4721. * @memberOf R
  4722. * @since v0.21.0
  4723. * @category List
  4724. * @sig ((a, a) Boolean) [a] [[a]]
  4725. * @param {Function} fn Function for determining whether two given (adjacent)
  4726. * elements should be in the same group
  4727. * @param {Array} list The array to group. Also accepts a string, which will be
  4728. * treated as a list of characters.
  4729. * @return {List} A list that contains sublists of elements,
  4730. * whose concatenations are equal to the original list.
  4731. * @example
  4732. *
  4733. * R.groupWith(R.equals, [0, 1, 1, 2, 3, 5, 8, 13, 21])
  4734. * //=> [[0], [1, 1], [2], [3], [5], [8], [13], [21]]
  4735. *
  4736. * R.groupWith((a, b) => a + 1 === b, [0, 1, 1, 2, 3, 5, 8, 13, 21])
  4737. * //=> [[0, 1], [1, 2, 3], [5], [8], [13], [21]]
  4738. *
  4739. * R.groupWith((a, b) => a % 2 === b % 2, [0, 1, 1, 2, 3, 5, 8, 13, 21])
  4740. * //=> [[0], [1, 1], [2], [3, 5], [8], [13, 21]]
  4741. *
  4742. * R.groupWith(R.eqBy(isVowel), 'aestiou')
  4743. * //=> ['ae', 'st', 'iou']
  4744. */
  4745. var groupWith = _curry2(function(fn, list) {
  4746. var res = [];
  4747. var idx = 0;
  4748. var len = list.length;
  4749. while (idx < len) {
  4750. var nextidx = idx + 1;
  4751. while (nextidx < len && fn(list[nextidx - 1], list[nextidx])) {
  4752. nextidx += 1;
  4753. }
  4754. res.push(list.slice(idx, nextidx));
  4755. idx = nextidx;
  4756. }
  4757. return res;
  4758. });
  4759. /**
  4760. * Returns `true` if the first argument is greater than the second; `false`
  4761. * otherwise.
  4762. *
  4763. * @func
  4764. * @memberOf R
  4765. * @since v0.1.0
  4766. * @category Relation
  4767. * @sig Ord a => a -> a -> Boolean
  4768. * @param {*} a
  4769. * @param {*} b
  4770. * @return {Boolean}
  4771. * @see R.lt
  4772. * @example
  4773. *
  4774. * R.gt(2, 1); //=> true
  4775. * R.gt(2, 2); //=> false
  4776. * R.gt(2, 3); //=> false
  4777. * R.gt('a', 'z'); //=> false
  4778. * R.gt('z', 'a'); //=> true
  4779. */
  4780. var gt = _curry2(function gt(a, b) { return a > b; });
  4781. /**
  4782. * Returns `true` if the first argument is greater than or equal to the second;
  4783. * `false` otherwise.
  4784. *
  4785. * @func
  4786. * @memberOf R
  4787. * @since v0.1.0
  4788. * @category Relation
  4789. * @sig Ord a => a -> a -> Boolean
  4790. * @param {Number} a
  4791. * @param {Number} b
  4792. * @return {Boolean}
  4793. * @see R.lte
  4794. * @example
  4795. *
  4796. * R.gte(2, 1); //=> true
  4797. * R.gte(2, 2); //=> true
  4798. * R.gte(2, 3); //=> false
  4799. * R.gte('a', 'z'); //=> false
  4800. * R.gte('z', 'a'); //=> true
  4801. */
  4802. var gte = _curry2(function gte(a, b) { return a >= b; });
  4803. /**
  4804. * Returns whether or not a path exists in an object. Only the object's
  4805. * own properties are checked.
  4806. *
  4807. * @func
  4808. * @memberOf R
  4809. * @since v0.26.0
  4810. * @category Object
  4811. * @typedefn Idx = String | Int
  4812. * @sig [Idx] -> {a} -> Boolean
  4813. * @param {Array} path The path to use.
  4814. * @param {Object} obj The object to check the path in.
  4815. * @return {Boolean} Whether the path exists.
  4816. * @see R.has
  4817. * @example
  4818. *
  4819. * R.hasPath(['a', 'b'], {a: {b: 2}}); // => true
  4820. * R.hasPath(['a', 'b'], {a: {b: undefined}}); // => true
  4821. * R.hasPath(['a', 'b'], {a: {c: 2}}); // => false
  4822. * R.hasPath(['a', 'b'], {}); // => false
  4823. */
  4824. var hasPath = _curry2(function hasPath(_path, obj) {
  4825. if (_path.length === 0 || isNil(obj)) {
  4826. return false;
  4827. }
  4828. var val = obj;
  4829. var idx = 0;
  4830. while (idx < _path.length) {
  4831. if (!isNil(val) && _has(_path[idx], val)) {
  4832. val = val[_path[idx]];
  4833. idx += 1;
  4834. } else {
  4835. return false;
  4836. }
  4837. }
  4838. return true;
  4839. });
  4840. /**
  4841. * Returns whether or not an object has an own property with the specified name
  4842. *
  4843. * @func
  4844. * @memberOf R
  4845. * @since v0.7.0
  4846. * @category Object
  4847. * @sig s -> {s: x} -> Boolean
  4848. * @param {String} prop The name of the property to check for.
  4849. * @param {Object} obj The object to query.
  4850. * @return {Boolean} Whether the property exists.
  4851. * @example
  4852. *
  4853. * const hasName = R.has('name');
  4854. * hasName({name: 'alice'}); //=> true
  4855. * hasName({name: 'bob'}); //=> true
  4856. * hasName({}); //=> false
  4857. *
  4858. * const point = {x: 0, y: 0};
  4859. * const pointHas = R.has(R.__, point);
  4860. * pointHas('x'); //=> true
  4861. * pointHas('y'); //=> true
  4862. * pointHas('z'); //=> false
  4863. */
  4864. var has = _curry2(function has(prop, obj) {
  4865. return hasPath([prop], obj);
  4866. });
  4867. /**
  4868. * Returns whether or not an object or its prototype chain has a property with
  4869. * the specified name
  4870. *
  4871. * @func
  4872. * @memberOf R
  4873. * @since v0.7.0
  4874. * @category Object
  4875. * @sig s -> {s: x} -> Boolean
  4876. * @param {String} prop The name of the property to check for.
  4877. * @param {Object} obj The object to query.
  4878. * @return {Boolean} Whether the property exists.
  4879. * @example
  4880. *
  4881. * function Rectangle(width, height) {
  4882. * this.width = width;
  4883. * this.height = height;
  4884. * }
  4885. * Rectangle.prototype.area = function() {
  4886. * return this.width * this.height;
  4887. * };
  4888. *
  4889. * const square = new Rectangle(2, 2);
  4890. * R.hasIn('width', square); //=> true
  4891. * R.hasIn('area', square); //=> true
  4892. */
  4893. var hasIn = _curry2(function hasIn(prop, obj) {
  4894. return prop in obj;
  4895. });
  4896. /**
  4897. * Returns true if its arguments are identical, false otherwise. Values are
  4898. * identical if they reference the same memory. `NaN` is identical to `NaN`;
  4899. * `0` and `-0` are not identical.
  4900. *
  4901. * Note this is merely a curried version of ES6 `Object.is`.
  4902. *
  4903. * @func
  4904. * @memberOf R
  4905. * @since v0.15.0
  4906. * @category Relation
  4907. * @sig a -> a -> Boolean
  4908. * @param {*} a
  4909. * @param {*} b
  4910. * @return {Boolean}
  4911. * @example
  4912. *
  4913. * const o = {};
  4914. * R.identical(o, o); //=> true
  4915. * R.identical(1, 1); //=> true
  4916. * R.identical(1, '1'); //=> false
  4917. * R.identical([], []); //=> false
  4918. * R.identical(0, -0); //=> false
  4919. * R.identical(NaN, NaN); //=> true
  4920. */
  4921. var identical = _curry2(_objectIs$1);
  4922. /**
  4923. * Creates a function that will process either the `onTrue` or the `onFalse`
  4924. * function depending upon the result of the `condition` predicate.
  4925. *
  4926. * @func
  4927. * @memberOf R
  4928. * @since v0.8.0
  4929. * @category Logic
  4930. * @sig (*... -> Boolean) -> (*... -> *) -> (*... -> *) -> (*... -> *)
  4931. * @param {Function} condition A predicate function
  4932. * @param {Function} onTrue A function to invoke when the `condition` evaluates to a truthy value.
  4933. * @param {Function} onFalse A function to invoke when the `condition` evaluates to a falsy value.
  4934. * @return {Function} A new function that will process either the `onTrue` or the `onFalse`
  4935. * function depending upon the result of the `condition` predicate.
  4936. * @see R.unless, R.when, R.cond
  4937. * @example
  4938. *
  4939. * const incCount = R.ifElse(
  4940. * R.has('count'),
  4941. * R.over(R.lensProp('count'), R.inc),
  4942. * R.assoc('count', 1)
  4943. * );
  4944. * incCount({}); //=> { count: 1 }
  4945. * incCount({ count: 1 }); //=> { count: 2 }
  4946. */
  4947. var ifElse = _curry3(function ifElse(condition, onTrue, onFalse) {
  4948. return curryN(Math.max(condition.length, onTrue.length, onFalse.length),
  4949. function _ifElse() {
  4950. return condition.apply(this, arguments) ? onTrue.apply(this, arguments) : onFalse.apply(this, arguments);
  4951. }
  4952. );
  4953. });
  4954. /**
  4955. * Increments its argument.
  4956. *
  4957. * @func
  4958. * @memberOf R
  4959. * @since v0.9.0
  4960. * @category Math
  4961. * @sig Number -> Number
  4962. * @param {Number} n
  4963. * @return {Number} n + 1
  4964. * @see R.dec
  4965. * @example
  4966. *
  4967. * R.inc(42); //=> 43
  4968. */
  4969. var inc = add(1);
  4970. /**
  4971. * Returns `true` if the specified value is equal, in [`R.equals`](#equals)
  4972. * terms, to at least one element of the given list; `false` otherwise.
  4973. * Works also with strings.
  4974. *
  4975. * @func
  4976. * @memberOf R
  4977. * @since v0.26.0
  4978. * @category List
  4979. * @sig a -> [a] -> Boolean
  4980. * @param {Object} a The item to compare against.
  4981. * @param {Array} list The array to consider.
  4982. * @return {Boolean} `true` if an equivalent item is in the list, `false` otherwise.
  4983. * @see R.any
  4984. * @example
  4985. *
  4986. * R.includes(3, [1, 2, 3]); //=> true
  4987. * R.includes(4, [1, 2, 3]); //=> false
  4988. * R.includes({ name: 'Fred' }, [{ name: 'Fred' }]); //=> true
  4989. * R.includes([42], [[42]]); //=> true
  4990. * R.includes('ba', 'banana'); //=>true
  4991. */
  4992. var includes = _curry2(_includes);
  4993. /**
  4994. * Given a function that generates a key, turns a list of objects into an
  4995. * object indexing the objects by the given key. Note that if multiple
  4996. * objects generate the same value for the indexing key only the last value
  4997. * will be included in the generated object.
  4998. *
  4999. * Acts as a transducer if a transformer is given in list position.
  5000. *
  5001. * @func
  5002. * @memberOf R
  5003. * @since v0.19.0
  5004. * @category List
  5005. * @sig (a -> String) -> [{k: v}] -> {k: {k: v}}
  5006. * @param {Function} fn Function :: a -> String
  5007. * @param {Array} array The array of objects to index
  5008. * @return {Object} An object indexing each array element by the given property.
  5009. * @example
  5010. *
  5011. * const list = [{id: 'xyz', title: 'A'}, {id: 'abc', title: 'B'}];
  5012. * R.indexBy(R.prop('id'), list);
  5013. * //=> {abc: {id: 'abc', title: 'B'}, xyz: {id: 'xyz', title: 'A'}}
  5014. */
  5015. var indexBy = reduceBy(function(acc, elem) { return elem; }, null);
  5016. /**
  5017. * Returns the position of the first occurrence of an item in an array, or -1
  5018. * if the item is not included in the array. [`R.equals`](#equals) is used to
  5019. * determine equality.
  5020. *
  5021. * @func
  5022. * @memberOf R
  5023. * @since v0.1.0
  5024. * @category List
  5025. * @sig a -> [a] -> Number
  5026. * @param {*} target The item to find.
  5027. * @param {Array} xs The array to search in.
  5028. * @return {Number} the index of the target, or -1 if the target is not found.
  5029. * @see R.lastIndexOf
  5030. * @example
  5031. *
  5032. * R.indexOf(3, [1,2,3,4]); //=> 2
  5033. * R.indexOf(10, [1,2,3,4]); //=> -1
  5034. */
  5035. var indexOf = _curry2(function indexOf(target, xs) {
  5036. return typeof xs.indexOf === 'function' && !_isArray(xs) ?
  5037. xs.indexOf(target) :
  5038. _indexOf(xs, target, 0);
  5039. });
  5040. /**
  5041. * Returns all but the last element of the given list or string.
  5042. *
  5043. * @func
  5044. * @memberOf R
  5045. * @since v0.9.0
  5046. * @category List
  5047. * @sig [a] -> [a]
  5048. * @sig String -> String
  5049. * @param {*} list
  5050. * @return {*}
  5051. * @see R.last, R.head, R.tail
  5052. * @example
  5053. *
  5054. * R.init([1, 2, 3]); //=> [1, 2]
  5055. * R.init([1, 2]); //=> [1]
  5056. * R.init([1]); //=> []
  5057. * R.init([]); //=> []
  5058. *
  5059. * R.init('abc'); //=> 'ab'
  5060. * R.init('ab'); //=> 'a'
  5061. * R.init('a'); //=> ''
  5062. * R.init(''); //=> ''
  5063. */
  5064. var init = slice(0, -1);
  5065. /**
  5066. * Takes a predicate `pred`, a list `xs`, and a list `ys`, and returns a list
  5067. * `xs'` comprising each of the elements of `xs` which is equal to one or more
  5068. * elements of `ys` according to `pred`.
  5069. *
  5070. * `pred` must be a binary function expecting an element from each list.
  5071. *
  5072. * `xs`, `ys`, and `xs'` are treated as sets, semantically, so ordering should
  5073. * not be significant, but since `xs'` is ordered the implementation guarantees
  5074. * that its values are in the same order as they appear in `xs`. Duplicates are
  5075. * not removed, so `xs'` may contain duplicates if `xs` contains duplicates.
  5076. *
  5077. * @func
  5078. * @memberOf R
  5079. * @since v0.24.0
  5080. * @category Relation
  5081. * @sig ((a, b) -> Boolean) -> [a] -> [b] -> [a]
  5082. * @param {Function} pred
  5083. * @param {Array} xs
  5084. * @param {Array} ys
  5085. * @return {Array}
  5086. * @see R.intersection
  5087. * @example
  5088. *
  5089. * R.innerJoin(
  5090. * (record, id) => record.id === id,
  5091. * [{id: 824, name: 'Richie Furay'},
  5092. * {id: 956, name: 'Dewey Martin'},
  5093. * {id: 313, name: 'Bruce Palmer'},
  5094. * {id: 456, name: 'Stephen Stills'},
  5095. * {id: 177, name: 'Neil Young'}],
  5096. * [177, 456, 999]
  5097. * );
  5098. * //=> [{id: 456, name: 'Stephen Stills'}, {id: 177, name: 'Neil Young'}]
  5099. */
  5100. var innerJoin = _curry3(function innerJoin(pred, xs, ys) {
  5101. return _filter(function(x) { return _includesWith(pred, x, ys); }, xs);
  5102. });
  5103. /**
  5104. * Inserts the supplied element into the list, at the specified `index`. _Note that
  5105. * this is not destructive_: it returns a copy of the list with the changes.
  5106. * <small>No lists have been harmed in the application of this function.</small>
  5107. *
  5108. * @func
  5109. * @memberOf R
  5110. * @since v0.2.2
  5111. * @category List
  5112. * @sig Number -> a -> [a] -> [a]
  5113. * @param {Number} index The position to insert the element
  5114. * @param {*} elt The element to insert into the Array
  5115. * @param {Array} list The list to insert into
  5116. * @return {Array} A new Array with `elt` inserted at `index`.
  5117. * @example
  5118. *
  5119. * R.insert(2, 'x', [1,2,3,4]); //=> [1,2,'x',3,4]
  5120. */
  5121. var insert = _curry3(function insert(idx, elt, list) {
  5122. idx = idx < list.length && idx >= 0 ? idx : list.length;
  5123. var result = Array.prototype.slice.call(list, 0);
  5124. result.splice(idx, 0, elt);
  5125. return result;
  5126. });
  5127. /**
  5128. * Inserts the sub-list into the list, at the specified `index`. _Note that this is not
  5129. * destructive_: it returns a copy of the list with the changes.
  5130. * <small>No lists have been harmed in the application of this function.</small>
  5131. *
  5132. * @func
  5133. * @memberOf R
  5134. * @since v0.9.0
  5135. * @category List
  5136. * @sig Number -> [a] -> [a] -> [a]
  5137. * @param {Number} index The position to insert the sub-list
  5138. * @param {Array} elts The sub-list to insert into the Array
  5139. * @param {Array} list The list to insert the sub-list into
  5140. * @return {Array} A new Array with `elts` inserted starting at `index`.
  5141. * @example
  5142. *
  5143. * R.insertAll(2, ['x','y','z'], [1,2,3,4]); //=> [1,2,'x','y','z',3,4]
  5144. */
  5145. var insertAll = _curry3(function insertAll(idx, elts, list) {
  5146. idx = idx < list.length && idx >= 0 ? idx : list.length;
  5147. return [].concat(
  5148. Array.prototype.slice.call(list, 0, idx),
  5149. elts,
  5150. Array.prototype.slice.call(list, idx)
  5151. );
  5152. });
  5153. /**
  5154. * Returns a new list containing only one copy of each element in the original
  5155. * list, based upon the value returned by applying the supplied function to
  5156. * each list element. Prefers the first item if the supplied function produces
  5157. * the same value on two items. [`R.equals`](#equals) is used for comparison.
  5158. *
  5159. * @func
  5160. * @memberOf R
  5161. * @since v0.16.0
  5162. * @category List
  5163. * @sig (a -> b) -> [a] -> [a]
  5164. * @param {Function} fn A function used to produce a value to use during comparisons.
  5165. * @param {Array} list The array to consider.
  5166. * @return {Array} The list of unique items.
  5167. * @example
  5168. *
  5169. * R.uniqBy(Math.abs, [-1, -5, 2, 10, 1, 2]); //=> [-1, -5, 2, 10]
  5170. */
  5171. var uniqBy = _curry2(function uniqBy(fn, list) {
  5172. var set = new _Set();
  5173. var result = [];
  5174. var idx = 0;
  5175. var appliedItem, item;
  5176. while (idx < list.length) {
  5177. item = list[idx];
  5178. appliedItem = fn(item);
  5179. if (set.add(appliedItem)) {
  5180. result.push(item);
  5181. }
  5182. idx += 1;
  5183. }
  5184. return result;
  5185. });
  5186. /**
  5187. * Returns a new list containing only one copy of each element in the original
  5188. * list. [`R.equals`](#equals) is used to determine equality.
  5189. *
  5190. * @func
  5191. * @memberOf R
  5192. * @since v0.1.0
  5193. * @category List
  5194. * @sig [a] -> [a]
  5195. * @param {Array} list The array to consider.
  5196. * @return {Array} The list of unique items.
  5197. * @example
  5198. *
  5199. * R.uniq([1, 1, 2, 1]); //=> [1, 2]
  5200. * R.uniq([1, '1']); //=> [1, '1']
  5201. * R.uniq([[42], [42]]); //=> [[42]]
  5202. */
  5203. var uniq = uniqBy(identity);
  5204. /**
  5205. * Combines two lists into a set (i.e. no duplicates) composed of those
  5206. * elements common to both lists.
  5207. *
  5208. * @func
  5209. * @memberOf R
  5210. * @since v0.1.0
  5211. * @category Relation
  5212. * @sig [*] -> [*] -> [*]
  5213. * @param {Array} list1 The first list.
  5214. * @param {Array} list2 The second list.
  5215. * @return {Array} The list of elements found in both `list1` and `list2`.
  5216. * @see R.innerJoin
  5217. * @example
  5218. *
  5219. * R.intersection([1,2,3,4], [7,6,5,4,3]); //=> [4, 3]
  5220. */
  5221. var intersection = _curry2(function intersection(list1, list2) {
  5222. var lookupList, filteredList;
  5223. if (list1.length > list2.length) {
  5224. lookupList = list1;
  5225. filteredList = list2;
  5226. } else {
  5227. lookupList = list2;
  5228. filteredList = list1;
  5229. }
  5230. return uniq(_filter(flip(_includes)(lookupList), filteredList));
  5231. });
  5232. /**
  5233. * Creates a new list with the separator interposed between elements.
  5234. *
  5235. * Dispatches to the `intersperse` method of the second argument, if present.
  5236. *
  5237. * @func
  5238. * @memberOf R
  5239. * @since v0.14.0
  5240. * @category List
  5241. * @sig a -> [a] -> [a]
  5242. * @param {*} separator The element to add to the list.
  5243. * @param {Array} list The list to be interposed.
  5244. * @return {Array} The new list.
  5245. * @example
  5246. *
  5247. * R.intersperse('a', ['b', 'n', 'n', 's']); //=> ['b', 'a', 'n', 'a', 'n', 'a', 's']
  5248. */
  5249. var intersperse = _curry2(_checkForMethod('intersperse', function intersperse(separator, list) {
  5250. var out = [];
  5251. var idx = 0;
  5252. var length = list.length;
  5253. while (idx < length) {
  5254. if (idx === length - 1) {
  5255. out.push(list[idx]);
  5256. } else {
  5257. out.push(list[idx], separator);
  5258. }
  5259. idx += 1;
  5260. }
  5261. return out;
  5262. }));
  5263. // Based on https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  5264. function _objectAssign(target) {
  5265. if (target == null) {
  5266. throw new TypeError('Cannot convert undefined or null to object');
  5267. }
  5268. var output = Object(target);
  5269. var idx = 1;
  5270. var length = arguments.length;
  5271. while (idx < length) {
  5272. var source = arguments[idx];
  5273. if (source != null) {
  5274. for (var nextKey in source) {
  5275. if (_has(nextKey, source)) {
  5276. output[nextKey] = source[nextKey];
  5277. }
  5278. }
  5279. }
  5280. idx += 1;
  5281. }
  5282. return output;
  5283. }
  5284. var _objectAssign$1 = typeof Object.assign === 'function' ? Object.assign : _objectAssign;
  5285. /**
  5286. * Creates an object containing a single key:value pair.
  5287. *
  5288. * @func
  5289. * @memberOf R
  5290. * @since v0.18.0
  5291. * @category Object
  5292. * @sig String -> a -> {String:a}
  5293. * @param {String} key
  5294. * @param {*} val
  5295. * @return {Object}
  5296. * @see R.pair
  5297. * @example
  5298. *
  5299. * const matchPhrases = R.compose(
  5300. * R.objOf('must'),
  5301. * R.map(R.objOf('match_phrase'))
  5302. * );
  5303. * matchPhrases(['foo', 'bar', 'baz']); //=> {must: [{match_phrase: 'foo'}, {match_phrase: 'bar'}, {match_phrase: 'baz'}]}
  5304. */
  5305. var objOf = _curry2(function objOf(key, val) {
  5306. var obj = {};
  5307. obj[key] = val;
  5308. return obj;
  5309. });
  5310. var _stepCatArray = {
  5311. '@@transducer/init': Array,
  5312. '@@transducer/step': function(xs, x) {
  5313. xs.push(x);
  5314. return xs;
  5315. },
  5316. '@@transducer/result': _identity
  5317. };
  5318. var _stepCatString = {
  5319. '@@transducer/init': String,
  5320. '@@transducer/step': function(a, b) { return a + b; },
  5321. '@@transducer/result': _identity
  5322. };
  5323. var _stepCatObject = {
  5324. '@@transducer/init': Object,
  5325. '@@transducer/step': function(result, input) {
  5326. return _objectAssign$1(
  5327. result,
  5328. _isArrayLike(input) ? objOf(input[0], input[1]) : input
  5329. );
  5330. },
  5331. '@@transducer/result': _identity
  5332. };
  5333. function _stepCat(obj) {
  5334. if (_isTransformer(obj)) {
  5335. return obj;
  5336. }
  5337. if (_isArrayLike(obj)) {
  5338. return _stepCatArray;
  5339. }
  5340. if (typeof obj === 'string') {
  5341. return _stepCatString;
  5342. }
  5343. if (typeof obj === 'object') {
  5344. return _stepCatObject;
  5345. }
  5346. throw new Error('Cannot create transformer for ' + obj);
  5347. }
  5348. /**
  5349. * Transforms the items of the list with the transducer and appends the
  5350. * transformed items to the accumulator using an appropriate iterator function
  5351. * based on the accumulator type.
  5352. *
  5353. * The accumulator can be an array, string, object or a transformer. Iterated
  5354. * items will be appended to arrays and concatenated to strings. Objects will
  5355. * be merged directly or 2-item arrays will be merged as key, value pairs.
  5356. *
  5357. * The accumulator can also be a transformer object that provides a 2-arity
  5358. * reducing iterator function, step, 0-arity initial value function, init, and
  5359. * 1-arity result extraction function result. The step function is used as the
  5360. * iterator function in reduce. The result function is used to convert the
  5361. * final accumulator into the return type and in most cases is R.identity. The
  5362. * init function is used to provide the initial accumulator.
  5363. *
  5364. * The iteration is performed with [`R.reduce`](#reduce) after initializing the
  5365. * transducer.
  5366. *
  5367. * @func
  5368. * @memberOf R
  5369. * @since v0.12.0
  5370. * @category List
  5371. * @sig a -> (b -> b) -> [c] -> a
  5372. * @param {*} acc The initial accumulator value.
  5373. * @param {Function} xf The transducer function. Receives a transformer and returns a transformer.
  5374. * @param {Array} list The list to iterate over.
  5375. * @return {*} The final, accumulated value.
  5376. * @see R.transduce
  5377. * @example
  5378. *
  5379. * const numbers = [1, 2, 3, 4];
  5380. * const transducer = R.compose(R.map(R.add(1)), R.take(2));
  5381. *
  5382. * R.into([], transducer, numbers); //=> [2, 3]
  5383. *
  5384. * const intoArray = R.into([]);
  5385. * intoArray(transducer, numbers); //=> [2, 3]
  5386. */
  5387. var into = _curry3(function into(acc, xf, list) {
  5388. return _isTransformer(acc) ?
  5389. _reduce(xf(acc), acc['@@transducer/init'](), list) :
  5390. _reduce(xf(_stepCat(acc)), _clone(acc, [], [], false), list);
  5391. });
  5392. /**
  5393. * Same as [`R.invertObj`](#invertObj), however this accounts for objects with
  5394. * duplicate values by putting the values into an array.
  5395. *
  5396. * @func
  5397. * @memberOf R
  5398. * @since v0.9.0
  5399. * @category Object
  5400. * @sig {s: x} -> {x: [ s, ... ]}
  5401. * @param {Object} obj The object or array to invert
  5402. * @return {Object} out A new object with keys in an array.
  5403. * @see R.invertObj
  5404. * @example
  5405. *
  5406. * const raceResultsByFirstName = {
  5407. * first: 'alice',
  5408. * second: 'jake',
  5409. * third: 'alice',
  5410. * };
  5411. * R.invert(raceResultsByFirstName);
  5412. * //=> { 'alice': ['first', 'third'], 'jake':['second'] }
  5413. */
  5414. var invert = _curry1(function invert(obj) {
  5415. var props = keys(obj);
  5416. var len = props.length;
  5417. var idx = 0;
  5418. var out = {};
  5419. while (idx < len) {
  5420. var key = props[idx];
  5421. var val = obj[key];
  5422. var list = _has(val, out) ? out[val] : (out[val] = []);
  5423. list[list.length] = key;
  5424. idx += 1;
  5425. }
  5426. return out;
  5427. });
  5428. /**
  5429. * Returns a new object with the keys of the given object as values, and the
  5430. * values of the given object, which are coerced to strings, as keys. Note
  5431. * that the last key found is preferred when handling the same value.
  5432. *
  5433. * @func
  5434. * @memberOf R
  5435. * @since v0.9.0
  5436. * @category Object
  5437. * @sig {s: x} -> {x: s}
  5438. * @param {Object} obj The object or array to invert
  5439. * @return {Object} out A new object
  5440. * @see R.invert
  5441. * @example
  5442. *
  5443. * const raceResults = {
  5444. * first: 'alice',
  5445. * second: 'jake'
  5446. * };
  5447. * R.invertObj(raceResults);
  5448. * //=> { 'alice': 'first', 'jake':'second' }
  5449. *
  5450. * // Alternatively:
  5451. * const raceResults = ['alice', 'jake'];
  5452. * R.invertObj(raceResults);
  5453. * //=> { 'alice': '0', 'jake':'1' }
  5454. */
  5455. var invertObj = _curry1(function invertObj(obj) {
  5456. var props = keys(obj);
  5457. var len = props.length;
  5458. var idx = 0;
  5459. var out = {};
  5460. while (idx < len) {
  5461. var key = props[idx];
  5462. out[obj[key]] = key;
  5463. idx += 1;
  5464. }
  5465. return out;
  5466. });
  5467. /**
  5468. * Turns a named method with a specified arity into a function that can be
  5469. * called directly supplied with arguments and a target object.
  5470. *
  5471. * The returned function is curried and accepts `arity + 1` parameters where
  5472. * the final parameter is the target object.
  5473. *
  5474. * @func
  5475. * @memberOf R
  5476. * @since v0.1.0
  5477. * @category Function
  5478. * @sig Number -> String -> (a -> b -> ... -> n -> Object -> *)
  5479. * @param {Number} arity Number of arguments the returned function should take
  5480. * before the target object.
  5481. * @param {String} method Name of any of the target object's methods to call.
  5482. * @return {Function} A new curried function.
  5483. * @see R.construct
  5484. * @example
  5485. *
  5486. * const sliceFrom = R.invoker(1, 'slice');
  5487. * sliceFrom(6, 'abcdefghijklm'); //=> 'ghijklm'
  5488. * const sliceFrom6 = R.invoker(2, 'slice')(6);
  5489. * sliceFrom6(8, 'abcdefghijklm'); //=> 'gh'
  5490. *
  5491. * const dog = {
  5492. * speak: async () => 'Woof!'
  5493. * };
  5494. * const speak = R.invoker(0, 'speak');
  5495. * speak(dog).then(console.log) //~> 'Woof!'
  5496. *
  5497. * @symb R.invoker(0, 'method')(o) = o['method']()
  5498. * @symb R.invoker(1, 'method')(a, o) = o['method'](a)
  5499. * @symb R.invoker(2, 'method')(a, b, o) = o['method'](a, b)
  5500. */
  5501. var invoker = _curry2(function invoker(arity, method) {
  5502. return curryN(arity + 1, function() {
  5503. var target = arguments[arity];
  5504. if (target != null && _isFunction(target[method])) {
  5505. return target[method].apply(target, Array.prototype.slice.call(arguments, 0, arity));
  5506. }
  5507. throw new TypeError(toString$1(target) + ' does not have a method named "' + method + '"');
  5508. });
  5509. });
  5510. /**
  5511. * See if an object (`val`) is an instance of the supplied constructor. This
  5512. * function will check up the inheritance chain, if any.
  5513. *
  5514. * @func
  5515. * @memberOf R
  5516. * @since v0.3.0
  5517. * @category Type
  5518. * @sig (* -> {*}) -> a -> Boolean
  5519. * @param {Object} ctor A constructor
  5520. * @param {*} val The value to test
  5521. * @return {Boolean}
  5522. * @example
  5523. *
  5524. * R.is(Object, {}); //=> true
  5525. * R.is(Number, 1); //=> true
  5526. * R.is(Object, 1); //=> false
  5527. * R.is(String, 's'); //=> true
  5528. * R.is(String, new String('')); //=> true
  5529. * R.is(Object, new String('')); //=> true
  5530. * R.is(Object, 's'); //=> false
  5531. * R.is(Number, {}); //=> false
  5532. */
  5533. var is = _curry2(function is(Ctor, val) {
  5534. return val != null && val.constructor === Ctor || val instanceof Ctor;
  5535. });
  5536. /**
  5537. * Returns `true` if the given value is its type's empty value; `false`
  5538. * otherwise.
  5539. *
  5540. * @func
  5541. * @memberOf R
  5542. * @since v0.1.0
  5543. * @category Logic
  5544. * @sig a -> Boolean
  5545. * @param {*} x
  5546. * @return {Boolean}
  5547. * @see R.empty
  5548. * @example
  5549. *
  5550. * R.isEmpty([1, 2, 3]); //=> false
  5551. * R.isEmpty([]); //=> true
  5552. * R.isEmpty(''); //=> true
  5553. * R.isEmpty(null); //=> false
  5554. * R.isEmpty({}); //=> true
  5555. * R.isEmpty({length: 0}); //=> false
  5556. */
  5557. var isEmpty = _curry1(function isEmpty(x) {
  5558. return x != null && equals(x, empty(x));
  5559. });
  5560. /**
  5561. * Returns a string made by inserting the `separator` between each element and
  5562. * concatenating all the elements into a single string.
  5563. *
  5564. * @func
  5565. * @memberOf R
  5566. * @since v0.1.0
  5567. * @category List
  5568. * @sig String -> [a] -> String
  5569. * @param {Number|String} separator The string used to separate the elements.
  5570. * @param {Array} xs The elements to join into a string.
  5571. * @return {String} str The string made by concatenating `xs` with `separator`.
  5572. * @see R.split
  5573. * @example
  5574. *
  5575. * const spacer = R.join(' ');
  5576. * spacer(['a', 2, 3.4]); //=> 'a 2 3.4'
  5577. * R.join('|', [1, 2, 3]); //=> '1|2|3'
  5578. */
  5579. var join = invoker(1, 'join');
  5580. /**
  5581. * juxt applies a list of functions to a list of values.
  5582. *
  5583. * @func
  5584. * @memberOf R
  5585. * @since v0.19.0
  5586. * @category Function
  5587. * @sig [(a, b, ..., m) -> n] -> ((a, b, ..., m) -> [n])
  5588. * @param {Array} fns An array of functions
  5589. * @return {Function} A function that returns a list of values after applying each of the original `fns` to its parameters.
  5590. * @see R.applySpec
  5591. * @example
  5592. *
  5593. * const getRange = R.juxt([Math.min, Math.max]);
  5594. * getRange(3, 4, 9, -3); //=> [-3, 9]
  5595. * @symb R.juxt([f, g, h])(a, b) = [f(a, b), g(a, b), h(a, b)]
  5596. */
  5597. var juxt = _curry1(function juxt(fns) {
  5598. return converge(function() { return Array.prototype.slice.call(arguments, 0); }, fns);
  5599. });
  5600. /**
  5601. * Returns a list containing the names of all the properties of the supplied
  5602. * object, including prototype properties.
  5603. * Note that the order of the output array is not guaranteed to be consistent
  5604. * across different JS platforms.
  5605. *
  5606. * @func
  5607. * @memberOf R
  5608. * @since v0.2.0
  5609. * @category Object
  5610. * @sig {k: v} -> [k]
  5611. * @param {Object} obj The object to extract properties from
  5612. * @return {Array} An array of the object's own and prototype properties.
  5613. * @see R.keys, R.valuesIn
  5614. * @example
  5615. *
  5616. * const F = function() { this.x = 'X'; };
  5617. * F.prototype.y = 'Y';
  5618. * const f = new F();
  5619. * R.keysIn(f); //=> ['x', 'y']
  5620. */
  5621. var keysIn = _curry1(function keysIn(obj) {
  5622. var prop;
  5623. var ks = [];
  5624. for (prop in obj) {
  5625. ks[ks.length] = prop;
  5626. }
  5627. return ks;
  5628. });
  5629. /**
  5630. * Returns the position of the last occurrence of an item in an array, or -1 if
  5631. * the item is not included in the array. [`R.equals`](#equals) is used to
  5632. * determine equality.
  5633. *
  5634. * @func
  5635. * @memberOf R
  5636. * @since v0.1.0
  5637. * @category List
  5638. * @sig a -> [a] -> Number
  5639. * @param {*} target The item to find.
  5640. * @param {Array} xs The array to search in.
  5641. * @return {Number} the index of the target, or -1 if the target is not found.
  5642. * @see R.indexOf
  5643. * @example
  5644. *
  5645. * R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6
  5646. * R.lastIndexOf(10, [1,2,3,4]); //=> -1
  5647. */
  5648. var lastIndexOf = _curry2(function lastIndexOf(target, xs) {
  5649. if (typeof xs.lastIndexOf === 'function' && !_isArray(xs)) {
  5650. return xs.lastIndexOf(target);
  5651. } else {
  5652. var idx = xs.length - 1;
  5653. while (idx >= 0) {
  5654. if (equals(xs[idx], target)) {
  5655. return idx;
  5656. }
  5657. idx -= 1;
  5658. }
  5659. return -1;
  5660. }
  5661. });
  5662. function _isNumber(x) {
  5663. return Object.prototype.toString.call(x) === '[object Number]';
  5664. }
  5665. /**
  5666. * Returns the number of elements in the array by returning `list.length`.
  5667. *
  5668. * @func
  5669. * @memberOf R
  5670. * @since v0.3.0
  5671. * @category List
  5672. * @sig [a] -> Number
  5673. * @param {Array} list The array to inspect.
  5674. * @return {Number} The length of the array.
  5675. * @example
  5676. *
  5677. * R.length([]); //=> 0
  5678. * R.length([1, 2, 3]); //=> 3
  5679. */
  5680. var length = _curry1(function length(list) {
  5681. return list != null && _isNumber(list.length) ? list.length : NaN;
  5682. });
  5683. /**
  5684. * Returns a lens for the given getter and setter functions. The getter "gets"
  5685. * the value of the focus; the setter "sets" the value of the focus. The setter
  5686. * should not mutate the data structure.
  5687. *
  5688. * @func
  5689. * @memberOf R
  5690. * @since v0.8.0
  5691. * @category Object
  5692. * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s
  5693. * @sig (s -> a) -> ((a, s) -> s) -> Lens s a
  5694. * @param {Function} getter
  5695. * @param {Function} setter
  5696. * @return {Lens}
  5697. * @see R.view, R.set, R.over, R.lensIndex, R.lensProp
  5698. * @example
  5699. *
  5700. * const xLens = R.lens(R.prop('x'), R.assoc('x'));
  5701. *
  5702. * R.view(xLens, {x: 1, y: 2}); //=> 1
  5703. * R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2}
  5704. * R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2}
  5705. */
  5706. var lens = _curry2(function lens(getter, setter) {
  5707. return function(toFunctorFn) {
  5708. return function(target) {
  5709. return map(
  5710. function(focus) {
  5711. return setter(focus, target);
  5712. },
  5713. toFunctorFn(getter(target))
  5714. );
  5715. };
  5716. };
  5717. });
  5718. /**
  5719. * Returns a lens whose focus is the specified index.
  5720. *
  5721. * @func
  5722. * @memberOf R
  5723. * @since v0.14.0
  5724. * @category Object
  5725. * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s
  5726. * @sig Number -> Lens s a
  5727. * @param {Number} n
  5728. * @return {Lens}
  5729. * @see R.view, R.set, R.over, R.nth
  5730. * @example
  5731. *
  5732. * const headLens = R.lensIndex(0);
  5733. *
  5734. * R.view(headLens, ['a', 'b', 'c']); //=> 'a'
  5735. * R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c']
  5736. * R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c']
  5737. */
  5738. var lensIndex = _curry1(function lensIndex(n) {
  5739. return lens(nth(n), update(n));
  5740. });
  5741. /**
  5742. * Returns a lens whose focus is the specified path.
  5743. *
  5744. * @func
  5745. * @memberOf R
  5746. * @since v0.19.0
  5747. * @category Object
  5748. * @typedefn Idx = String | Int
  5749. * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s
  5750. * @sig [Idx] -> Lens s a
  5751. * @param {Array} path The path to use.
  5752. * @return {Lens}
  5753. * @see R.view, R.set, R.over
  5754. * @example
  5755. *
  5756. * const xHeadYLens = R.lensPath(['x', 0, 'y']);
  5757. *
  5758. * R.view(xHeadYLens, {x: [{y: 2, z: 3}, {y: 4, z: 5}]});
  5759. * //=> 2
  5760. * R.set(xHeadYLens, 1, {x: [{y: 2, z: 3}, {y: 4, z: 5}]});
  5761. * //=> {x: [{y: 1, z: 3}, {y: 4, z: 5}]}
  5762. * R.over(xHeadYLens, R.negate, {x: [{y: 2, z: 3}, {y: 4, z: 5}]});
  5763. * //=> {x: [{y: -2, z: 3}, {y: 4, z: 5}]}
  5764. */
  5765. var lensPath = _curry1(function lensPath(p) {
  5766. return lens(path(p), assocPath(p));
  5767. });
  5768. /**
  5769. * Returns a lens whose focus is the specified property.
  5770. *
  5771. * @func
  5772. * @memberOf R
  5773. * @since v0.14.0
  5774. * @category Object
  5775. * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s
  5776. * @sig String -> Lens s a
  5777. * @param {String} k
  5778. * @return {Lens}
  5779. * @see R.view, R.set, R.over
  5780. * @example
  5781. *
  5782. * const xLens = R.lensProp('x');
  5783. *
  5784. * R.view(xLens, {x: 1, y: 2}); //=> 1
  5785. * R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2}
  5786. * R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2}
  5787. */
  5788. var lensProp = _curry1(function lensProp(k) {
  5789. return lens(prop(k), assoc(k));
  5790. });
  5791. /**
  5792. * Returns `true` if the first argument is less than the second; `false`
  5793. * otherwise.
  5794. *
  5795. * @func
  5796. * @memberOf R
  5797. * @since v0.1.0
  5798. * @category Relation
  5799. * @sig Ord a => a -> a -> Boolean
  5800. * @param {*} a
  5801. * @param {*} b
  5802. * @return {Boolean}
  5803. * @see R.gt
  5804. * @example
  5805. *
  5806. * R.lt(2, 1); //=> false
  5807. * R.lt(2, 2); //=> false
  5808. * R.lt(2, 3); //=> true
  5809. * R.lt('a', 'z'); //=> true
  5810. * R.lt('z', 'a'); //=> false
  5811. */
  5812. var lt = _curry2(function lt(a, b) { return a < b; });
  5813. /**
  5814. * Returns `true` if the first argument is less than or equal to the second;
  5815. * `false` otherwise.
  5816. *
  5817. * @func
  5818. * @memberOf R
  5819. * @since v0.1.0
  5820. * @category Relation
  5821. * @sig Ord a => a -> a -> Boolean
  5822. * @param {Number} a
  5823. * @param {Number} b
  5824. * @return {Boolean}
  5825. * @see R.gte
  5826. * @example
  5827. *
  5828. * R.lte(2, 1); //=> false
  5829. * R.lte(2, 2); //=> true
  5830. * R.lte(2, 3); //=> true
  5831. * R.lte('a', 'z'); //=> true
  5832. * R.lte('z', 'a'); //=> false
  5833. */
  5834. var lte = _curry2(function lte(a, b) { return a <= b; });
  5835. /**
  5836. * The `mapAccum` function behaves like a combination of map and reduce; it
  5837. * applies a function to each element of a list, passing an accumulating
  5838. * parameter from left to right, and returning a final value of this
  5839. * accumulator together with the new list.
  5840. *
  5841. * The iterator function receives two arguments, *acc* and *value*, and should
  5842. * return a tuple *[acc, value]*.
  5843. *
  5844. * @func
  5845. * @memberOf R
  5846. * @since v0.10.0
  5847. * @category List
  5848. * @sig ((acc, x) -> (acc, y)) -> acc -> [x] -> (acc, [y])
  5849. * @param {Function} fn The function to be called on every element of the input `list`.
  5850. * @param {*} acc The accumulator value.
  5851. * @param {Array} list The list to iterate over.
  5852. * @return {*} The final, accumulated value.
  5853. * @see R.scan, R.addIndex, R.mapAccumRight
  5854. * @example
  5855. *
  5856. * const digits = ['1', '2', '3', '4'];
  5857. * const appender = (a, b) => [a + b, a + b];
  5858. *
  5859. * R.mapAccum(appender, 0, digits); //=> ['01234', ['01', '012', '0123', '01234']]
  5860. * @symb R.mapAccum(f, a, [b, c, d]) = [
  5861. * f(f(f(a, b)[0], c)[0], d)[0],
  5862. * [
  5863. * f(a, b)[1],
  5864. * f(f(a, b)[0], c)[1],
  5865. * f(f(f(a, b)[0], c)[0], d)[1]
  5866. * ]
  5867. * ]
  5868. */
  5869. var mapAccum = _curry3(function mapAccum(fn, acc, list) {
  5870. var idx = 0;
  5871. var len = list.length;
  5872. var result = [];
  5873. var tuple = [acc];
  5874. while (idx < len) {
  5875. tuple = fn(tuple[0], list[idx]);
  5876. result[idx] = tuple[1];
  5877. idx += 1;
  5878. }
  5879. return [tuple[0], result];
  5880. });
  5881. /**
  5882. * The `mapAccumRight` function behaves like a combination of map and reduce; it
  5883. * applies a function to each element of a list, passing an accumulating
  5884. * parameter from right to left, and returning a final value of this
  5885. * accumulator together with the new list.
  5886. *
  5887. * Similar to [`mapAccum`](#mapAccum), except moves through the input list from
  5888. * the right to the left.
  5889. *
  5890. * The iterator function receives two arguments, *acc* and *value*, and should
  5891. * return a tuple *[acc, value]*.
  5892. *
  5893. * @func
  5894. * @memberOf R
  5895. * @since v0.10.0
  5896. * @category List
  5897. * @sig ((acc, x) -> (acc, y)) -> acc -> [x] -> (acc, [y])
  5898. * @param {Function} fn The function to be called on every element of the input `list`.
  5899. * @param {*} acc The accumulator value.
  5900. * @param {Array} list The list to iterate over.
  5901. * @return {*} The final, accumulated value.
  5902. * @see R.addIndex, R.mapAccum
  5903. * @example
  5904. *
  5905. * const digits = ['1', '2', '3', '4'];
  5906. * const appender = (a, b) => [b + a, b + a];
  5907. *
  5908. * R.mapAccumRight(appender, 5, digits); //=> ['12345', ['12345', '2345', '345', '45']]
  5909. * @symb R.mapAccumRight(f, a, [b, c, d]) = [
  5910. * f(f(f(a, d)[0], c)[0], b)[0],
  5911. * [
  5912. * f(a, d)[1],
  5913. * f(f(a, d)[0], c)[1],
  5914. * f(f(f(a, d)[0], c)[0], b)[1]
  5915. * ]
  5916. * ]
  5917. */
  5918. var mapAccumRight = _curry3(function mapAccumRight(fn, acc, list) {
  5919. var idx = list.length - 1;
  5920. var result = [];
  5921. var tuple = [acc];
  5922. while (idx >= 0) {
  5923. tuple = fn(tuple[0], list[idx]);
  5924. result[idx] = tuple[1];
  5925. idx -= 1;
  5926. }
  5927. return [tuple[0], result];
  5928. });
  5929. /**
  5930. * An Object-specific version of [`map`](#map). The function is applied to three
  5931. * arguments: *(value, key, obj)*. If only the value is significant, use
  5932. * [`map`](#map) instead.
  5933. *
  5934. * @func
  5935. * @memberOf R
  5936. * @since v0.9.0
  5937. * @category Object
  5938. * @sig ((*, String, Object) -> *) -> Object -> Object
  5939. * @param {Function} fn
  5940. * @param {Object} obj
  5941. * @return {Object}
  5942. * @see R.map
  5943. * @example
  5944. *
  5945. * const xyz = { x: 1, y: 2, z: 3 };
  5946. * const prependKeyAndDouble = (num, key, obj) => key + (num * 2);
  5947. *
  5948. * R.mapObjIndexed(prependKeyAndDouble, xyz); //=> { x: 'x2', y: 'y4', z: 'z6' }
  5949. */
  5950. var mapObjIndexed = _curry2(function mapObjIndexed(fn, obj) {
  5951. return _reduce(function(acc, key) {
  5952. acc[key] = fn(obj[key], key, obj);
  5953. return acc;
  5954. }, {}, keys(obj));
  5955. });
  5956. /**
  5957. * Tests a regular expression against a String. Note that this function will
  5958. * return an empty array when there are no matches. This differs from
  5959. * [`String.prototype.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match)
  5960. * which returns `null` when there are no matches.
  5961. *
  5962. * @func
  5963. * @memberOf R
  5964. * @since v0.1.0
  5965. * @category String
  5966. * @sig RegExp -> String -> [String | Undefined]
  5967. * @param {RegExp} rx A regular expression.
  5968. * @param {String} str The string to match against
  5969. * @return {Array} The list of matches or empty array.
  5970. * @see R.test
  5971. * @example
  5972. *
  5973. * R.match(/([a-z]a)/g, 'bananas'); //=> ['ba', 'na', 'na']
  5974. * R.match(/a/, 'b'); //=> []
  5975. * R.match(/a/, null); //=> TypeError: null does not have a method named "match"
  5976. */
  5977. var match = _curry2(function match(rx, str) {
  5978. return str.match(rx) || [];
  5979. });
  5980. /**
  5981. * `mathMod` behaves like the modulo operator should mathematically, unlike the
  5982. * `%` operator (and by extension, [`R.modulo`](#modulo)). So while
  5983. * `-17 % 5` is `-2`, `mathMod(-17, 5)` is `3`. `mathMod` requires Integer
  5984. * arguments, and returns NaN when the modulus is zero or negative.
  5985. *
  5986. * @func
  5987. * @memberOf R
  5988. * @since v0.3.0
  5989. * @category Math
  5990. * @sig Number -> Number -> Number
  5991. * @param {Number} m The dividend.
  5992. * @param {Number} p the modulus.
  5993. * @return {Number} The result of `b mod a`.
  5994. * @see R.modulo
  5995. * @example
  5996. *
  5997. * R.mathMod(-17, 5); //=> 3
  5998. * R.mathMod(17, 5); //=> 2
  5999. * R.mathMod(17, -5); //=> NaN
  6000. * R.mathMod(17, 0); //=> NaN
  6001. * R.mathMod(17.2, 5); //=> NaN
  6002. * R.mathMod(17, 5.3); //=> NaN
  6003. *
  6004. * const clock = R.mathMod(R.__, 12);
  6005. * clock(15); //=> 3
  6006. * clock(24); //=> 0
  6007. *
  6008. * const seventeenMod = R.mathMod(17);
  6009. * seventeenMod(3); //=> 2
  6010. * seventeenMod(4); //=> 1
  6011. * seventeenMod(10); //=> 7
  6012. */
  6013. var mathMod = _curry2(function mathMod(m, p) {
  6014. if (!_isInteger(m)) { return NaN; }
  6015. if (!_isInteger(p) || p < 1) { return NaN; }
  6016. return ((m % p) + p) % p;
  6017. });
  6018. /**
  6019. * Takes a function and two values, and returns whichever value produces the
  6020. * larger result when passed to the provided function.
  6021. *
  6022. * @func
  6023. * @memberOf R
  6024. * @since v0.8.0
  6025. * @category Relation
  6026. * @sig Ord b => (a -> b) -> a -> a -> a
  6027. * @param {Function} f
  6028. * @param {*} a
  6029. * @param {*} b
  6030. * @return {*}
  6031. * @see R.max, R.minBy
  6032. * @example
  6033. *
  6034. * // square :: Number -> Number
  6035. * const square = n => n * n;
  6036. *
  6037. * R.maxBy(square, -3, 2); //=> -3
  6038. *
  6039. * R.reduce(R.maxBy(square), 0, [3, -5, 4, 1, -2]); //=> -5
  6040. * R.reduce(R.maxBy(square), 0, []); //=> 0
  6041. */
  6042. var maxBy = _curry3(function maxBy(f, a, b) {
  6043. return f(b) > f(a) ? b : a;
  6044. });
  6045. /**
  6046. * Adds together all the elements of a list.
  6047. *
  6048. * @func
  6049. * @memberOf R
  6050. * @since v0.1.0
  6051. * @category Math
  6052. * @sig [Number] -> Number
  6053. * @param {Array} list An array of numbers
  6054. * @return {Number} The sum of all the numbers in the list.
  6055. * @see R.reduce
  6056. * @example
  6057. *
  6058. * R.sum([2,4,6,8,100,1]); //=> 121
  6059. */
  6060. var sum = reduce(add, 0);
  6061. /**
  6062. * Returns the mean of the given list of numbers.
  6063. *
  6064. * @func
  6065. * @memberOf R
  6066. * @since v0.14.0
  6067. * @category Math
  6068. * @sig [Number] -> Number
  6069. * @param {Array} list
  6070. * @return {Number}
  6071. * @see R.median
  6072. * @example
  6073. *
  6074. * R.mean([2, 7, 9]); //=> 6
  6075. * R.mean([]); //=> NaN
  6076. */
  6077. var mean = _curry1(function mean(list) {
  6078. return sum(list) / list.length;
  6079. });
  6080. /**
  6081. * Returns the median of the given list of numbers.
  6082. *
  6083. * @func
  6084. * @memberOf R
  6085. * @since v0.14.0
  6086. * @category Math
  6087. * @sig [Number] -> Number
  6088. * @param {Array} list
  6089. * @return {Number}
  6090. * @see R.mean
  6091. * @example
  6092. *
  6093. * R.median([2, 9, 7]); //=> 7
  6094. * R.median([7, 2, 10, 9]); //=> 8
  6095. * R.median([]); //=> NaN
  6096. */
  6097. var median = _curry1(function median(list) {
  6098. var len = list.length;
  6099. if (len === 0) {
  6100. return NaN;
  6101. }
  6102. var width = 2 - len % 2;
  6103. var idx = (len - width) / 2;
  6104. return mean(Array.prototype.slice.call(list, 0).sort(function(a, b) {
  6105. return a < b ? -1 : a > b ? 1 : 0;
  6106. }).slice(idx, idx + width));
  6107. });
  6108. /**
  6109. * Creates a new function that, when invoked, caches the result of calling `fn`
  6110. * for a given argument set and returns the result. Subsequent calls to the
  6111. * memoized `fn` with the same argument set will not result in an additional
  6112. * call to `fn`; instead, the cached result for that set of arguments will be
  6113. * returned.
  6114. *
  6115. *
  6116. * @func
  6117. * @memberOf R
  6118. * @since v0.24.0
  6119. * @category Function
  6120. * @sig (*... -> String) -> (*... -> a) -> (*... -> a)
  6121. * @param {Function} fn The function to generate the cache key.
  6122. * @param {Function} fn The function to memoize.
  6123. * @return {Function} Memoized version of `fn`.
  6124. * @example
  6125. *
  6126. * let count = 0;
  6127. * const factorial = R.memoizeWith(R.identity, n => {
  6128. * count += 1;
  6129. * return R.product(R.range(1, n + 1));
  6130. * });
  6131. * factorial(5); //=> 120
  6132. * factorial(5); //=> 120
  6133. * factorial(5); //=> 120
  6134. * count; //=> 1
  6135. */
  6136. var memoizeWith = _curry2(function memoizeWith(mFn, fn) {
  6137. var cache = {};
  6138. return _arity(fn.length, function() {
  6139. var key = mFn.apply(this, arguments);
  6140. if (!_has(key, cache)) {
  6141. cache[key] = fn.apply(this, arguments);
  6142. }
  6143. return cache[key];
  6144. });
  6145. });
  6146. /**
  6147. * Create a new object with the own properties of the first object merged with
  6148. * the own properties of the second object. If a key exists in both objects,
  6149. * the value from the second object will be used.
  6150. *
  6151. * @func
  6152. * @memberOf R
  6153. * @since v0.1.0
  6154. * @category Object
  6155. * @sig {k: v} -> {k: v} -> {k: v}
  6156. * @param {Object} l
  6157. * @param {Object} r
  6158. * @return {Object}
  6159. * @see R.mergeRight, R.mergeDeepRight, R.mergeWith, R.mergeWithKey
  6160. * @deprecated since v0.26.0
  6161. * @example
  6162. *
  6163. * R.merge({ 'name': 'fred', 'age': 10 }, { 'age': 40 });
  6164. * //=> { 'name': 'fred', 'age': 40 }
  6165. *
  6166. * const withDefaults = R.merge({x: 0, y: 0});
  6167. * withDefaults({y: 2}); //=> {x: 0, y: 2}
  6168. * @symb R.merge(a, b) = {...a, ...b}
  6169. */
  6170. var merge = _curry2(function merge(l, r) {
  6171. return _objectAssign$1({}, l, r);
  6172. });
  6173. /**
  6174. * Merges a list of objects together into one object.
  6175. *
  6176. * @func
  6177. * @memberOf R
  6178. * @since v0.10.0
  6179. * @category List
  6180. * @sig [{k: v}] -> {k: v}
  6181. * @param {Array} list An array of objects
  6182. * @return {Object} A merged object.
  6183. * @see R.reduce
  6184. * @example
  6185. *
  6186. * R.mergeAll([{foo:1},{bar:2},{baz:3}]); //=> {foo:1,bar:2,baz:3}
  6187. * R.mergeAll([{foo:1},{foo:2},{bar:2}]); //=> {foo:2,bar:2}
  6188. * @symb R.mergeAll([{ x: 1 }, { y: 2 }, { z: 3 }]) = { x: 1, y: 2, z: 3 }
  6189. */
  6190. var mergeAll = _curry1(function mergeAll(list) {
  6191. return _objectAssign$1.apply(null, [{}].concat(list));
  6192. });
  6193. /**
  6194. * Creates a new object with the own properties of the two provided objects. If
  6195. * a key exists in both objects, the provided function is applied to the key
  6196. * and the values associated with the key in each object, with the result being
  6197. * used as the value associated with the key in the returned object.
  6198. *
  6199. * @func
  6200. * @memberOf R
  6201. * @since v0.19.0
  6202. * @category Object
  6203. * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}
  6204. * @param {Function} fn
  6205. * @param {Object} l
  6206. * @param {Object} r
  6207. * @return {Object}
  6208. * @see R.mergeDeepWithKey, R.merge, R.mergeWith
  6209. * @example
  6210. *
  6211. * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r
  6212. * R.mergeWithKey(concatValues,
  6213. * { a: true, thing: 'foo', values: [10, 20] },
  6214. * { b: true, thing: 'bar', values: [15, 35] });
  6215. * //=> { a: true, b: true, thing: 'bar', values: [10, 20, 15, 35] }
  6216. * @symb R.mergeWithKey(f, { x: 1, y: 2 }, { y: 5, z: 3 }) = { x: 1, y: f('y', 2, 5), z: 3 }
  6217. */
  6218. var mergeWithKey = _curry3(function mergeWithKey(fn, l, r) {
  6219. var result = {};
  6220. var k;
  6221. for (k in l) {
  6222. if (_has(k, l)) {
  6223. result[k] = _has(k, r) ? fn(k, l[k], r[k]) : l[k];
  6224. }
  6225. }
  6226. for (k in r) {
  6227. if (_has(k, r) && !(_has(k, result))) {
  6228. result[k] = r[k];
  6229. }
  6230. }
  6231. return result;
  6232. });
  6233. /**
  6234. * Creates a new object with the own properties of the two provided objects.
  6235. * If a key exists in both objects:
  6236. * - and both associated values are also objects then the values will be
  6237. * recursively merged.
  6238. * - otherwise the provided function is applied to the key and associated values
  6239. * using the resulting value as the new value associated with the key.
  6240. * If a key only exists in one object, the value will be associated with the key
  6241. * of the resulting object.
  6242. *
  6243. * @func
  6244. * @memberOf R
  6245. * @since v0.24.0
  6246. * @category Object
  6247. * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}
  6248. * @param {Function} fn
  6249. * @param {Object} lObj
  6250. * @param {Object} rObj
  6251. * @return {Object}
  6252. * @see R.mergeWithKey, R.mergeDeepWith
  6253. * @example
  6254. *
  6255. * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r
  6256. * R.mergeDeepWithKey(concatValues,
  6257. * { a: true, c: { thing: 'foo', values: [10, 20] }},
  6258. * { b: true, c: { thing: 'bar', values: [15, 35] }});
  6259. * //=> { a: true, b: true, c: { thing: 'bar', values: [10, 20, 15, 35] }}
  6260. */
  6261. var mergeDeepWithKey = _curry3(function mergeDeepWithKey(fn, lObj, rObj) {
  6262. return mergeWithKey(function(k, lVal, rVal) {
  6263. if (_isObject(lVal) && _isObject(rVal)) {
  6264. return mergeDeepWithKey(fn, lVal, rVal);
  6265. } else {
  6266. return fn(k, lVal, rVal);
  6267. }
  6268. }, lObj, rObj);
  6269. });
  6270. /**
  6271. * Creates a new object with the own properties of the first object merged with
  6272. * the own properties of the second object. If a key exists in both objects:
  6273. * - and both values are objects, the two values will be recursively merged
  6274. * - otherwise the value from the first object will be used.
  6275. *
  6276. * @func
  6277. * @memberOf R
  6278. * @since v0.24.0
  6279. * @category Object
  6280. * @sig {a} -> {a} -> {a}
  6281. * @param {Object} lObj
  6282. * @param {Object} rObj
  6283. * @return {Object}
  6284. * @see R.merge, R.mergeDeepRight, R.mergeDeepWith, R.mergeDeepWithKey
  6285. * @example
  6286. *
  6287. * R.mergeDeepLeft({ name: 'fred', age: 10, contact: { email: 'moo@example.com' }},
  6288. * { age: 40, contact: { email: 'baa@example.com' }});
  6289. * //=> { name: 'fred', age: 10, contact: { email: 'moo@example.com' }}
  6290. */
  6291. var mergeDeepLeft = _curry2(function mergeDeepLeft(lObj, rObj) {
  6292. return mergeDeepWithKey(function(k, lVal, rVal) {
  6293. return lVal;
  6294. }, lObj, rObj);
  6295. });
  6296. /**
  6297. * Creates a new object with the own properties of the first object merged with
  6298. * the own properties of the second object. If a key exists in both objects:
  6299. * - and both values are objects, the two values will be recursively merged
  6300. * - otherwise the value from the second object will be used.
  6301. *
  6302. * @func
  6303. * @memberOf R
  6304. * @since v0.24.0
  6305. * @category Object
  6306. * @sig {a} -> {a} -> {a}
  6307. * @param {Object} lObj
  6308. * @param {Object} rObj
  6309. * @return {Object}
  6310. * @see R.merge, R.mergeDeepLeft, R.mergeDeepWith, R.mergeDeepWithKey
  6311. * @example
  6312. *
  6313. * R.mergeDeepRight({ name: 'fred', age: 10, contact: { email: 'moo@example.com' }},
  6314. * { age: 40, contact: { email: 'baa@example.com' }});
  6315. * //=> { name: 'fred', age: 40, contact: { email: 'baa@example.com' }}
  6316. */
  6317. var mergeDeepRight = _curry2(function mergeDeepRight(lObj, rObj) {
  6318. return mergeDeepWithKey(function(k, lVal, rVal) {
  6319. return rVal;
  6320. }, lObj, rObj);
  6321. });
  6322. /**
  6323. * Creates a new object with the own properties of the two provided objects.
  6324. * If a key exists in both objects:
  6325. * - and both associated values are also objects then the values will be
  6326. * recursively merged.
  6327. * - otherwise the provided function is applied to associated values using the
  6328. * resulting value as the new value associated with the key.
  6329. * If a key only exists in one object, the value will be associated with the key
  6330. * of the resulting object.
  6331. *
  6332. * @func
  6333. * @memberOf R
  6334. * @since v0.24.0
  6335. * @category Object
  6336. * @sig ((a, a) -> a) -> {a} -> {a} -> {a}
  6337. * @param {Function} fn
  6338. * @param {Object} lObj
  6339. * @param {Object} rObj
  6340. * @return {Object}
  6341. * @see R.mergeWith, R.mergeDeepWithKey
  6342. * @example
  6343. *
  6344. * R.mergeDeepWith(R.concat,
  6345. * { a: true, c: { values: [10, 20] }},
  6346. * { b: true, c: { values: [15, 35] }});
  6347. * //=> { a: true, b: true, c: { values: [10, 20, 15, 35] }}
  6348. */
  6349. var mergeDeepWith = _curry3(function mergeDeepWith(fn, lObj, rObj) {
  6350. return mergeDeepWithKey(function(k, lVal, rVal) {
  6351. return fn(lVal, rVal);
  6352. }, lObj, rObj);
  6353. });
  6354. /**
  6355. * Create a new object with the own properties of the first object merged with
  6356. * the own properties of the second object. If a key exists in both objects,
  6357. * the value from the first object will be used.
  6358. *
  6359. * @func
  6360. * @memberOf R
  6361. * @since v0.26.0
  6362. * @category Object
  6363. * @sig {k: v} -> {k: v} -> {k: v}
  6364. * @param {Object} l
  6365. * @param {Object} r
  6366. * @return {Object}
  6367. * @see R.mergeRight, R.mergeDeepLeft, R.mergeWith, R.mergeWithKey
  6368. * @example
  6369. *
  6370. * R.mergeLeft({ 'age': 40 }, { 'name': 'fred', 'age': 10 });
  6371. * //=> { 'name': 'fred', 'age': 40 }
  6372. *
  6373. * const resetToDefault = R.mergeLeft({x: 0});
  6374. * resetToDefault({x: 5, y: 2}); //=> {x: 0, y: 2}
  6375. * @symb R.mergeLeft(a, b) = {...b, ...a}
  6376. */
  6377. var mergeLeft = _curry2(function mergeLeft(l, r) {
  6378. return _objectAssign$1({}, r, l);
  6379. });
  6380. /**
  6381. * Create a new object with the own properties of the first object merged with
  6382. * the own properties of the second object. If a key exists in both objects,
  6383. * the value from the second object will be used.
  6384. *
  6385. * @func
  6386. * @memberOf R
  6387. * @since v0.26.0
  6388. * @category Object
  6389. * @sig {k: v} -> {k: v} -> {k: v}
  6390. * @param {Object} l
  6391. * @param {Object} r
  6392. * @return {Object}
  6393. * @see R.mergeLeft, R.mergeDeepRight, R.mergeWith, R.mergeWithKey
  6394. * @example
  6395. *
  6396. * R.mergeRight({ 'name': 'fred', 'age': 10 }, { 'age': 40 });
  6397. * //=> { 'name': 'fred', 'age': 40 }
  6398. *
  6399. * const withDefaults = R.mergeRight({x: 0, y: 0});
  6400. * withDefaults({y: 2}); //=> {x: 0, y: 2}
  6401. * @symb R.mergeRight(a, b) = {...a, ...b}
  6402. */
  6403. var mergeRight = _curry2(function mergeRight(l, r) {
  6404. return _objectAssign$1({}, l, r);
  6405. });
  6406. /**
  6407. * Creates a new object with the own properties of the two provided objects. If
  6408. * a key exists in both objects, the provided function is applied to the values
  6409. * associated with the key in each object, with the result being used as the
  6410. * value associated with the key in the returned object.
  6411. *
  6412. * @func
  6413. * @memberOf R
  6414. * @since v0.19.0
  6415. * @category Object
  6416. * @sig ((a, a) -> a) -> {a} -> {a} -> {a}
  6417. * @param {Function} fn
  6418. * @param {Object} l
  6419. * @param {Object} r
  6420. * @return {Object}
  6421. * @see R.mergeDeepWith, R.merge, R.mergeWithKey
  6422. * @example
  6423. *
  6424. * R.mergeWith(R.concat,
  6425. * { a: true, values: [10, 20] },
  6426. * { b: true, values: [15, 35] });
  6427. * //=> { a: true, b: true, values: [10, 20, 15, 35] }
  6428. */
  6429. var mergeWith = _curry3(function mergeWith(fn, l, r) {
  6430. return mergeWithKey(function(_, _l, _r) {
  6431. return fn(_l, _r);
  6432. }, l, r);
  6433. });
  6434. /**
  6435. * Returns the smaller of its two arguments.
  6436. *
  6437. * @func
  6438. * @memberOf R
  6439. * @since v0.1.0
  6440. * @category Relation
  6441. * @sig Ord a => a -> a -> a
  6442. * @param {*} a
  6443. * @param {*} b
  6444. * @return {*}
  6445. * @see R.minBy, R.max
  6446. * @example
  6447. *
  6448. * R.min(789, 123); //=> 123
  6449. * R.min('a', 'b'); //=> 'a'
  6450. */
  6451. var min = _curry2(function min(a, b) { return b < a ? b : a; });
  6452. /**
  6453. * Takes a function and two values, and returns whichever value produces the
  6454. * smaller result when passed to the provided function.
  6455. *
  6456. * @func
  6457. * @memberOf R
  6458. * @since v0.8.0
  6459. * @category Relation
  6460. * @sig Ord b => (a -> b) -> a -> a -> a
  6461. * @param {Function} f
  6462. * @param {*} a
  6463. * @param {*} b
  6464. * @return {*}
  6465. * @see R.min, R.maxBy
  6466. * @example
  6467. *
  6468. * // square :: Number -> Number
  6469. * const square = n => n * n;
  6470. *
  6471. * R.minBy(square, -3, 2); //=> 2
  6472. *
  6473. * R.reduce(R.minBy(square), Infinity, [3, -5, 4, 1, -2]); //=> 1
  6474. * R.reduce(R.minBy(square), Infinity, []); //=> Infinity
  6475. */
  6476. var minBy = _curry3(function minBy(f, a, b) {
  6477. return f(b) < f(a) ? b : a;
  6478. });
  6479. /**
  6480. * Divides the first parameter by the second and returns the remainder. Note
  6481. * that this function preserves the JavaScript-style behavior for modulo. For
  6482. * mathematical modulo see [`mathMod`](#mathMod).
  6483. *
  6484. * @func
  6485. * @memberOf R
  6486. * @since v0.1.1
  6487. * @category Math
  6488. * @sig Number -> Number -> Number
  6489. * @param {Number} a The value to the divide.
  6490. * @param {Number} b The pseudo-modulus
  6491. * @return {Number} The result of `b % a`.
  6492. * @see R.mathMod
  6493. * @example
  6494. *
  6495. * R.modulo(17, 3); //=> 2
  6496. * // JS behavior:
  6497. * R.modulo(-17, 3); //=> -2
  6498. * R.modulo(17, -3); //=> 2
  6499. *
  6500. * const isOdd = R.modulo(R.__, 2);
  6501. * isOdd(42); //=> 0
  6502. * isOdd(21); //=> 1
  6503. */
  6504. var modulo = _curry2(function modulo(a, b) { return a % b; });
  6505. /**
  6506. * Move an item, at index `from`, to index `to`, in a list of elements.
  6507. * A new list will be created containing the new elements order.
  6508. *
  6509. * @func
  6510. * @memberOf R
  6511. * @since v0.27.1
  6512. * @category List
  6513. * @sig Number -> Number -> [a] -> [a]
  6514. * @param {Number} from The source index
  6515. * @param {Number} to The destination index
  6516. * @param {Array} list The list which will serve to realise the move
  6517. * @return {Array} The new list reordered
  6518. * @example
  6519. *
  6520. * R.move(0, 2, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['b', 'c', 'a', 'd', 'e', 'f']
  6521. * R.move(-1, 0, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['f', 'a', 'b', 'c', 'd', 'e'] list rotation
  6522. */
  6523. var move = _curry3(function(from, to, list) {
  6524. var length = list.length;
  6525. var result = list.slice();
  6526. var positiveFrom = from < 0 ? length + from : from;
  6527. var positiveTo = to < 0 ? length + to : to;
  6528. var item = result.splice(positiveFrom, 1);
  6529. return positiveFrom < 0 || positiveFrom >= list.length
  6530. || positiveTo < 0 || positiveTo >= list.length
  6531. ? list
  6532. : []
  6533. .concat(result.slice(0, positiveTo))
  6534. .concat(item)
  6535. .concat(result.slice(positiveTo, list.length));
  6536. });
  6537. /**
  6538. * Multiplies two numbers. Equivalent to `a * b` but curried.
  6539. *
  6540. * @func
  6541. * @memberOf R
  6542. * @since v0.1.0
  6543. * @category Math
  6544. * @sig Number -> Number -> Number
  6545. * @param {Number} a The first value.
  6546. * @param {Number} b The second value.
  6547. * @return {Number} The result of `a * b`.
  6548. * @see R.divide
  6549. * @example
  6550. *
  6551. * const double = R.multiply(2);
  6552. * const triple = R.multiply(3);
  6553. * double(3); //=> 6
  6554. * triple(4); //=> 12
  6555. * R.multiply(2, 5); //=> 10
  6556. */
  6557. var multiply = _curry2(function multiply(a, b) { return a * b; });
  6558. /**
  6559. * Negates its argument.
  6560. *
  6561. * @func
  6562. * @memberOf R
  6563. * @since v0.9.0
  6564. * @category Math
  6565. * @sig Number -> Number
  6566. * @param {Number} n
  6567. * @return {Number}
  6568. * @example
  6569. *
  6570. * R.negate(42); //=> -42
  6571. */
  6572. var negate = _curry1(function negate(n) { return -n; });
  6573. /**
  6574. * Returns `true` if no elements of the list match the predicate, `false`
  6575. * otherwise.
  6576. *
  6577. * Dispatches to the `all` method of the second argument, if present.
  6578. *
  6579. * Acts as a transducer if a transformer is given in list position.
  6580. *
  6581. * @func
  6582. * @memberOf R
  6583. * @since v0.12.0
  6584. * @category List
  6585. * @sig (a -> Boolean) -> [a] -> Boolean
  6586. * @param {Function} fn The predicate function.
  6587. * @param {Array} list The array to consider.
  6588. * @return {Boolean} `true` if the predicate is not satisfied by every element, `false` otherwise.
  6589. * @see R.all, R.any
  6590. * @example
  6591. *
  6592. * const isEven = n => n % 2 === 0;
  6593. * const isOdd = n => n % 2 === 1;
  6594. *
  6595. * R.none(isEven, [1, 3, 5, 7, 9, 11]); //=> true
  6596. * R.none(isOdd, [1, 3, 5, 7, 8, 11]); //=> false
  6597. */
  6598. var none = _curry2(function none(fn, input) {
  6599. return all(_complement(fn), input);
  6600. });
  6601. /**
  6602. * Returns a function which returns its nth argument.
  6603. *
  6604. * @func
  6605. * @memberOf R
  6606. * @since v0.9.0
  6607. * @category Function
  6608. * @sig Number -> *... -> *
  6609. * @param {Number} n
  6610. * @return {Function}
  6611. * @example
  6612. *
  6613. * R.nthArg(1)('a', 'b', 'c'); //=> 'b'
  6614. * R.nthArg(-1)('a', 'b', 'c'); //=> 'c'
  6615. * @symb R.nthArg(-1)(a, b, c) = c
  6616. * @symb R.nthArg(0)(a, b, c) = a
  6617. * @symb R.nthArg(1)(a, b, c) = b
  6618. */
  6619. var nthArg = _curry1(function nthArg(n) {
  6620. var arity = n < 0 ? 1 : n + 1;
  6621. return curryN(arity, function() {
  6622. return nth(n, arguments);
  6623. });
  6624. });
  6625. /**
  6626. * `o` is a curried composition function that returns a unary function.
  6627. * Like [`compose`](#compose), `o` performs right-to-left function composition.
  6628. * Unlike [`compose`](#compose), the rightmost function passed to `o` will be
  6629. * invoked with only one argument. Also, unlike [`compose`](#compose), `o` is
  6630. * limited to accepting only 2 unary functions. The name o was chosen because
  6631. * of its similarity to the mathematical composition operator .
  6632. *
  6633. * @func
  6634. * @memberOf R
  6635. * @since v0.24.0
  6636. * @category Function
  6637. * @sig (b -> c) -> (a -> b) -> a -> c
  6638. * @param {Function} f
  6639. * @param {Function} g
  6640. * @return {Function}
  6641. * @see R.compose, R.pipe
  6642. * @example
  6643. *
  6644. * const classyGreeting = name => "The name's " + name.last + ", " + name.first + " " + name.last
  6645. * const yellGreeting = R.o(R.toUpper, classyGreeting);
  6646. * yellGreeting({first: 'James', last: 'Bond'}); //=> "THE NAME'S BOND, JAMES BOND"
  6647. *
  6648. * R.o(R.multiply(10), R.add(10))(-4) //=> 60
  6649. *
  6650. * @symb R.o(f, g, x) = f(g(x))
  6651. */
  6652. var o = _curry3(function o(f, g, x) {
  6653. return f(g(x));
  6654. });
  6655. function _of(x) { return [x]; }
  6656. /**
  6657. * Returns a singleton array containing the value provided.
  6658. *
  6659. * Note this `of` is different from the ES6 `of`; See
  6660. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of
  6661. *
  6662. * @func
  6663. * @memberOf R
  6664. * @since v0.3.0
  6665. * @category Function
  6666. * @sig a -> [a]
  6667. * @param {*} x any value
  6668. * @return {Array} An array wrapping `x`.
  6669. * @example
  6670. *
  6671. * R.of(null); //=> [null]
  6672. * R.of([42]); //=> [[42]]
  6673. */
  6674. var of = _curry1(_of);
  6675. /**
  6676. * Returns a partial copy of an object omitting the keys specified.
  6677. *
  6678. * @func
  6679. * @memberOf R
  6680. * @since v0.1.0
  6681. * @category Object
  6682. * @sig [String] -> {String: *} -> {String: *}
  6683. * @param {Array} names an array of String property names to omit from the new object
  6684. * @param {Object} obj The object to copy from
  6685. * @return {Object} A new object with properties from `names` not on it.
  6686. * @see R.pick
  6687. * @example
  6688. *
  6689. * R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3}
  6690. */
  6691. var omit = _curry2(function omit(names, obj) {
  6692. var result = {};
  6693. var index = {};
  6694. var idx = 0;
  6695. var len = names.length;
  6696. while (idx < len) {
  6697. index[names[idx]] = 1;
  6698. idx += 1;
  6699. }
  6700. for (var prop in obj) {
  6701. if (!index.hasOwnProperty(prop)) {
  6702. result[prop] = obj[prop];
  6703. }
  6704. }
  6705. return result;
  6706. });
  6707. /**
  6708. * Accepts a function `fn` and returns a function that guards invocation of
  6709. * `fn` such that `fn` can only ever be called once, no matter how many times
  6710. * the returned function is invoked. The first value calculated is returned in
  6711. * subsequent invocations.
  6712. *
  6713. * @func
  6714. * @memberOf R
  6715. * @since v0.1.0
  6716. * @category Function
  6717. * @sig (a... -> b) -> (a... -> b)
  6718. * @param {Function} fn The function to wrap in a call-only-once wrapper.
  6719. * @return {Function} The wrapped function.
  6720. * @example
  6721. *
  6722. * const addOneOnce = R.once(x => x + 1);
  6723. * addOneOnce(10); //=> 11
  6724. * addOneOnce(addOneOnce(50)); //=> 11
  6725. */
  6726. var once = _curry1(function once(fn) {
  6727. var called = false;
  6728. var result;
  6729. return _arity(fn.length, function() {
  6730. if (called) {
  6731. return result;
  6732. }
  6733. called = true;
  6734. result = fn.apply(this, arguments);
  6735. return result;
  6736. });
  6737. });
  6738. function _assertPromise(name, p) {
  6739. if (p == null || !_isFunction(p.then)) {
  6740. throw new TypeError('`' + name + '` expected a Promise, received ' + _toString(p, []));
  6741. }
  6742. }
  6743. /**
  6744. * Returns the result of applying the onFailure function to the value inside
  6745. * a failed promise. This is useful for handling rejected promises
  6746. * inside function compositions.
  6747. *
  6748. * @func
  6749. * @memberOf R
  6750. * @since v0.26.0
  6751. * @category Function
  6752. * @sig (e -> b) -> (Promise e a) -> (Promise e b)
  6753. * @sig (e -> (Promise f b)) -> (Promise e a) -> (Promise f b)
  6754. * @param {Function} onFailure The function to apply. Can return a value or a promise of a value.
  6755. * @param {Promise} p
  6756. * @return {Promise} The result of calling `p.then(null, onFailure)`
  6757. * @see R.then
  6758. * @example
  6759. *
  6760. * var failedFetch = (id) => Promise.reject('bad ID');
  6761. * var useDefault = () => ({ firstName: 'Bob', lastName: 'Loblaw' })
  6762. *
  6763. * //recoverFromFailure :: String -> Promise ({firstName, lastName})
  6764. * var recoverFromFailure = R.pipe(
  6765. * failedFetch,
  6766. * R.otherwise(useDefault),
  6767. * R.then(R.pick(['firstName', 'lastName'])),
  6768. * );
  6769. * recoverFromFailure(12345).then(console.log)
  6770. */
  6771. var otherwise = _curry2(function otherwise(f, p) {
  6772. _assertPromise('otherwise', p);
  6773. return p.then(null, f);
  6774. });
  6775. // `Identity` is a functor that holds a single value, where `map` simply
  6776. // transforms the held value with the provided function.
  6777. var Identity = function(x) {
  6778. return {value: x, map: function(f) { return Identity(f(x)); }};
  6779. };
  6780. /**
  6781. * Returns the result of "setting" the portion of the given data structure
  6782. * focused by the given lens to the result of applying the given function to
  6783. * the focused value.
  6784. *
  6785. * @func
  6786. * @memberOf R
  6787. * @since v0.16.0
  6788. * @category Object
  6789. * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s
  6790. * @sig Lens s a -> (a -> a) -> s -> s
  6791. * @param {Lens} lens
  6792. * @param {*} v
  6793. * @param {*} x
  6794. * @return {*}
  6795. * @see R.prop, R.lensIndex, R.lensProp
  6796. * @example
  6797. *
  6798. * const headLens = R.lensIndex(0);
  6799. *
  6800. * R.over(headLens, R.toUpper, ['foo', 'bar', 'baz']); //=> ['FOO', 'bar', 'baz']
  6801. */
  6802. var over = _curry3(function over(lens, f, x) {
  6803. // The value returned by the getter function is first transformed with `f`,
  6804. // then set as the value of an `Identity`. This is then mapped over with the
  6805. // setter function of the lens.
  6806. return lens(function(y) { return Identity(f(y)); })(x).value;
  6807. });
  6808. /**
  6809. * Takes two arguments, `fst` and `snd`, and returns `[fst, snd]`.
  6810. *
  6811. * @func
  6812. * @memberOf R
  6813. * @since v0.18.0
  6814. * @category List
  6815. * @sig a -> b -> (a,b)
  6816. * @param {*} fst
  6817. * @param {*} snd
  6818. * @return {Array}
  6819. * @see R.objOf, R.of
  6820. * @example
  6821. *
  6822. * R.pair('foo', 'bar'); //=> ['foo', 'bar']
  6823. */
  6824. var pair = _curry2(function pair(fst, snd) { return [fst, snd]; });
  6825. function _createPartialApplicator(concat) {
  6826. return _curry2(function(fn, args) {
  6827. return _arity(Math.max(0, fn.length - args.length), function() {
  6828. return fn.apply(this, concat(args, arguments));
  6829. });
  6830. });
  6831. }
  6832. /**
  6833. * Takes a function `f` and a list of arguments, and returns a function `g`.
  6834. * When applied, `g` returns the result of applying `f` to the arguments
  6835. * provided initially followed by the arguments provided to `g`.
  6836. *
  6837. * @func
  6838. * @memberOf R
  6839. * @since v0.10.0
  6840. * @category Function
  6841. * @sig ((a, b, c, ..., n) -> x) -> [a, b, c, ...] -> ((d, e, f, ..., n) -> x)
  6842. * @param {Function} f
  6843. * @param {Array} args
  6844. * @return {Function}
  6845. * @see R.partialRight, R.curry
  6846. * @example
  6847. *
  6848. * const multiply2 = (a, b) => a * b;
  6849. * const double = R.partial(multiply2, [2]);
  6850. * double(2); //=> 4
  6851. *
  6852. * const greet = (salutation, title, firstName, lastName) =>
  6853. * salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!';
  6854. *
  6855. * const sayHello = R.partial(greet, ['Hello']);
  6856. * const sayHelloToMs = R.partial(sayHello, ['Ms.']);
  6857. * sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!'
  6858. * @symb R.partial(f, [a, b])(c, d) = f(a, b, c, d)
  6859. */
  6860. var partial = _createPartialApplicator(_concat);
  6861. /**
  6862. * Takes a function `f` and a list of arguments, and returns a function `g`.
  6863. * When applied, `g` returns the result of applying `f` to the arguments
  6864. * provided to `g` followed by the arguments provided initially.
  6865. *
  6866. * @func
  6867. * @memberOf R
  6868. * @since v0.10.0
  6869. * @category Function
  6870. * @sig ((a, b, c, ..., n) -> x) -> [d, e, f, ..., n] -> ((a, b, c, ...) -> x)
  6871. * @param {Function} f
  6872. * @param {Array} args
  6873. * @return {Function}
  6874. * @see R.partial
  6875. * @example
  6876. *
  6877. * const greet = (salutation, title, firstName, lastName) =>
  6878. * salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!';
  6879. *
  6880. * const greetMsJaneJones = R.partialRight(greet, ['Ms.', 'Jane', 'Jones']);
  6881. *
  6882. * greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!'
  6883. * @symb R.partialRight(f, [a, b])(c, d) = f(c, d, a, b)
  6884. */
  6885. var partialRight = _createPartialApplicator(flip(_concat));
  6886. /**
  6887. * Takes a predicate and a list or other `Filterable` object and returns the
  6888. * pair of filterable objects of the same type of elements which do and do not
  6889. * satisfy, the predicate, respectively. Filterable objects include plain objects or any object
  6890. * that has a filter method such as `Array`.
  6891. *
  6892. * @func
  6893. * @memberOf R
  6894. * @since v0.1.4
  6895. * @category List
  6896. * @sig Filterable f => (a -> Boolean) -> f a -> [f a, f a]
  6897. * @param {Function} pred A predicate to determine which side the element belongs to.
  6898. * @param {Array} filterable the list (or other filterable) to partition.
  6899. * @return {Array} An array, containing first the subset of elements that satisfy the
  6900. * predicate, and second the subset of elements that do not satisfy.
  6901. * @see R.filter, R.reject
  6902. * @example
  6903. *
  6904. * R.partition(R.includes('s'), ['sss', 'ttt', 'foo', 'bars']);
  6905. * // => [ [ 'sss', 'bars' ], [ 'ttt', 'foo' ] ]
  6906. *
  6907. * R.partition(R.includes('s'), { a: 'sss', b: 'ttt', foo: 'bars' });
  6908. * // => [ { a: 'sss', foo: 'bars' }, { b: 'ttt' } ]
  6909. */
  6910. var partition = juxt([filter, reject]);
  6911. /**
  6912. * Determines whether a nested path on an object has a specific value, in
  6913. * [`R.equals`](#equals) terms. Most likely used to filter a list.
  6914. *
  6915. * @func
  6916. * @memberOf R
  6917. * @since v0.7.0
  6918. * @category Relation
  6919. * @typedefn Idx = String | Int
  6920. * @sig [Idx] -> a -> {a} -> Boolean
  6921. * @param {Array} path The path of the nested property to use
  6922. * @param {*} val The value to compare the nested property with
  6923. * @param {Object} obj The object to check the nested property in
  6924. * @return {Boolean} `true` if the value equals the nested object property,
  6925. * `false` otherwise.
  6926. * @example
  6927. *
  6928. * const user1 = { address: { zipCode: 90210 } };
  6929. * const user2 = { address: { zipCode: 55555 } };
  6930. * const user3 = { name: 'Bob' };
  6931. * const users = [ user1, user2, user3 ];
  6932. * const isFamous = R.pathEq(['address', 'zipCode'], 90210);
  6933. * R.filter(isFamous, users); //=> [ user1 ]
  6934. */
  6935. var pathEq = _curry3(function pathEq(_path, val, obj) {
  6936. return equals(path(_path, obj), val);
  6937. });
  6938. /**
  6939. * If the given, non-null object has a value at the given path, returns the
  6940. * value at that path. Otherwise returns the provided default value.
  6941. *
  6942. * @func
  6943. * @memberOf R
  6944. * @since v0.18.0
  6945. * @category Object
  6946. * @typedefn Idx = String | Int
  6947. * @sig a -> [Idx] -> {a} -> a
  6948. * @param {*} d The default value.
  6949. * @param {Array} p The path to use.
  6950. * @param {Object} obj The object to retrieve the nested property from.
  6951. * @return {*} The data at `path` of the supplied object or the default value.
  6952. * @example
  6953. *
  6954. * R.pathOr('N/A', ['a', 'b'], {a: {b: 2}}); //=> 2
  6955. * R.pathOr('N/A', ['a', 'b'], {c: {b: 2}}); //=> "N/A"
  6956. */
  6957. var pathOr = _curry3(function pathOr(d, p, obj) {
  6958. return defaultTo(d, path(p, obj));
  6959. });
  6960. /**
  6961. * Returns `true` if the specified object property at given path satisfies the
  6962. * given predicate; `false` otherwise.
  6963. *
  6964. * @func
  6965. * @memberOf R
  6966. * @since v0.19.0
  6967. * @category Logic
  6968. * @typedefn Idx = String | Int
  6969. * @sig (a -> Boolean) -> [Idx] -> {a} -> Boolean
  6970. * @param {Function} pred
  6971. * @param {Array} propPath
  6972. * @param {*} obj
  6973. * @return {Boolean}
  6974. * @see R.propSatisfies, R.path
  6975. * @example
  6976. *
  6977. * R.pathSatisfies(y => y > 0, ['x', 'y'], {x: {y: 2}}); //=> true
  6978. * R.pathSatisfies(R.is(Object), [], {x: {y: 2}}); //=> true
  6979. */
  6980. var pathSatisfies = _curry3(function pathSatisfies(pred, propPath, obj) {
  6981. return pred(path(propPath, obj));
  6982. });
  6983. /**
  6984. * Returns a partial copy of an object containing only the keys specified. If
  6985. * the key does not exist, the property is ignored.
  6986. *
  6987. * @func
  6988. * @memberOf R
  6989. * @since v0.1.0
  6990. * @category Object
  6991. * @sig [k] -> {k: v} -> {k: v}
  6992. * @param {Array} names an array of String property names to copy onto a new object
  6993. * @param {Object} obj The object to copy from
  6994. * @return {Object} A new object with only properties from `names` on it.
  6995. * @see R.omit, R.props
  6996. * @example
  6997. *
  6998. * R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
  6999. * R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1}
  7000. */
  7001. var pick = _curry2(function pick(names, obj) {
  7002. var result = {};
  7003. var idx = 0;
  7004. while (idx < names.length) {
  7005. if (names[idx] in obj) {
  7006. result[names[idx]] = obj[names[idx]];
  7007. }
  7008. idx += 1;
  7009. }
  7010. return result;
  7011. });
  7012. /**
  7013. * Similar to `pick` except that this one includes a `key: undefined` pair for
  7014. * properties that don't exist.
  7015. *
  7016. * @func
  7017. * @memberOf R
  7018. * @since v0.1.0
  7019. * @category Object
  7020. * @sig [k] -> {k: v} -> {k: v}
  7021. * @param {Array} names an array of String property names to copy onto a new object
  7022. * @param {Object} obj The object to copy from
  7023. * @return {Object} A new object with only properties from `names` on it.
  7024. * @see R.pick
  7025. * @example
  7026. *
  7027. * R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
  7028. * R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined}
  7029. */
  7030. var pickAll = _curry2(function pickAll(names, obj) {
  7031. var result = {};
  7032. var idx = 0;
  7033. var len = names.length;
  7034. while (idx < len) {
  7035. var name = names[idx];
  7036. result[name] = obj[name];
  7037. idx += 1;
  7038. }
  7039. return result;
  7040. });
  7041. /**
  7042. * Returns a partial copy of an object containing only the keys that satisfy
  7043. * the supplied predicate.
  7044. *
  7045. * @func
  7046. * @memberOf R
  7047. * @since v0.8.0
  7048. * @category Object
  7049. * @sig ((v, k) -> Boolean) -> {k: v} -> {k: v}
  7050. * @param {Function} pred A predicate to determine whether or not a key
  7051. * should be included on the output object.
  7052. * @param {Object} obj The object to copy from
  7053. * @return {Object} A new object with only properties that satisfy `pred`
  7054. * on it.
  7055. * @see R.pick, R.filter
  7056. * @example
  7057. *
  7058. * const isUpperCase = (val, key) => key.toUpperCase() === key;
  7059. * R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4}
  7060. */
  7061. var pickBy = _curry2(function pickBy(test, obj) {
  7062. var result = {};
  7063. for (var prop in obj) {
  7064. if (test(obj[prop], prop, obj)) {
  7065. result[prop] = obj[prop];
  7066. }
  7067. }
  7068. return result;
  7069. });
  7070. /**
  7071. * Returns the left-to-right Kleisli composition of the provided functions,
  7072. * each of which must return a value of a type supported by [`chain`](#chain).
  7073. *
  7074. * `R.pipeK(f, g, h)` is equivalent to `R.pipe(f, R.chain(g), R.chain(h))`.
  7075. *
  7076. * @func
  7077. * @memberOf R
  7078. * @since v0.16.0
  7079. * @category Function
  7080. * @sig Chain m => ((a -> m b), (b -> m c), ..., (y -> m z)) -> (a -> m z)
  7081. * @param {...Function}
  7082. * @return {Function}
  7083. * @see R.composeK
  7084. * @deprecated since v0.26.0
  7085. * @example
  7086. *
  7087. * // parseJson :: String -> Maybe *
  7088. * // get :: String -> Object -> Maybe *
  7089. *
  7090. * // getStateCode :: Maybe String -> Maybe String
  7091. * const getStateCode = R.pipeK(
  7092. * parseJson,
  7093. * get('user'),
  7094. * get('address'),
  7095. * get('state'),
  7096. * R.compose(Maybe.of, R.toUpper)
  7097. * );
  7098. *
  7099. * getStateCode('{"user":{"address":{"state":"ny"}}}');
  7100. * //=> Just('NY')
  7101. * getStateCode('[Invalid JSON]');
  7102. * //=> Nothing()
  7103. * @symb R.pipeK(f, g, h)(a) = R.chain(h, R.chain(g, f(a)))
  7104. */
  7105. function pipeK() {
  7106. if (arguments.length === 0) {
  7107. throw new Error('pipeK requires at least one argument');
  7108. }
  7109. return composeK.apply(this, reverse(arguments));
  7110. }
  7111. /**
  7112. * Returns a new list with the given element at the front, followed by the
  7113. * contents of the list.
  7114. *
  7115. * @func
  7116. * @memberOf R
  7117. * @since v0.1.0
  7118. * @category List
  7119. * @sig a -> [a] -> [a]
  7120. * @param {*} el The item to add to the head of the output list.
  7121. * @param {Array} list The array to add to the tail of the output list.
  7122. * @return {Array} A new array.
  7123. * @see R.append
  7124. * @example
  7125. *
  7126. * R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum']
  7127. */
  7128. var prepend = _curry2(function prepend(el, list) {
  7129. return _concat([el], list);
  7130. });
  7131. /**
  7132. * Multiplies together all the elements of a list.
  7133. *
  7134. * @func
  7135. * @memberOf R
  7136. * @since v0.1.0
  7137. * @category Math
  7138. * @sig [Number] -> Number
  7139. * @param {Array} list An array of numbers
  7140. * @return {Number} The product of all the numbers in the list.
  7141. * @see R.reduce
  7142. * @example
  7143. *
  7144. * R.product([2,4,6,8,100,1]); //=> 38400
  7145. */
  7146. var product = reduce(multiply, 1);
  7147. /**
  7148. * Accepts a function `fn` and a list of transformer functions and returns a
  7149. * new curried function. When the new function is invoked, it calls the
  7150. * function `fn` with parameters consisting of the result of calling each
  7151. * supplied handler on successive arguments to the new function.
  7152. *
  7153. * If more arguments are passed to the returned function than transformer
  7154. * functions, those arguments are passed directly to `fn` as additional
  7155. * parameters. If you expect additional arguments that don't need to be
  7156. * transformed, although you can ignore them, it's best to pass an identity
  7157. * function so that the new function reports the correct arity.
  7158. *
  7159. * @func
  7160. * @memberOf R
  7161. * @since v0.1.0
  7162. * @category Function
  7163. * @sig ((x1, x2, ...) -> z) -> [(a -> x1), (b -> x2), ...] -> (a -> b -> ... -> z)
  7164. * @param {Function} fn The function to wrap.
  7165. * @param {Array} transformers A list of transformer functions
  7166. * @return {Function} The wrapped function.
  7167. * @see R.converge
  7168. * @example
  7169. *
  7170. * R.useWith(Math.pow, [R.identity, R.identity])(3, 4); //=> 81
  7171. * R.useWith(Math.pow, [R.identity, R.identity])(3)(4); //=> 81
  7172. * R.useWith(Math.pow, [R.dec, R.inc])(3, 4); //=> 32
  7173. * R.useWith(Math.pow, [R.dec, R.inc])(3)(4); //=> 32
  7174. * @symb R.useWith(f, [g, h])(a, b) = f(g(a), h(b))
  7175. */
  7176. var useWith = _curry2(function useWith(fn, transformers) {
  7177. return curryN(transformers.length, function() {
  7178. var args = [];
  7179. var idx = 0;
  7180. while (idx < transformers.length) {
  7181. args.push(transformers[idx].call(this, arguments[idx]));
  7182. idx += 1;
  7183. }
  7184. return fn.apply(this, args.concat(Array.prototype.slice.call(arguments, transformers.length)));
  7185. });
  7186. });
  7187. /**
  7188. * Reasonable analog to SQL `select` statement.
  7189. *
  7190. * @func
  7191. * @memberOf R
  7192. * @since v0.1.0
  7193. * @category Object
  7194. * @category Relation
  7195. * @sig [k] -> [{k: v}] -> [{k: v}]
  7196. * @param {Array} props The property names to project
  7197. * @param {Array} objs The objects to query
  7198. * @return {Array} An array of objects with just the `props` properties.
  7199. * @example
  7200. *
  7201. * const abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2};
  7202. * const fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7};
  7203. * const kids = [abby, fred];
  7204. * R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}]
  7205. */
  7206. var project = useWith(_map, [pickAll, identity]); // passing `identity` gives correct arity
  7207. /**
  7208. * Returns `true` if the specified object property is equal, in
  7209. * [`R.equals`](#equals) terms, to the given value; `false` otherwise.
  7210. * You can test multiple properties with [`R.whereEq`](#whereEq).
  7211. *
  7212. * @func
  7213. * @memberOf R
  7214. * @since v0.1.0
  7215. * @category Relation
  7216. * @sig String -> a -> Object -> Boolean
  7217. * @param {String} name
  7218. * @param {*} val
  7219. * @param {*} obj
  7220. * @return {Boolean}
  7221. * @see R.whereEq, R.propSatisfies, R.equals
  7222. * @example
  7223. *
  7224. * const abby = {name: 'Abby', age: 7, hair: 'blond'};
  7225. * const fred = {name: 'Fred', age: 12, hair: 'brown'};
  7226. * const rusty = {name: 'Rusty', age: 10, hair: 'brown'};
  7227. * const alois = {name: 'Alois', age: 15, disposition: 'surly'};
  7228. * const kids = [abby, fred, rusty, alois];
  7229. * const hasBrownHair = R.propEq('hair', 'brown');
  7230. * R.filter(hasBrownHair, kids); //=> [fred, rusty]
  7231. */
  7232. var propEq = _curry3(function propEq(name, val, obj) {
  7233. return equals(val, obj[name]);
  7234. });
  7235. /**
  7236. * Returns `true` if the specified object property is of the given type;
  7237. * `false` otherwise.
  7238. *
  7239. * @func
  7240. * @memberOf R
  7241. * @since v0.16.0
  7242. * @category Type
  7243. * @sig Type -> String -> Object -> Boolean
  7244. * @param {Function} type
  7245. * @param {String} name
  7246. * @param {*} obj
  7247. * @return {Boolean}
  7248. * @see R.is, R.propSatisfies
  7249. * @example
  7250. *
  7251. * R.propIs(Number, 'x', {x: 1, y: 2}); //=> true
  7252. * R.propIs(Number, 'x', {x: 'foo'}); //=> false
  7253. * R.propIs(Number, 'x', {}); //=> false
  7254. */
  7255. var propIs = _curry3(function propIs(type, name, obj) {
  7256. return is(type, obj[name]);
  7257. });
  7258. /**
  7259. * If the given, non-null object has an own property with the specified name,
  7260. * returns the value of that property. Otherwise returns the provided default
  7261. * value.
  7262. *
  7263. * @func
  7264. * @memberOf R
  7265. * @since v0.6.0
  7266. * @category Object
  7267. * @sig a -> String -> Object -> a
  7268. * @param {*} val The default value.
  7269. * @param {String} p The name of the property to return.
  7270. * @param {Object} obj The object to query.
  7271. * @return {*} The value of given property of the supplied object or the default value.
  7272. * @example
  7273. *
  7274. * const alice = {
  7275. * name: 'ALICE',
  7276. * age: 101
  7277. * };
  7278. * const favorite = R.prop('favoriteLibrary');
  7279. * const favoriteWithDefault = R.propOr('Ramda', 'favoriteLibrary');
  7280. *
  7281. * favorite(alice); //=> undefined
  7282. * favoriteWithDefault(alice); //=> 'Ramda'
  7283. */
  7284. var propOr = _curry3(function propOr(val, p, obj) {
  7285. return pathOr(val, [p], obj);
  7286. });
  7287. /**
  7288. * Returns `true` if the specified object property satisfies the given
  7289. * predicate; `false` otherwise. You can test multiple properties with
  7290. * [`R.where`](#where).
  7291. *
  7292. * @func
  7293. * @memberOf R
  7294. * @since v0.16.0
  7295. * @category Logic
  7296. * @sig (a -> Boolean) -> String -> {String: a} -> Boolean
  7297. * @param {Function} pred
  7298. * @param {String} name
  7299. * @param {*} obj
  7300. * @return {Boolean}
  7301. * @see R.where, R.propEq, R.propIs
  7302. * @example
  7303. *
  7304. * R.propSatisfies(x => x > 0, 'x', {x: 1, y: 2}); //=> true
  7305. */
  7306. var propSatisfies = _curry3(function propSatisfies(pred, name, obj) {
  7307. return pred(obj[name]);
  7308. });
  7309. /**
  7310. * Acts as multiple `prop`: array of keys in, array of values out. Preserves
  7311. * order.
  7312. *
  7313. * @func
  7314. * @memberOf R
  7315. * @since v0.1.0
  7316. * @category Object
  7317. * @sig [k] -> {k: v} -> [v]
  7318. * @param {Array} ps The property names to fetch
  7319. * @param {Object} obj The object to query
  7320. * @return {Array} The corresponding values or partially applied function.
  7321. * @example
  7322. *
  7323. * R.props(['x', 'y'], {x: 1, y: 2}); //=> [1, 2]
  7324. * R.props(['c', 'a', 'b'], {b: 2, a: 1}); //=> [undefined, 1, 2]
  7325. *
  7326. * const fullName = R.compose(R.join(' '), R.props(['first', 'last']));
  7327. * fullName({last: 'Bullet-Tooth', age: 33, first: 'Tony'}); //=> 'Tony Bullet-Tooth'
  7328. */
  7329. var props = _curry2(function props(ps, obj) {
  7330. return ps.map(function(p) {
  7331. return path([p], obj);
  7332. });
  7333. });
  7334. /**
  7335. * Returns a list of numbers from `from` (inclusive) to `to` (exclusive).
  7336. *
  7337. * @func
  7338. * @memberOf R
  7339. * @since v0.1.0
  7340. * @category List
  7341. * @sig Number -> Number -> [Number]
  7342. * @param {Number} from The first number in the list.
  7343. * @param {Number} to One more than the last number in the list.
  7344. * @return {Array} The list of numbers in the set `[a, b)`.
  7345. * @example
  7346. *
  7347. * R.range(1, 5); //=> [1, 2, 3, 4]
  7348. * R.range(50, 53); //=> [50, 51, 52]
  7349. */
  7350. var range = _curry2(function range(from, to) {
  7351. if (!(_isNumber(from) && _isNumber(to))) {
  7352. throw new TypeError('Both arguments to range must be numbers');
  7353. }
  7354. var result = [];
  7355. var n = from;
  7356. while (n < to) {
  7357. result.push(n);
  7358. n += 1;
  7359. }
  7360. return result;
  7361. });
  7362. /**
  7363. * Returns a single item by iterating through the list, successively calling
  7364. * the iterator function and passing it an accumulator value and the current
  7365. * value from the array, and then passing the result to the next call.
  7366. *
  7367. * Similar to [`reduce`](#reduce), except moves through the input list from the
  7368. * right to the left.
  7369. *
  7370. * The iterator function receives two values: *(value, acc)*, while the arguments'
  7371. * order of `reduce`'s iterator function is *(acc, value)*.
  7372. *
  7373. * Note: `R.reduceRight` does not skip deleted or unassigned indices (sparse
  7374. * arrays), unlike the native `Array.prototype.reduceRight` method. For more details
  7375. * on this behavior, see:
  7376. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight#Description
  7377. *
  7378. * @func
  7379. * @memberOf R
  7380. * @since v0.1.0
  7381. * @category List
  7382. * @sig ((a, b) -> b) -> b -> [a] -> b
  7383. * @param {Function} fn The iterator function. Receives two values, the current element from the array
  7384. * and the accumulator.
  7385. * @param {*} acc The accumulator value.
  7386. * @param {Array} list The list to iterate over.
  7387. * @return {*} The final, accumulated value.
  7388. * @see R.reduce, R.addIndex
  7389. * @example
  7390. *
  7391. * R.reduceRight(R.subtract, 0, [1, 2, 3, 4]) // => (1 - (2 - (3 - (4 - 0)))) = -2
  7392. * // - -2
  7393. * // / \ / \
  7394. * // 1 - 1 3
  7395. * // / \ / \
  7396. * // 2 - ==> 2 -1
  7397. * // / \ / \
  7398. * // 3 - 3 4
  7399. * // / \ / \
  7400. * // 4 0 4 0
  7401. *
  7402. * @symb R.reduceRight(f, a, [b, c, d]) = f(b, f(c, f(d, a)))
  7403. */
  7404. var reduceRight = _curry3(function reduceRight(fn, acc, list) {
  7405. var idx = list.length - 1;
  7406. while (idx >= 0) {
  7407. acc = fn(list[idx], acc);
  7408. idx -= 1;
  7409. }
  7410. return acc;
  7411. });
  7412. /**
  7413. * Like [`reduce`](#reduce), `reduceWhile` returns a single item by iterating
  7414. * through the list, successively calling the iterator function. `reduceWhile`
  7415. * also takes a predicate that is evaluated before each step. If the predicate
  7416. * returns `false`, it "short-circuits" the iteration and returns the current
  7417. * value of the accumulator.
  7418. *
  7419. * @func
  7420. * @memberOf R
  7421. * @since v0.22.0
  7422. * @category List
  7423. * @sig ((a, b) -> Boolean) -> ((a, b) -> a) -> a -> [b] -> a
  7424. * @param {Function} pred The predicate. It is passed the accumulator and the
  7425. * current element.
  7426. * @param {Function} fn The iterator function. Receives two values, the
  7427. * accumulator and the current element.
  7428. * @param {*} a The accumulator value.
  7429. * @param {Array} list The list to iterate over.
  7430. * @return {*} The final, accumulated value.
  7431. * @see R.reduce, R.reduced
  7432. * @example
  7433. *
  7434. * const isOdd = (acc, x) => x % 2 === 1;
  7435. * const xs = [1, 3, 5, 60, 777, 800];
  7436. * R.reduceWhile(isOdd, R.add, 0, xs); //=> 9
  7437. *
  7438. * const ys = [2, 4, 6]
  7439. * R.reduceWhile(isOdd, R.add, 111, ys); //=> 111
  7440. */
  7441. var reduceWhile = _curryN(4, [], function _reduceWhile(pred, fn, a, list) {
  7442. return _reduce(function(acc, x) {
  7443. return pred(acc, x) ? fn(acc, x) : _reduced(acc);
  7444. }, a, list);
  7445. });
  7446. /**
  7447. * Returns a value wrapped to indicate that it is the final value of the reduce
  7448. * and transduce functions. The returned value should be considered a black
  7449. * box: the internal structure is not guaranteed to be stable.
  7450. *
  7451. * Note: this optimization is only available to the below functions:
  7452. * - [`reduce`](#reduce)
  7453. * - [`reduceWhile`](#reduceWhile)
  7454. * - [`transduce`](#transduce)
  7455. *
  7456. * @func
  7457. * @memberOf R
  7458. * @since v0.15.0
  7459. * @category List
  7460. * @sig a -> *
  7461. * @param {*} x The final value of the reduce.
  7462. * @return {*} The wrapped value.
  7463. * @see R.reduce, R.reduceWhile, R.transduce
  7464. * @example
  7465. *
  7466. * R.reduce(
  7467. * (acc, item) => item > 3 ? R.reduced(acc) : acc.concat(item),
  7468. * [],
  7469. * [1, 2, 3, 4, 5]) // [1, 2, 3]
  7470. */
  7471. var reduced = _curry1(_reduced);
  7472. /**
  7473. * Calls an input function `n` times, returning an array containing the results
  7474. * of those function calls.
  7475. *
  7476. * `fn` is passed one argument: The current value of `n`, which begins at `0`
  7477. * and is gradually incremented to `n - 1`.
  7478. *
  7479. * @func
  7480. * @memberOf R
  7481. * @since v0.2.3
  7482. * @category List
  7483. * @sig (Number -> a) -> Number -> [a]
  7484. * @param {Function} fn The function to invoke. Passed one argument, the current value of `n`.
  7485. * @param {Number} n A value between `0` and `n - 1`. Increments after each function call.
  7486. * @return {Array} An array containing the return values of all calls to `fn`.
  7487. * @see R.repeat
  7488. * @example
  7489. *
  7490. * R.times(R.identity, 5); //=> [0, 1, 2, 3, 4]
  7491. * @symb R.times(f, 0) = []
  7492. * @symb R.times(f, 1) = [f(0)]
  7493. * @symb R.times(f, 2) = [f(0), f(1)]
  7494. */
  7495. var times = _curry2(function times(fn, n) {
  7496. var len = Number(n);
  7497. var idx = 0;
  7498. var list;
  7499. if (len < 0 || isNaN(len)) {
  7500. throw new RangeError('n must be a non-negative number');
  7501. }
  7502. list = new Array(len);
  7503. while (idx < len) {
  7504. list[idx] = fn(idx);
  7505. idx += 1;
  7506. }
  7507. return list;
  7508. });
  7509. /**
  7510. * Returns a fixed list of size `n` containing a specified identical value.
  7511. *
  7512. * @func
  7513. * @memberOf R
  7514. * @since v0.1.1
  7515. * @category List
  7516. * @sig a -> n -> [a]
  7517. * @param {*} value The value to repeat.
  7518. * @param {Number} n The desired size of the output list.
  7519. * @return {Array} A new array containing `n` `value`s.
  7520. * @see R.times
  7521. * @example
  7522. *
  7523. * R.repeat('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi']
  7524. *
  7525. * const obj = {};
  7526. * const repeatedObjs = R.repeat(obj, 5); //=> [{}, {}, {}, {}, {}]
  7527. * repeatedObjs[0] === repeatedObjs[1]; //=> true
  7528. * @symb R.repeat(a, 0) = []
  7529. * @symb R.repeat(a, 1) = [a]
  7530. * @symb R.repeat(a, 2) = [a, a]
  7531. */
  7532. var repeat = _curry2(function repeat(value, n) {
  7533. return times(always(value), n);
  7534. });
  7535. /**
  7536. * Replace a substring or regex match in a string with a replacement.
  7537. *
  7538. * The first two parameters correspond to the parameters of the
  7539. * `String.prototype.replace()` function, so the second parameter can also be a
  7540. * function.
  7541. *
  7542. * @func
  7543. * @memberOf R
  7544. * @since v0.7.0
  7545. * @category String
  7546. * @sig RegExp|String -> String -> String -> String
  7547. * @param {RegExp|String} pattern A regular expression or a substring to match.
  7548. * @param {String} replacement The string to replace the matches with.
  7549. * @param {String} str The String to do the search and replacement in.
  7550. * @return {String} The result.
  7551. * @example
  7552. *
  7553. * R.replace('foo', 'bar', 'foo foo foo'); //=> 'bar foo foo'
  7554. * R.replace(/foo/, 'bar', 'foo foo foo'); //=> 'bar foo foo'
  7555. *
  7556. * // Use the "g" (global) flag to replace all occurrences:
  7557. * R.replace(/foo/g, 'bar', 'foo foo foo'); //=> 'bar bar bar'
  7558. */
  7559. var replace = _curry3(function replace(regex, replacement, str) {
  7560. return str.replace(regex, replacement);
  7561. });
  7562. /**
  7563. * Scan is similar to [`reduce`](#reduce), but returns a list of successively
  7564. * reduced values from the left
  7565. *
  7566. * @func
  7567. * @memberOf R
  7568. * @since v0.10.0
  7569. * @category List
  7570. * @sig ((a, b) -> a) -> a -> [b] -> [a]
  7571. * @param {Function} fn The iterator function. Receives two values, the accumulator and the
  7572. * current element from the array
  7573. * @param {*} acc The accumulator value.
  7574. * @param {Array} list The list to iterate over.
  7575. * @return {Array} A list of all intermediately reduced values.
  7576. * @see R.reduce, R.mapAccum
  7577. * @example
  7578. *
  7579. * const numbers = [1, 2, 3, 4];
  7580. * const factorials = R.scan(R.multiply, 1, numbers); //=> [1, 1, 2, 6, 24]
  7581. * @symb R.scan(f, a, [b, c]) = [a, f(a, b), f(f(a, b), c)]
  7582. */
  7583. var scan = _curry3(function scan(fn, acc, list) {
  7584. var idx = 0;
  7585. var len = list.length;
  7586. var result = [acc];
  7587. while (idx < len) {
  7588. acc = fn(acc, list[idx]);
  7589. result[idx + 1] = acc;
  7590. idx += 1;
  7591. }
  7592. return result;
  7593. });
  7594. /**
  7595. * Transforms a [Traversable](https://github.com/fantasyland/fantasy-land#traversable)
  7596. * of [Applicative](https://github.com/fantasyland/fantasy-land#applicative) into an
  7597. * Applicative of Traversable.
  7598. *
  7599. * Dispatches to the `sequence` method of the second argument, if present.
  7600. *
  7601. * @func
  7602. * @memberOf R
  7603. * @since v0.19.0
  7604. * @category List
  7605. * @sig (Applicative f, Traversable t) => (a -> f a) -> t (f a) -> f (t a)
  7606. * @param {Function} of
  7607. * @param {*} traversable
  7608. * @return {*}
  7609. * @see R.traverse
  7610. * @example
  7611. *
  7612. * R.sequence(Maybe.of, [Just(1), Just(2), Just(3)]); //=> Just([1, 2, 3])
  7613. * R.sequence(Maybe.of, [Just(1), Just(2), Nothing()]); //=> Nothing()
  7614. *
  7615. * R.sequence(R.of, Just([1, 2, 3])); //=> [Just(1), Just(2), Just(3)]
  7616. * R.sequence(R.of, Nothing()); //=> [Nothing()]
  7617. */
  7618. var sequence = _curry2(function sequence(of, traversable) {
  7619. return typeof traversable.sequence === 'function' ?
  7620. traversable.sequence(of) :
  7621. reduceRight(
  7622. function(x, acc) { return ap(map(prepend, x), acc); },
  7623. of([]),
  7624. traversable
  7625. );
  7626. });
  7627. /**
  7628. * Returns the result of "setting" the portion of the given data structure
  7629. * focused by the given lens to the given value.
  7630. *
  7631. * @func
  7632. * @memberOf R
  7633. * @since v0.16.0
  7634. * @category Object
  7635. * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s
  7636. * @sig Lens s a -> a -> s -> s
  7637. * @param {Lens} lens
  7638. * @param {*} v
  7639. * @param {*} x
  7640. * @return {*}
  7641. * @see R.prop, R.lensIndex, R.lensProp
  7642. * @example
  7643. *
  7644. * const xLens = R.lensProp('x');
  7645. *
  7646. * R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2}
  7647. * R.set(xLens, 8, {x: 1, y: 2}); //=> {x: 8, y: 2}
  7648. */
  7649. var set = _curry3(function set(lens, v, x) {
  7650. return over(lens, always(v), x);
  7651. });
  7652. /**
  7653. * Returns a copy of the list, sorted according to the comparator function,
  7654. * which should accept two values at a time and return a negative number if the
  7655. * first value is smaller, a positive number if it's larger, and zero if they
  7656. * are equal. Please note that this is a **copy** of the list. It does not
  7657. * modify the original.
  7658. *
  7659. * @func
  7660. * @memberOf R
  7661. * @since v0.1.0
  7662. * @category List
  7663. * @sig ((a, a) -> Number) -> [a] -> [a]
  7664. * @param {Function} comparator A sorting function :: a -> b -> Int
  7665. * @param {Array} list The list to sort
  7666. * @return {Array} a new array with its elements sorted by the comparator function.
  7667. * @example
  7668. *
  7669. * const diff = function(a, b) { return a - b; };
  7670. * R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7]
  7671. */
  7672. var sort = _curry2(function sort(comparator, list) {
  7673. return Array.prototype.slice.call(list, 0).sort(comparator);
  7674. });
  7675. /**
  7676. * Sorts the list according to the supplied function.
  7677. *
  7678. * @func
  7679. * @memberOf R
  7680. * @since v0.1.0
  7681. * @category Relation
  7682. * @sig Ord b => (a -> b) -> [a] -> [a]
  7683. * @param {Function} fn
  7684. * @param {Array} list The list to sort.
  7685. * @return {Array} A new list sorted by the keys generated by `fn`.
  7686. * @example
  7687. *
  7688. * const sortByFirstItem = R.sortBy(R.prop(0));
  7689. * const pairs = [[-1, 1], [-2, 2], [-3, 3]];
  7690. * sortByFirstItem(pairs); //=> [[-3, 3], [-2, 2], [-1, 1]]
  7691. *
  7692. * const sortByNameCaseInsensitive = R.sortBy(R.compose(R.toLower, R.prop('name')));
  7693. * const alice = {
  7694. * name: 'ALICE',
  7695. * age: 101
  7696. * };
  7697. * const bob = {
  7698. * name: 'Bob',
  7699. * age: -10
  7700. * };
  7701. * const clara = {
  7702. * name: 'clara',
  7703. * age: 314.159
  7704. * };
  7705. * const people = [clara, bob, alice];
  7706. * sortByNameCaseInsensitive(people); //=> [alice, bob, clara]
  7707. */
  7708. var sortBy = _curry2(function sortBy(fn, list) {
  7709. return Array.prototype.slice.call(list, 0).sort(function(a, b) {
  7710. var aa = fn(a);
  7711. var bb = fn(b);
  7712. return aa < bb ? -1 : aa > bb ? 1 : 0;
  7713. });
  7714. });
  7715. /**
  7716. * Sorts a list according to a list of comparators.
  7717. *
  7718. * @func
  7719. * @memberOf R
  7720. * @since v0.23.0
  7721. * @category Relation
  7722. * @sig [(a, a) -> Number] -> [a] -> [a]
  7723. * @param {Array} functions A list of comparator functions.
  7724. * @param {Array} list The list to sort.
  7725. * @return {Array} A new list sorted according to the comarator functions.
  7726. * @example
  7727. *
  7728. * const alice = {
  7729. * name: 'alice',
  7730. * age: 40
  7731. * };
  7732. * const bob = {
  7733. * name: 'bob',
  7734. * age: 30
  7735. * };
  7736. * const clara = {
  7737. * name: 'clara',
  7738. * age: 40
  7739. * };
  7740. * const people = [clara, bob, alice];
  7741. * const ageNameSort = R.sortWith([
  7742. * R.descend(R.prop('age')),
  7743. * R.ascend(R.prop('name'))
  7744. * ]);
  7745. * ageNameSort(people); //=> [alice, clara, bob]
  7746. */
  7747. var sortWith = _curry2(function sortWith(fns, list) {
  7748. return Array.prototype.slice.call(list, 0).sort(function(a, b) {
  7749. var result = 0;
  7750. var i = 0;
  7751. while (result === 0 && i < fns.length) {
  7752. result = fns[i](a, b);
  7753. i += 1;
  7754. }
  7755. return result;
  7756. });
  7757. });
  7758. /**
  7759. * Splits a string into an array of strings based on the given
  7760. * separator.
  7761. *
  7762. * @func
  7763. * @memberOf R
  7764. * @since v0.1.0
  7765. * @category String
  7766. * @sig (String | RegExp) -> String -> [String]
  7767. * @param {String|RegExp} sep The pattern.
  7768. * @param {String} str The string to separate into an array.
  7769. * @return {Array} The array of strings from `str` separated by `sep`.
  7770. * @see R.join
  7771. * @example
  7772. *
  7773. * const pathComponents = R.split('/');
  7774. * R.tail(pathComponents('/usr/local/bin/node')); //=> ['usr', 'local', 'bin', 'node']
  7775. *
  7776. * R.split('.', 'a.b.c.xyz.d'); //=> ['a', 'b', 'c', 'xyz', 'd']
  7777. */
  7778. var split = invoker(1, 'split');
  7779. /**
  7780. * Splits a given list or string at a given index.
  7781. *
  7782. * @func
  7783. * @memberOf R
  7784. * @since v0.19.0
  7785. * @category List
  7786. * @sig Number -> [a] -> [[a], [a]]
  7787. * @sig Number -> String -> [String, String]
  7788. * @param {Number} index The index where the array/string is split.
  7789. * @param {Array|String} array The array/string to be split.
  7790. * @return {Array}
  7791. * @example
  7792. *
  7793. * R.splitAt(1, [1, 2, 3]); //=> [[1], [2, 3]]
  7794. * R.splitAt(5, 'hello world'); //=> ['hello', ' world']
  7795. * R.splitAt(-1, 'foobar'); //=> ['fooba', 'r']
  7796. */
  7797. var splitAt = _curry2(function splitAt(index, array) {
  7798. return [slice(0, index, array), slice(index, length(array), array)];
  7799. });
  7800. /**
  7801. * Splits a collection into slices of the specified length.
  7802. *
  7803. * @func
  7804. * @memberOf R
  7805. * @since v0.16.0
  7806. * @category List
  7807. * @sig Number -> [a] -> [[a]]
  7808. * @sig Number -> String -> [String]
  7809. * @param {Number} n
  7810. * @param {Array} list
  7811. * @return {Array}
  7812. * @example
  7813. *
  7814. * R.splitEvery(3, [1, 2, 3, 4, 5, 6, 7]); //=> [[1, 2, 3], [4, 5, 6], [7]]
  7815. * R.splitEvery(3, 'foobarbaz'); //=> ['foo', 'bar', 'baz']
  7816. */
  7817. var splitEvery = _curry2(function splitEvery(n, list) {
  7818. if (n <= 0) {
  7819. throw new Error('First argument to splitEvery must be a positive integer');
  7820. }
  7821. var result = [];
  7822. var idx = 0;
  7823. while (idx < list.length) {
  7824. result.push(slice(idx, idx += n, list));
  7825. }
  7826. return result;
  7827. });
  7828. /**
  7829. * Takes a list and a predicate and returns a pair of lists with the following properties:
  7830. *
  7831. * - the result of concatenating the two output lists is equivalent to the input list;
  7832. * - none of the elements of the first output list satisfies the predicate; and
  7833. * - if the second output list is non-empty, its first element satisfies the predicate.
  7834. *
  7835. * @func
  7836. * @memberOf R
  7837. * @since v0.19.0
  7838. * @category List
  7839. * @sig (a -> Boolean) -> [a] -> [[a], [a]]
  7840. * @param {Function} pred The predicate that determines where the array is split.
  7841. * @param {Array} list The array to be split.
  7842. * @return {Array}
  7843. * @example
  7844. *
  7845. * R.splitWhen(R.equals(2), [1, 2, 3, 1, 2, 3]); //=> [[1], [2, 3, 1, 2, 3]]
  7846. */
  7847. var splitWhen = _curry2(function splitWhen(pred, list) {
  7848. var idx = 0;
  7849. var len = list.length;
  7850. var prefix = [];
  7851. while (idx < len && !pred(list[idx])) {
  7852. prefix.push(list[idx]);
  7853. idx += 1;
  7854. }
  7855. return [prefix, Array.prototype.slice.call(list, idx)];
  7856. });
  7857. /**
  7858. * Checks if a list starts with the provided sublist.
  7859. *
  7860. * Similarly, checks if a string starts with the provided substring.
  7861. *
  7862. * @func
  7863. * @memberOf R
  7864. * @since v0.24.0
  7865. * @category List
  7866. * @sig [a] -> [a] -> Boolean
  7867. * @sig String -> String -> Boolean
  7868. * @param {*} prefix
  7869. * @param {*} list
  7870. * @return {Boolean}
  7871. * @see R.endsWith
  7872. * @example
  7873. *
  7874. * R.startsWith('a', 'abc') //=> true
  7875. * R.startsWith('b', 'abc') //=> false
  7876. * R.startsWith(['a'], ['a', 'b', 'c']) //=> true
  7877. * R.startsWith(['b'], ['a', 'b', 'c']) //=> false
  7878. */
  7879. var startsWith = _curry2(function(prefix, list) {
  7880. return equals(take(prefix.length, list), prefix);
  7881. });
  7882. /**
  7883. * Subtracts its second argument from its first argument.
  7884. *
  7885. * @func
  7886. * @memberOf R
  7887. * @since v0.1.0
  7888. * @category Math
  7889. * @sig Number -> Number -> Number
  7890. * @param {Number} a The first value.
  7891. * @param {Number} b The second value.
  7892. * @return {Number} The result of `a - b`.
  7893. * @see R.add
  7894. * @example
  7895. *
  7896. * R.subtract(10, 8); //=> 2
  7897. *
  7898. * const minus5 = R.subtract(R.__, 5);
  7899. * minus5(17); //=> 12
  7900. *
  7901. * const complementaryAngle = R.subtract(90);
  7902. * complementaryAngle(30); //=> 60
  7903. * complementaryAngle(72); //=> 18
  7904. */
  7905. var subtract = _curry2(function subtract(a, b) {
  7906. return Number(a) - Number(b);
  7907. });
  7908. /**
  7909. * Finds the set (i.e. no duplicates) of all elements contained in the first or
  7910. * second list, but not both.
  7911. *
  7912. * @func
  7913. * @memberOf R
  7914. * @since v0.19.0
  7915. * @category Relation
  7916. * @sig [*] -> [*] -> [*]
  7917. * @param {Array} list1 The first list.
  7918. * @param {Array} list2 The second list.
  7919. * @return {Array} The elements in `list1` or `list2`, but not both.
  7920. * @see R.symmetricDifferenceWith, R.difference, R.differenceWith
  7921. * @example
  7922. *
  7923. * R.symmetricDifference([1,2,3,4], [7,6,5,4,3]); //=> [1,2,7,6,5]
  7924. * R.symmetricDifference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5,1,2]
  7925. */
  7926. var symmetricDifference = _curry2(function symmetricDifference(list1, list2) {
  7927. return concat(difference(list1, list2), difference(list2, list1));
  7928. });
  7929. /**
  7930. * Finds the set (i.e. no duplicates) of all elements contained in the first or
  7931. * second list, but not both. Duplication is determined according to the value
  7932. * returned by applying the supplied predicate to two list elements.
  7933. *
  7934. * @func
  7935. * @memberOf R
  7936. * @since v0.19.0
  7937. * @category Relation
  7938. * @sig ((a, a) -> Boolean) -> [a] -> [a] -> [a]
  7939. * @param {Function} pred A predicate used to test whether two items are equal.
  7940. * @param {Array} list1 The first list.
  7941. * @param {Array} list2 The second list.
  7942. * @return {Array} The elements in `list1` or `list2`, but not both.
  7943. * @see R.symmetricDifference, R.difference, R.differenceWith
  7944. * @example
  7945. *
  7946. * const eqA = R.eqBy(R.prop('a'));
  7947. * const l1 = [{a: 1}, {a: 2}, {a: 3}, {a: 4}];
  7948. * const l2 = [{a: 3}, {a: 4}, {a: 5}, {a: 6}];
  7949. * R.symmetricDifferenceWith(eqA, l1, l2); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}]
  7950. */
  7951. var symmetricDifferenceWith = _curry3(function symmetricDifferenceWith(pred, list1, list2) {
  7952. return concat(differenceWith(pred, list1, list2), differenceWith(pred, list2, list1));
  7953. });
  7954. /**
  7955. * Returns a new list containing the last `n` elements of a given list, passing
  7956. * each value to the supplied predicate function, and terminating when the
  7957. * predicate function returns `false`. Excludes the element that caused the
  7958. * predicate function to fail. The predicate function is passed one argument:
  7959. * *(value)*.
  7960. *
  7961. * @func
  7962. * @memberOf R
  7963. * @since v0.16.0
  7964. * @category List
  7965. * @sig (a -> Boolean) -> [a] -> [a]
  7966. * @sig (a -> Boolean) -> String -> String
  7967. * @param {Function} fn The function called per iteration.
  7968. * @param {Array} xs The collection to iterate over.
  7969. * @return {Array} A new array.
  7970. * @see R.dropLastWhile, R.addIndex
  7971. * @example
  7972. *
  7973. * const isNotOne = x => x !== 1;
  7974. *
  7975. * R.takeLastWhile(isNotOne, [1, 2, 3, 4]); //=> [2, 3, 4]
  7976. *
  7977. * R.takeLastWhile(x => x !== 'R' , 'Ramda'); //=> 'amda'
  7978. */
  7979. var takeLastWhile = _curry2(function takeLastWhile(fn, xs) {
  7980. var idx = xs.length - 1;
  7981. while (idx >= 0 && fn(xs[idx])) {
  7982. idx -= 1;
  7983. }
  7984. return slice(idx + 1, Infinity, xs);
  7985. });
  7986. function XTakeWhile(f, xf) {
  7987. this.xf = xf;
  7988. this.f = f;
  7989. }
  7990. XTakeWhile.prototype['@@transducer/init'] = _xfBase.init;
  7991. XTakeWhile.prototype['@@transducer/result'] = _xfBase.result;
  7992. XTakeWhile.prototype['@@transducer/step'] = function(result, input) {
  7993. return this.f(input) ? this.xf['@@transducer/step'](result, input) : _reduced(result);
  7994. };
  7995. var _xtakeWhile = _curry2(function _xtakeWhile(f, xf) { return new XTakeWhile(f, xf); });
  7996. /**
  7997. * Returns a new list containing the first `n` elements of a given list,
  7998. * passing each value to the supplied predicate function, and terminating when
  7999. * the predicate function returns `false`. Excludes the element that caused the
  8000. * predicate function to fail. The predicate function is passed one argument:
  8001. * *(value)*.
  8002. *
  8003. * Dispatches to the `takeWhile` method of the second argument, if present.
  8004. *
  8005. * Acts as a transducer if a transformer is given in list position.
  8006. *
  8007. * @func
  8008. * @memberOf R
  8009. * @since v0.1.0
  8010. * @category List
  8011. * @sig (a -> Boolean) -> [a] -> [a]
  8012. * @sig (a -> Boolean) -> String -> String
  8013. * @param {Function} fn The function called per iteration.
  8014. * @param {Array} xs The collection to iterate over.
  8015. * @return {Array} A new array.
  8016. * @see R.dropWhile, R.transduce, R.addIndex
  8017. * @example
  8018. *
  8019. * const isNotFour = x => x !== 4;
  8020. *
  8021. * R.takeWhile(isNotFour, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3]
  8022. *
  8023. * R.takeWhile(x => x !== 'd' , 'Ramda'); //=> 'Ram'
  8024. */
  8025. var takeWhile = _curry2(_dispatchable(['takeWhile'], _xtakeWhile, function takeWhile(fn, xs) {
  8026. var idx = 0;
  8027. var len = xs.length;
  8028. while (idx < len && fn(xs[idx])) {
  8029. idx += 1;
  8030. }
  8031. return slice(0, idx, xs);
  8032. }));
  8033. function XTap(f, xf) {
  8034. this.xf = xf;
  8035. this.f = f;
  8036. }
  8037. XTap.prototype['@@transducer/init'] = _xfBase.init;
  8038. XTap.prototype['@@transducer/result'] = _xfBase.result;
  8039. XTap.prototype['@@transducer/step'] = function(result, input) {
  8040. this.f(input);
  8041. return this.xf['@@transducer/step'](result, input);
  8042. };
  8043. var _xtap = _curry2(function _xtap(f, xf) { return new XTap(f, xf); });
  8044. /**
  8045. * Runs the given function with the supplied object, then returns the object.
  8046. *
  8047. * Acts as a transducer if a transformer is given as second parameter.
  8048. *
  8049. * @func
  8050. * @memberOf R
  8051. * @since v0.1.0
  8052. * @category Function
  8053. * @sig (a -> *) -> a -> a
  8054. * @param {Function} fn The function to call with `x`. The return value of `fn` will be thrown away.
  8055. * @param {*} x
  8056. * @return {*} `x`.
  8057. * @example
  8058. *
  8059. * const sayX = x => console.log('x is ' + x);
  8060. * R.tap(sayX, 100); //=> 100
  8061. * // logs 'x is 100'
  8062. * @symb R.tap(f, a) = a
  8063. */
  8064. var tap = _curry2(_dispatchable([], _xtap, function tap(fn, x) {
  8065. fn(x);
  8066. return x;
  8067. }));
  8068. function _isRegExp(x) {
  8069. return Object.prototype.toString.call(x) === '[object RegExp]';
  8070. }
  8071. /**
  8072. * Determines whether a given string matches a given regular expression.
  8073. *
  8074. * @func
  8075. * @memberOf R
  8076. * @since v0.12.0
  8077. * @category String
  8078. * @sig RegExp -> String -> Boolean
  8079. * @param {RegExp} pattern
  8080. * @param {String} str
  8081. * @return {Boolean}
  8082. * @see R.match
  8083. * @example
  8084. *
  8085. * R.test(/^x/, 'xyz'); //=> true
  8086. * R.test(/^y/, 'xyz'); //=> false
  8087. */
  8088. var test = _curry2(function test(pattern, str) {
  8089. if (!_isRegExp(pattern)) {
  8090. throw new TypeError('‘test’ requires a value of type RegExp as its first argument; received ' + toString$1(pattern));
  8091. }
  8092. return _cloneRegExp(pattern).test(str);
  8093. });
  8094. /**
  8095. * Returns the result of applying the onSuccess function to the value inside
  8096. * a successfully resolved promise. This is useful for working with promises
  8097. * inside function compositions.
  8098. *
  8099. * @func
  8100. * @memberOf R
  8101. * @since v0.27.1
  8102. * @category Function
  8103. * @sig (a -> b) -> (Promise e a) -> (Promise e b)
  8104. * @sig (a -> (Promise e b)) -> (Promise e a) -> (Promise e b)
  8105. * @param {Function} onSuccess The function to apply. Can return a value or a promise of a value.
  8106. * @param {Promise} p
  8107. * @return {Promise} The result of calling `p.then(onSuccess)`
  8108. * @see R.otherwise
  8109. * @example
  8110. *
  8111. * var makeQuery = (email) => ({ query: { email }});
  8112. *
  8113. * //getMemberName :: String -> Promise ({firstName, lastName})
  8114. * var getMemberName = R.pipe(
  8115. * makeQuery,
  8116. * fetchMember,
  8117. * R.andThen(R.pick(['firstName', 'lastName']))
  8118. * );
  8119. */
  8120. var andThen = _curry2(function andThen(f, p) {
  8121. _assertPromise('andThen', p);
  8122. return p.then(f);
  8123. });
  8124. /**
  8125. * The lower case version of a string.
  8126. *
  8127. * @func
  8128. * @memberOf R
  8129. * @since v0.9.0
  8130. * @category String
  8131. * @sig String -> String
  8132. * @param {String} str The string to lower case.
  8133. * @return {String} The lower case version of `str`.
  8134. * @see R.toUpper
  8135. * @example
  8136. *
  8137. * R.toLower('XYZ'); //=> 'xyz'
  8138. */
  8139. var toLower = invoker(0, 'toLowerCase');
  8140. /**
  8141. * Converts an object into an array of key, value arrays. Only the object's
  8142. * own properties are used.
  8143. * Note that the order of the output array is not guaranteed to be consistent
  8144. * across different JS platforms.
  8145. *
  8146. * @func
  8147. * @memberOf R
  8148. * @since v0.4.0
  8149. * @category Object
  8150. * @sig {String: *} -> [[String,*]]
  8151. * @param {Object} obj The object to extract from
  8152. * @return {Array} An array of key, value arrays from the object's own properties.
  8153. * @see R.fromPairs
  8154. * @example
  8155. *
  8156. * R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]]
  8157. */
  8158. var toPairs = _curry1(function toPairs(obj) {
  8159. var pairs = [];
  8160. for (var prop in obj) {
  8161. if (_has(prop, obj)) {
  8162. pairs[pairs.length] = [prop, obj[prop]];
  8163. }
  8164. }
  8165. return pairs;
  8166. });
  8167. /**
  8168. * Converts an object into an array of key, value arrays. The object's own
  8169. * properties and prototype properties are used. Note that the order of the
  8170. * output array is not guaranteed to be consistent across different JS
  8171. * platforms.
  8172. *
  8173. * @func
  8174. * @memberOf R
  8175. * @since v0.4.0
  8176. * @category Object
  8177. * @sig {String: *} -> [[String,*]]
  8178. * @param {Object} obj The object to extract from
  8179. * @return {Array} An array of key, value arrays from the object's own
  8180. * and prototype properties.
  8181. * @example
  8182. *
  8183. * const F = function() { this.x = 'X'; };
  8184. * F.prototype.y = 'Y';
  8185. * const f = new F();
  8186. * R.toPairsIn(f); //=> [['x','X'], ['y','Y']]
  8187. */
  8188. var toPairsIn = _curry1(function toPairsIn(obj) {
  8189. var pairs = [];
  8190. for (var prop in obj) {
  8191. pairs[pairs.length] = [prop, obj[prop]];
  8192. }
  8193. return pairs;
  8194. });
  8195. /**
  8196. * The upper case version of a string.
  8197. *
  8198. * @func
  8199. * @memberOf R
  8200. * @since v0.9.0
  8201. * @category String
  8202. * @sig String -> String
  8203. * @param {String} str The string to upper case.
  8204. * @return {String} The upper case version of `str`.
  8205. * @see R.toLower
  8206. * @example
  8207. *
  8208. * R.toUpper('abc'); //=> 'ABC'
  8209. */
  8210. var toUpper = invoker(0, 'toUpperCase');
  8211. /**
  8212. * Initializes a transducer using supplied iterator function. Returns a single
  8213. * item by iterating through the list, successively calling the transformed
  8214. * iterator function and passing it an accumulator value and the current value
  8215. * from the array, and then passing the result to the next call.
  8216. *
  8217. * The iterator function receives two values: *(acc, value)*. It will be
  8218. * wrapped as a transformer to initialize the transducer. A transformer can be
  8219. * passed directly in place of an iterator function. In both cases, iteration
  8220. * may be stopped early with the [`R.reduced`](#reduced) function.
  8221. *
  8222. * A transducer is a function that accepts a transformer and returns a
  8223. * transformer and can be composed directly.
  8224. *
  8225. * A transformer is an an object that provides a 2-arity reducing iterator
  8226. * function, step, 0-arity initial value function, init, and 1-arity result
  8227. * extraction function, result. The step function is used as the iterator
  8228. * function in reduce. The result function is used to convert the final
  8229. * accumulator into the return type and in most cases is
  8230. * [`R.identity`](#identity). The init function can be used to provide an
  8231. * initial accumulator, but is ignored by transduce.
  8232. *
  8233. * The iteration is performed with [`R.reduce`](#reduce) after initializing the transducer.
  8234. *
  8235. * @func
  8236. * @memberOf R
  8237. * @since v0.12.0
  8238. * @category List
  8239. * @sig (c -> c) -> ((a, b) -> a) -> a -> [b] -> a
  8240. * @param {Function} xf The transducer function. Receives a transformer and returns a transformer.
  8241. * @param {Function} fn The iterator function. Receives two values, the accumulator and the
  8242. * current element from the array. Wrapped as transformer, if necessary, and used to
  8243. * initialize the transducer
  8244. * @param {*} acc The initial accumulator value.
  8245. * @param {Array} list The list to iterate over.
  8246. * @return {*} The final, accumulated value.
  8247. * @see R.reduce, R.reduced, R.into
  8248. * @example
  8249. *
  8250. * const numbers = [1, 2, 3, 4];
  8251. * const transducer = R.compose(R.map(R.add(1)), R.take(2));
  8252. * R.transduce(transducer, R.flip(R.append), [], numbers); //=> [2, 3]
  8253. *
  8254. * const isOdd = (x) => x % 2 === 1;
  8255. * const firstOddTransducer = R.compose(R.filter(isOdd), R.take(1));
  8256. * R.transduce(firstOddTransducer, R.flip(R.append), [], R.range(0, 100)); //=> [1]
  8257. */
  8258. var transduce = curryN(4, function transduce(xf, fn, acc, list) {
  8259. return _reduce(xf(typeof fn === 'function' ? _xwrap(fn) : fn), acc, list);
  8260. });
  8261. /**
  8262. * Transposes the rows and columns of a 2D list.
  8263. * When passed a list of `n` lists of length `x`,
  8264. * returns a list of `x` lists of length `n`.
  8265. *
  8266. *
  8267. * @func
  8268. * @memberOf R
  8269. * @since v0.19.0
  8270. * @category List
  8271. * @sig [[a]] -> [[a]]
  8272. * @param {Array} list A 2D list
  8273. * @return {Array} A 2D list
  8274. * @example
  8275. *
  8276. * R.transpose([[1, 'a'], [2, 'b'], [3, 'c']]) //=> [[1, 2, 3], ['a', 'b', 'c']]
  8277. * R.transpose([[1, 2, 3], ['a', 'b', 'c']]) //=> [[1, 'a'], [2, 'b'], [3, 'c']]
  8278. *
  8279. * // If some of the rows are shorter than the following rows, their elements are skipped:
  8280. * R.transpose([[10, 11], [20], [], [30, 31, 32]]) //=> [[10, 20, 30], [11, 31], [32]]
  8281. * @symb R.transpose([[a], [b], [c]]) = [a, b, c]
  8282. * @symb R.transpose([[a, b], [c, d]]) = [[a, c], [b, d]]
  8283. * @symb R.transpose([[a, b], [c]]) = [[a, c], [b]]
  8284. */
  8285. var transpose = _curry1(function transpose(outerlist) {
  8286. var i = 0;
  8287. var result = [];
  8288. while (i < outerlist.length) {
  8289. var innerlist = outerlist[i];
  8290. var j = 0;
  8291. while (j < innerlist.length) {
  8292. if (typeof result[j] === 'undefined') {
  8293. result[j] = [];
  8294. }
  8295. result[j].push(innerlist[j]);
  8296. j += 1;
  8297. }
  8298. i += 1;
  8299. }
  8300. return result;
  8301. });
  8302. /**
  8303. * Maps an [Applicative](https://github.com/fantasyland/fantasy-land#applicative)-returning
  8304. * function over a [Traversable](https://github.com/fantasyland/fantasy-land#traversable),
  8305. * then uses [`sequence`](#sequence) to transform the resulting Traversable of Applicative
  8306. * into an Applicative of Traversable.
  8307. *
  8308. * Dispatches to the `traverse` method of the third argument, if present.
  8309. *
  8310. * @func
  8311. * @memberOf R
  8312. * @since v0.19.0
  8313. * @category List
  8314. * @sig (Applicative f, Traversable t) => (a -> f a) -> (a -> f b) -> t a -> f (t b)
  8315. * @param {Function} of
  8316. * @param {Function} f
  8317. * @param {*} traversable
  8318. * @return {*}
  8319. * @see R.sequence
  8320. * @example
  8321. *
  8322. * // Returns `Maybe.Nothing` if the given divisor is `0`
  8323. * const safeDiv = n => d => d === 0 ? Maybe.Nothing() : Maybe.Just(n / d)
  8324. *
  8325. * R.traverse(Maybe.of, safeDiv(10), [2, 4, 5]); //=> Maybe.Just([5, 2.5, 2])
  8326. * R.traverse(Maybe.of, safeDiv(10), [2, 0, 5]); //=> Maybe.Nothing
  8327. */
  8328. var traverse = _curry3(function traverse(of, f, traversable) {
  8329. return typeof traversable['fantasy-land/traverse'] === 'function' ?
  8330. traversable['fantasy-land/traverse'](f, of) :
  8331. sequence(of, map(f, traversable));
  8332. });
  8333. var ws = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
  8334. '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028' +
  8335. '\u2029\uFEFF';
  8336. var zeroWidth = '\u200b';
  8337. var hasProtoTrim = (typeof String.prototype.trim === 'function');
  8338. /**
  8339. * Removes (strips) whitespace from both ends of the string.
  8340. *
  8341. * @func
  8342. * @memberOf R
  8343. * @since v0.6.0
  8344. * @category String
  8345. * @sig String -> String
  8346. * @param {String} str The string to trim.
  8347. * @return {String} Trimmed version of `str`.
  8348. * @example
  8349. *
  8350. * R.trim(' xyz '); //=> 'xyz'
  8351. * R.map(R.trim, R.split(',', 'x, y, z')); //=> ['x', 'y', 'z']
  8352. */
  8353. var trim = !hasProtoTrim || (ws.trim() || !zeroWidth.trim()) ?
  8354. _curry1(function trim(str) {
  8355. var beginRx = new RegExp('^[' + ws + '][' + ws + ']*');
  8356. var endRx = new RegExp('[' + ws + '][' + ws + ']*$');
  8357. return str.replace(beginRx, '').replace(endRx, '');
  8358. }) :
  8359. _curry1(function trim(str) {
  8360. return str.trim();
  8361. });
  8362. /**
  8363. * `tryCatch` takes two functions, a `tryer` and a `catcher`. The returned
  8364. * function evaluates the `tryer`; if it does not throw, it simply returns the
  8365. * result. If the `tryer` *does* throw, the returned function evaluates the
  8366. * `catcher` function and returns its result. Note that for effective
  8367. * composition with this function, both the `tryer` and `catcher` functions
  8368. * must return the same type of results.
  8369. *
  8370. * @func
  8371. * @memberOf R
  8372. * @since v0.20.0
  8373. * @category Function
  8374. * @sig (...x -> a) -> ((e, ...x) -> a) -> (...x -> a)
  8375. * @param {Function} tryer The function that may throw.
  8376. * @param {Function} catcher The function that will be evaluated if `tryer` throws.
  8377. * @return {Function} A new function that will catch exceptions and send then to the catcher.
  8378. * @example
  8379. *
  8380. * R.tryCatch(R.prop('x'), R.F)({x: true}); //=> true
  8381. * R.tryCatch(() => { throw 'foo'}, R.always('catched'))('bar') // => 'catched'
  8382. * R.tryCatch(R.times(R.identity), R.always([]))('s') // => []
  8383. * R.tryCatch(() => { throw 'this is not a valid value'}, (err, value)=>({error : err, value }))('bar') // => {'error': 'this is not a valid value', 'value': 'bar'}
  8384. */
  8385. var tryCatch = _curry2(function _tryCatch(tryer, catcher) {
  8386. return _arity(tryer.length, function() {
  8387. try {
  8388. return tryer.apply(this, arguments);
  8389. } catch (e) {
  8390. return catcher.apply(this, _concat([e], arguments));
  8391. }
  8392. });
  8393. });
  8394. /**
  8395. * Takes a function `fn`, which takes a single array argument, and returns a
  8396. * function which:
  8397. *
  8398. * - takes any number of positional arguments;
  8399. * - passes these arguments to `fn` as an array; and
  8400. * - returns the result.
  8401. *
  8402. * In other words, `R.unapply` derives a variadic function from a function which
  8403. * takes an array. `R.unapply` is the inverse of [`R.apply`](#apply).
  8404. *
  8405. * @func
  8406. * @memberOf R
  8407. * @since v0.8.0
  8408. * @category Function
  8409. * @sig ([*...] -> a) -> (*... -> a)
  8410. * @param {Function} fn
  8411. * @return {Function}
  8412. * @see R.apply
  8413. * @example
  8414. *
  8415. * R.unapply(JSON.stringify)(1, 2, 3); //=> '[1,2,3]'
  8416. * @symb R.unapply(f)(a, b) = f([a, b])
  8417. */
  8418. var unapply = _curry1(function unapply(fn) {
  8419. return function() {
  8420. return fn(Array.prototype.slice.call(arguments, 0));
  8421. };
  8422. });
  8423. /**
  8424. * Wraps a function of any arity (including nullary) in a function that accepts
  8425. * exactly 1 parameter. Any extraneous parameters will not be passed to the
  8426. * supplied function.
  8427. *
  8428. * @func
  8429. * @memberOf R
  8430. * @since v0.2.0
  8431. * @category Function
  8432. * @sig (* -> b) -> (a -> b)
  8433. * @param {Function} fn The function to wrap.
  8434. * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
  8435. * arity 1.
  8436. * @see R.binary, R.nAry
  8437. * @example
  8438. *
  8439. * const takesTwoArgs = function(a, b) {
  8440. * return [a, b];
  8441. * };
  8442. * takesTwoArgs.length; //=> 2
  8443. * takesTwoArgs(1, 2); //=> [1, 2]
  8444. *
  8445. * const takesOneArg = R.unary(takesTwoArgs);
  8446. * takesOneArg.length; //=> 1
  8447. * // Only 1 argument is passed to the wrapped function
  8448. * takesOneArg(1, 2); //=> [1, undefined]
  8449. * @symb R.unary(f)(a, b, c) = f(a)
  8450. */
  8451. var unary = _curry1(function unary(fn) {
  8452. return nAry(1, fn);
  8453. });
  8454. /**
  8455. * Returns a function of arity `n` from a (manually) curried function.
  8456. *
  8457. * @func
  8458. * @memberOf R
  8459. * @since v0.14.0
  8460. * @category Function
  8461. * @sig Number -> (a -> b) -> (a -> c)
  8462. * @param {Number} length The arity for the returned function.
  8463. * @param {Function} fn The function to uncurry.
  8464. * @return {Function} A new function.
  8465. * @see R.curry
  8466. * @example
  8467. *
  8468. * const addFour = a => b => c => d => a + b + c + d;
  8469. *
  8470. * const uncurriedAddFour = R.uncurryN(4, addFour);
  8471. * uncurriedAddFour(1, 2, 3, 4); //=> 10
  8472. */
  8473. var uncurryN = _curry2(function uncurryN(depth, fn) {
  8474. return curryN(depth, function() {
  8475. var currentDepth = 1;
  8476. var value = fn;
  8477. var idx = 0;
  8478. var endIdx;
  8479. while (currentDepth <= depth && typeof value === 'function') {
  8480. endIdx = currentDepth === depth ? arguments.length : idx + value.length;
  8481. value = value.apply(this, Array.prototype.slice.call(arguments, idx, endIdx));
  8482. currentDepth += 1;
  8483. idx = endIdx;
  8484. }
  8485. return value;
  8486. });
  8487. });
  8488. /**
  8489. * Builds a list from a seed value. Accepts an iterator function, which returns
  8490. * either false to stop iteration or an array of length 2 containing the value
  8491. * to add to the resulting list and the seed to be used in the next call to the
  8492. * iterator function.
  8493. *
  8494. * The iterator function receives one argument: *(seed)*.
  8495. *
  8496. * @func
  8497. * @memberOf R
  8498. * @since v0.10.0
  8499. * @category List
  8500. * @sig (a -> [b]) -> * -> [b]
  8501. * @param {Function} fn The iterator function. receives one argument, `seed`, and returns
  8502. * either false to quit iteration or an array of length two to proceed. The element
  8503. * at index 0 of this array will be added to the resulting array, and the element
  8504. * at index 1 will be passed to the next call to `fn`.
  8505. * @param {*} seed The seed value.
  8506. * @return {Array} The final list.
  8507. * @example
  8508. *
  8509. * const f = n => n > 50 ? false : [-n, n + 10];
  8510. * R.unfold(f, 10); //=> [-10, -20, -30, -40, -50]
  8511. * @symb R.unfold(f, x) = [f(x)[0], f(f(x)[1])[0], f(f(f(x)[1])[1])[0], ...]
  8512. */
  8513. var unfold = _curry2(function unfold(fn, seed) {
  8514. var pair = fn(seed);
  8515. var result = [];
  8516. while (pair && pair.length) {
  8517. result[result.length] = pair[0];
  8518. pair = fn(pair[1]);
  8519. }
  8520. return result;
  8521. });
  8522. /**
  8523. * Combines two lists into a set (i.e. no duplicates) composed of the elements
  8524. * of each list.
  8525. *
  8526. * @func
  8527. * @memberOf R
  8528. * @since v0.1.0
  8529. * @category Relation
  8530. * @sig [*] -> [*] -> [*]
  8531. * @param {Array} as The first list.
  8532. * @param {Array} bs The second list.
  8533. * @return {Array} The first and second lists concatenated, with
  8534. * duplicates removed.
  8535. * @example
  8536. *
  8537. * R.union([1, 2, 3], [2, 3, 4]); //=> [1, 2, 3, 4]
  8538. */
  8539. var union = _curry2(compose(uniq, _concat));
  8540. /**
  8541. * Returns a new list containing only one copy of each element in the original
  8542. * list, based upon the value returned by applying the supplied predicate to
  8543. * two list elements. Prefers the first item if two items compare equal based
  8544. * on the predicate.
  8545. *
  8546. * @func
  8547. * @memberOf R
  8548. * @since v0.2.0
  8549. * @category List
  8550. * @sig ((a, a) -> Boolean) -> [a] -> [a]
  8551. * @param {Function} pred A predicate used to test whether two items are equal.
  8552. * @param {Array} list The array to consider.
  8553. * @return {Array} The list of unique items.
  8554. * @example
  8555. *
  8556. * const strEq = R.eqBy(String);
  8557. * R.uniqWith(strEq)([1, '1', 2, 1]); //=> [1, 2]
  8558. * R.uniqWith(strEq)([{}, {}]); //=> [{}]
  8559. * R.uniqWith(strEq)([1, '1', 1]); //=> [1]
  8560. * R.uniqWith(strEq)(['1', 1, 1]); //=> ['1']
  8561. */
  8562. var uniqWith = _curry2(function uniqWith(pred, list) {
  8563. var idx = 0;
  8564. var len = list.length;
  8565. var result = [];
  8566. var item;
  8567. while (idx < len) {
  8568. item = list[idx];
  8569. if (!_includesWith(pred, item, result)) {
  8570. result[result.length] = item;
  8571. }
  8572. idx += 1;
  8573. }
  8574. return result;
  8575. });
  8576. /**
  8577. * Combines two lists into a set (i.e. no duplicates) composed of the elements
  8578. * of each list. Duplication is determined according to the value returned by
  8579. * applying the supplied predicate to two list elements.
  8580. *
  8581. * @func
  8582. * @memberOf R
  8583. * @since v0.1.0
  8584. * @category Relation
  8585. * @sig ((a, a) -> Boolean) -> [*] -> [*] -> [*]
  8586. * @param {Function} pred A predicate used to test whether two items are equal.
  8587. * @param {Array} list1 The first list.
  8588. * @param {Array} list2 The second list.
  8589. * @return {Array} The first and second lists concatenated, with
  8590. * duplicates removed.
  8591. * @see R.union
  8592. * @example
  8593. *
  8594. * const l1 = [{a: 1}, {a: 2}];
  8595. * const l2 = [{a: 1}, {a: 4}];
  8596. * R.unionWith(R.eqBy(R.prop('a')), l1, l2); //=> [{a: 1}, {a: 2}, {a: 4}]
  8597. */
  8598. var unionWith = _curry3(function unionWith(pred, list1, list2) {
  8599. return uniqWith(pred, _concat(list1, list2));
  8600. });
  8601. /**
  8602. * Tests the final argument by passing it to the given predicate function. If
  8603. * the predicate is not satisfied, the function will return the result of
  8604. * calling the `whenFalseFn` function with the same argument. If the predicate
  8605. * is satisfied, the argument is returned as is.
  8606. *
  8607. * @func
  8608. * @memberOf R
  8609. * @since v0.18.0
  8610. * @category Logic
  8611. * @sig (a -> Boolean) -> (a -> a) -> a -> a
  8612. * @param {Function} pred A predicate function
  8613. * @param {Function} whenFalseFn A function to invoke when the `pred` evaluates
  8614. * to a falsy value.
  8615. * @param {*} x An object to test with the `pred` function and
  8616. * pass to `whenFalseFn` if necessary.
  8617. * @return {*} Either `x` or the result of applying `x` to `whenFalseFn`.
  8618. * @see R.ifElse, R.when, R.cond
  8619. * @example
  8620. *
  8621. * let safeInc = R.unless(R.isNil, R.inc);
  8622. * safeInc(null); //=> null
  8623. * safeInc(1); //=> 2
  8624. */
  8625. var unless = _curry3(function unless(pred, whenFalseFn, x) {
  8626. return pred(x) ? x : whenFalseFn(x);
  8627. });
  8628. /**
  8629. * Shorthand for `R.chain(R.identity)`, which removes one level of nesting from
  8630. * any [Chain](https://github.com/fantasyland/fantasy-land#chain).
  8631. *
  8632. * @func
  8633. * @memberOf R
  8634. * @since v0.3.0
  8635. * @category List
  8636. * @sig Chain c => c (c a) -> c a
  8637. * @param {*} list
  8638. * @return {*}
  8639. * @see R.flatten, R.chain
  8640. * @example
  8641. *
  8642. * R.unnest([1, [2], [[3]]]); //=> [1, 2, [3]]
  8643. * R.unnest([[1, 2], [3, 4], [5, 6]]); //=> [1, 2, 3, 4, 5, 6]
  8644. */
  8645. var unnest = chain(_identity);
  8646. /**
  8647. * Takes a predicate, a transformation function, and an initial value,
  8648. * and returns a value of the same type as the initial value.
  8649. * It does so by applying the transformation until the predicate is satisfied,
  8650. * at which point it returns the satisfactory value.
  8651. *
  8652. * @func
  8653. * @memberOf R
  8654. * @since v0.20.0
  8655. * @category Logic
  8656. * @sig (a -> Boolean) -> (a -> a) -> a -> a
  8657. * @param {Function} pred A predicate function
  8658. * @param {Function} fn The iterator function
  8659. * @param {*} init Initial value
  8660. * @return {*} Final value that satisfies predicate
  8661. * @example
  8662. *
  8663. * R.until(R.gt(R.__, 100), R.multiply(2))(1) // => 128
  8664. */
  8665. var until = _curry3(function until(pred, fn, init) {
  8666. var val = init;
  8667. while (!pred(val)) {
  8668. val = fn(val);
  8669. }
  8670. return val;
  8671. });
  8672. /**
  8673. * Returns a list of all the properties, including prototype properties, of the
  8674. * supplied object.
  8675. * Note that the order of the output array is not guaranteed to be consistent
  8676. * across different JS platforms.
  8677. *
  8678. * @func
  8679. * @memberOf R
  8680. * @since v0.2.0
  8681. * @category Object
  8682. * @sig {k: v} -> [v]
  8683. * @param {Object} obj The object to extract values from
  8684. * @return {Array} An array of the values of the object's own and prototype properties.
  8685. * @see R.values, R.keysIn
  8686. * @example
  8687. *
  8688. * const F = function() { this.x = 'X'; };
  8689. * F.prototype.y = 'Y';
  8690. * const f = new F();
  8691. * R.valuesIn(f); //=> ['X', 'Y']
  8692. */
  8693. var valuesIn = _curry1(function valuesIn(obj) {
  8694. var prop;
  8695. var vs = [];
  8696. for (prop in obj) {
  8697. vs[vs.length] = obj[prop];
  8698. }
  8699. return vs;
  8700. });
  8701. // `Const` is a functor that effectively ignores the function given to `map`.
  8702. var Const = function(x) {
  8703. return {value: x, 'fantasy-land/map': function() { return this; }};
  8704. };
  8705. /**
  8706. * Returns a "view" of the given data structure, determined by the given lens.
  8707. * The lens's focus determines which portion of the data structure is visible.
  8708. *
  8709. * @func
  8710. * @memberOf R
  8711. * @since v0.16.0
  8712. * @category Object
  8713. * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s
  8714. * @sig Lens s a -> s -> a
  8715. * @param {Lens} lens
  8716. * @param {*} x
  8717. * @return {*}
  8718. * @see R.prop, R.lensIndex, R.lensProp
  8719. * @example
  8720. *
  8721. * const xLens = R.lensProp('x');
  8722. *
  8723. * R.view(xLens, {x: 1, y: 2}); //=> 1
  8724. * R.view(xLens, {x: 4, y: 2}); //=> 4
  8725. */
  8726. var view = _curry2(function view(lens, x) {
  8727. // Using `Const` effectively ignores the setter function of the `lens`,
  8728. // leaving the value returned by the getter function unmodified.
  8729. return lens(Const)(x).value;
  8730. });
  8731. /**
  8732. * Tests the final argument by passing it to the given predicate function. If
  8733. * the predicate is satisfied, the function will return the result of calling
  8734. * the `whenTrueFn` function with the same argument. If the predicate is not
  8735. * satisfied, the argument is returned as is.
  8736. *
  8737. * @func
  8738. * @memberOf R
  8739. * @since v0.18.0
  8740. * @category Logic
  8741. * @sig (a -> Boolean) -> (a -> a) -> a -> a
  8742. * @param {Function} pred A predicate function
  8743. * @param {Function} whenTrueFn A function to invoke when the `condition`
  8744. * evaluates to a truthy value.
  8745. * @param {*} x An object to test with the `pred` function and
  8746. * pass to `whenTrueFn` if necessary.
  8747. * @return {*} Either `x` or the result of applying `x` to `whenTrueFn`.
  8748. * @see R.ifElse, R.unless, R.cond
  8749. * @example
  8750. *
  8751. * // truncate :: String -> String
  8752. * const truncate = R.when(
  8753. * R.propSatisfies(R.gt(R.__, 10), 'length'),
  8754. * R.pipe(R.take(10), R.append('…'), R.join(''))
  8755. * );
  8756. * truncate('12345'); //=> '12345'
  8757. * truncate('0123456789ABC'); //=> '0123456789…'
  8758. */
  8759. var when = _curry3(function when(pred, whenTrueFn, x) {
  8760. return pred(x) ? whenTrueFn(x) : x;
  8761. });
  8762. /**
  8763. * Takes a spec object and a test object; returns true if the test satisfies
  8764. * the spec. Each of the spec's own properties must be a predicate function.
  8765. * Each predicate is applied to the value of the corresponding property of the
  8766. * test object. `where` returns true if all the predicates return true, false
  8767. * otherwise.
  8768. *
  8769. * `where` is well suited to declaratively expressing constraints for other
  8770. * functions such as [`filter`](#filter) and [`find`](#find).
  8771. *
  8772. * @func
  8773. * @memberOf R
  8774. * @since v0.1.1
  8775. * @category Object
  8776. * @sig {String: (* -> Boolean)} -> {String: *} -> Boolean
  8777. * @param {Object} spec
  8778. * @param {Object} testObj
  8779. * @return {Boolean}
  8780. * @see R.propSatisfies, R.whereEq
  8781. * @example
  8782. *
  8783. * // pred :: Object -> Boolean
  8784. * const pred = R.where({
  8785. * a: R.equals('foo'),
  8786. * b: R.complement(R.equals('bar')),
  8787. * x: R.gt(R.__, 10),
  8788. * y: R.lt(R.__, 20)
  8789. * });
  8790. *
  8791. * pred({a: 'foo', b: 'xxx', x: 11, y: 19}); //=> true
  8792. * pred({a: 'xxx', b: 'xxx', x: 11, y: 19}); //=> false
  8793. * pred({a: 'foo', b: 'bar', x: 11, y: 19}); //=> false
  8794. * pred({a: 'foo', b: 'xxx', x: 10, y: 19}); //=> false
  8795. * pred({a: 'foo', b: 'xxx', x: 11, y: 20}); //=> false
  8796. */
  8797. var where = _curry2(function where(spec, testObj) {
  8798. for (var prop in spec) {
  8799. if (_has(prop, spec) && !spec[prop](testObj[prop])) {
  8800. return false;
  8801. }
  8802. }
  8803. return true;
  8804. });
  8805. /**
  8806. * Takes a spec object and a test object; returns true if the test satisfies
  8807. * the spec, false otherwise. An object satisfies the spec if, for each of the
  8808. * spec's own properties, accessing that property of the object gives the same
  8809. * value (in [`R.equals`](#equals) terms) as accessing that property of the
  8810. * spec.
  8811. *
  8812. * `whereEq` is a specialization of [`where`](#where).
  8813. *
  8814. * @func
  8815. * @memberOf R
  8816. * @since v0.14.0
  8817. * @category Object
  8818. * @sig {String: *} -> {String: *} -> Boolean
  8819. * @param {Object} spec
  8820. * @param {Object} testObj
  8821. * @return {Boolean}
  8822. * @see R.propEq, R.where
  8823. * @example
  8824. *
  8825. * // pred :: Object -> Boolean
  8826. * const pred = R.whereEq({a: 1, b: 2});
  8827. *
  8828. * pred({a: 1}); //=> false
  8829. * pred({a: 1, b: 2}); //=> true
  8830. * pred({a: 1, b: 2, c: 3}); //=> true
  8831. * pred({a: 1, b: 1}); //=> false
  8832. */
  8833. var whereEq = _curry2(function whereEq(spec, testObj) {
  8834. return where(map(equals, spec), testObj);
  8835. });
  8836. /**
  8837. * Returns a new list without values in the first argument.
  8838. * [`R.equals`](#equals) is used to determine equality.
  8839. *
  8840. * Acts as a transducer if a transformer is given in list position.
  8841. *
  8842. * @func
  8843. * @memberOf R
  8844. * @since v0.19.0
  8845. * @category List
  8846. * @sig [a] -> [a] -> [a]
  8847. * @param {Array} list1 The values to be removed from `list2`.
  8848. * @param {Array} list2 The array to remove values from.
  8849. * @return {Array} The new array without values in `list1`.
  8850. * @see R.transduce, R.difference, R.remove
  8851. * @example
  8852. *
  8853. * R.without([1, 2], [1, 2, 1, 3, 4]); //=> [3, 4]
  8854. */
  8855. var without = _curry2(function(xs, list) {
  8856. return reject(flip(_includes)(xs), list);
  8857. });
  8858. /**
  8859. * Exclusive disjunction logical operation.
  8860. * Returns `true` if one of the arguments is truthy and the other is falsy.
  8861. * Otherwise, it returns `false`.
  8862. *
  8863. * @func
  8864. * @memberOf R
  8865. * @since v0.27.1
  8866. * @category Logic
  8867. * @sig a -> b -> Boolean
  8868. * @param {Any} a
  8869. * @param {Any} b
  8870. * @return {Boolean} true if one of the arguments is truthy and the other is falsy
  8871. * @see R.or, R.and
  8872. * @example
  8873. *
  8874. * R.xor(true, true); //=> false
  8875. * R.xor(true, false); //=> true
  8876. * R.xor(false, true); //=> true
  8877. * R.xor(false, false); //=> false
  8878. */
  8879. var xor = _curry2(function xor(a, b) {
  8880. return Boolean(!a ^ !b);
  8881. });
  8882. /**
  8883. * Creates a new list out of the two supplied by creating each possible pair
  8884. * from the lists.
  8885. *
  8886. * @func
  8887. * @memberOf R
  8888. * @since v0.1.0
  8889. * @category List
  8890. * @sig [a] -> [b] -> [[a,b]]
  8891. * @param {Array} as The first list.
  8892. * @param {Array} bs The second list.
  8893. * @return {Array} The list made by combining each possible pair from
  8894. * `as` and `bs` into pairs (`[a, b]`).
  8895. * @example
  8896. *
  8897. * R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
  8898. * @symb R.xprod([a, b], [c, d]) = [[a, c], [a, d], [b, c], [b, d]]
  8899. */
  8900. var xprod = _curry2(function xprod(a, b) { // = xprodWith(prepend); (takes about 3 times as long...)
  8901. var idx = 0;
  8902. var ilen = a.length;
  8903. var j;
  8904. var jlen = b.length;
  8905. var result = [];
  8906. while (idx < ilen) {
  8907. j = 0;
  8908. while (j < jlen) {
  8909. result[result.length] = [a[idx], b[j]];
  8910. j += 1;
  8911. }
  8912. idx += 1;
  8913. }
  8914. return result;
  8915. });
  8916. /**
  8917. * Creates a new list out of the two supplied by pairing up equally-positioned
  8918. * items from both lists. The returned list is truncated to the length of the
  8919. * shorter of the two input lists.
  8920. * Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`.
  8921. *
  8922. * @func
  8923. * @memberOf R
  8924. * @since v0.1.0
  8925. * @category List
  8926. * @sig [a] -> [b] -> [[a,b]]
  8927. * @param {Array} list1 The first array to consider.
  8928. * @param {Array} list2 The second array to consider.
  8929. * @return {Array} The list made by pairing up same-indexed elements of `list1` and `list2`.
  8930. * @example
  8931. *
  8932. * R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']]
  8933. * @symb R.zip([a, b, c], [d, e, f]) = [[a, d], [b, e], [c, f]]
  8934. */
  8935. var zip = _curry2(function zip(a, b) {
  8936. var rv = [];
  8937. var idx = 0;
  8938. var len = Math.min(a.length, b.length);
  8939. while (idx < len) {
  8940. rv[idx] = [a[idx], b[idx]];
  8941. idx += 1;
  8942. }
  8943. return rv;
  8944. });
  8945. /**
  8946. * Creates a new object out of a list of keys and a list of values.
  8947. * Key/value pairing is truncated to the length of the shorter of the two lists.
  8948. * Note: `zipObj` is equivalent to `pipe(zip, fromPairs)`.
  8949. *
  8950. * @func
  8951. * @memberOf R
  8952. * @since v0.3.0
  8953. * @category List
  8954. * @sig [String] -> [*] -> {String: *}
  8955. * @param {Array} keys The array that will be properties on the output object.
  8956. * @param {Array} values The list of values on the output object.
  8957. * @return {Object} The object made by pairing up same-indexed elements of `keys` and `values`.
  8958. * @example
  8959. *
  8960. * R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3}
  8961. */
  8962. var zipObj = _curry2(function zipObj(keys, values) {
  8963. var idx = 0;
  8964. var len = Math.min(keys.length, values.length);
  8965. var out = {};
  8966. while (idx < len) {
  8967. out[keys[idx]] = values[idx];
  8968. idx += 1;
  8969. }
  8970. return out;
  8971. });
  8972. /**
  8973. * Creates a new list out of the two supplied by applying the function to each
  8974. * equally-positioned pair in the lists. The returned list is truncated to the
  8975. * length of the shorter of the two input lists.
  8976. *
  8977. * @function
  8978. * @memberOf R
  8979. * @since v0.1.0
  8980. * @category List
  8981. * @sig ((a, b) -> c) -> [a] -> [b] -> [c]
  8982. * @param {Function} fn The function used to combine the two elements into one value.
  8983. * @param {Array} list1 The first array to consider.
  8984. * @param {Array} list2 The second array to consider.
  8985. * @return {Array} The list made by combining same-indexed elements of `list1` and `list2`
  8986. * using `fn`.
  8987. * @example
  8988. *
  8989. * const f = (x, y) => {
  8990. * // ...
  8991. * };
  8992. * R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']);
  8993. * //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')]
  8994. * @symb R.zipWith(fn, [a, b, c], [d, e, f]) = [fn(a, d), fn(b, e), fn(c, f)]
  8995. */
  8996. var zipWith = _curry3(function zipWith(fn, a, b) {
  8997. var rv = [];
  8998. var idx = 0;
  8999. var len = Math.min(a.length, b.length);
  9000. while (idx < len) {
  9001. rv[idx] = fn(a[idx], b[idx]);
  9002. idx += 1;
  9003. }
  9004. return rv;
  9005. });
  9006. /**
  9007. * Creates a thunk out of a function. A thunk delays a calculation until
  9008. * its result is needed, providing lazy evaluation of arguments.
  9009. *
  9010. * @func
  9011. * @memberOf R
  9012. * @since v0.26.0
  9013. * @category Function
  9014. * @sig ((a, b, ..., j) -> k) -> (a, b, ..., j) -> (() -> k)
  9015. * @param {Function} fn A function to wrap in a thunk
  9016. * @return {Function} Expects arguments for `fn` and returns a new function
  9017. * that, when called, applies those arguments to `fn`.
  9018. * @see R.partial, R.partialRight
  9019. * @example
  9020. *
  9021. * R.thunkify(R.identity)(42)(); //=> 42
  9022. * R.thunkify((a, b) => a + b)(25, 17)(); //=> 42
  9023. */
  9024. var thunkify = _curry1(function thunkify(fn) {
  9025. return curryN(fn.length, function createThunk() {
  9026. var fnArgs = arguments;
  9027. return function invokeThunk() {
  9028. return fn.apply(this, fnArgs);
  9029. };
  9030. });
  9031. });
  9032. exports.F = F;
  9033. exports.T = T;
  9034. exports.__ = __;
  9035. exports.add = add;
  9036. exports.addIndex = addIndex;
  9037. exports.adjust = adjust;
  9038. exports.all = all;
  9039. exports.allPass = allPass;
  9040. exports.always = always;
  9041. exports.and = and;
  9042. exports.any = any;
  9043. exports.anyPass = anyPass;
  9044. exports.ap = ap;
  9045. exports.aperture = aperture;
  9046. exports.append = append;
  9047. exports.apply = apply;
  9048. exports.applySpec = applySpec;
  9049. exports.applyTo = applyTo;
  9050. exports.ascend = ascend;
  9051. exports.assoc = assoc;
  9052. exports.assocPath = assocPath;
  9053. exports.binary = binary;
  9054. exports.bind = bind;
  9055. exports.both = both;
  9056. exports.call = call;
  9057. exports.chain = chain;
  9058. exports.clamp = clamp;
  9059. exports.clone = clone;
  9060. exports.comparator = comparator;
  9061. exports.complement = complement;
  9062. exports.compose = compose;
  9063. exports.composeK = composeK;
  9064. exports.composeP = composeP;
  9065. exports.composeWith = composeWith;
  9066. exports.concat = concat;
  9067. exports.cond = cond;
  9068. exports.construct = construct;
  9069. exports.constructN = constructN;
  9070. exports.contains = contains$1;
  9071. exports.converge = converge;
  9072. exports.countBy = countBy;
  9073. exports.curry = curry;
  9074. exports.curryN = curryN;
  9075. exports.dec = dec;
  9076. exports.defaultTo = defaultTo;
  9077. exports.descend = descend;
  9078. exports.difference = difference;
  9079. exports.differenceWith = differenceWith;
  9080. exports.dissoc = dissoc;
  9081. exports.dissocPath = dissocPath;
  9082. exports.divide = divide;
  9083. exports.drop = drop;
  9084. exports.dropLast = dropLast$1;
  9085. exports.dropLastWhile = dropLastWhile$1;
  9086. exports.dropRepeats = dropRepeats;
  9087. exports.dropRepeatsWith = dropRepeatsWith;
  9088. exports.dropWhile = dropWhile;
  9089. exports.either = either;
  9090. exports.empty = empty;
  9091. exports.endsWith = endsWith;
  9092. exports.eqBy = eqBy;
  9093. exports.eqProps = eqProps;
  9094. exports.equals = equals;
  9095. exports.evolve = evolve;
  9096. exports.filter = filter;
  9097. exports.find = find;
  9098. exports.findIndex = findIndex;
  9099. exports.findLast = findLast;
  9100. exports.findLastIndex = findLastIndex;
  9101. exports.flatten = flatten;
  9102. exports.flip = flip;
  9103. exports.forEach = forEach;
  9104. exports.forEachObjIndexed = forEachObjIndexed;
  9105. exports.fromPairs = fromPairs;
  9106. exports.groupBy = groupBy;
  9107. exports.groupWith = groupWith;
  9108. exports.gt = gt;
  9109. exports.gte = gte;
  9110. exports.has = has;
  9111. exports.hasIn = hasIn;
  9112. exports.hasPath = hasPath;
  9113. exports.head = head;
  9114. exports.identical = identical;
  9115. exports.identity = identity;
  9116. exports.ifElse = ifElse;
  9117. exports.inc = inc;
  9118. exports.includes = includes;
  9119. exports.indexBy = indexBy;
  9120. exports.indexOf = indexOf;
  9121. exports.init = init;
  9122. exports.innerJoin = innerJoin;
  9123. exports.insert = insert;
  9124. exports.insertAll = insertAll;
  9125. exports.intersection = intersection;
  9126. exports.intersperse = intersperse;
  9127. exports.into = into;
  9128. exports.invert = invert;
  9129. exports.invertObj = invertObj;
  9130. exports.invoker = invoker;
  9131. exports.is = is;
  9132. exports.isEmpty = isEmpty;
  9133. exports.isNil = isNil;
  9134. exports.join = join;
  9135. exports.juxt = juxt;
  9136. exports.keys = keys;
  9137. exports.keysIn = keysIn;
  9138. exports.last = last;
  9139. exports.lastIndexOf = lastIndexOf;
  9140. exports.length = length;
  9141. exports.lens = lens;
  9142. exports.lensIndex = lensIndex;
  9143. exports.lensPath = lensPath;
  9144. exports.lensProp = lensProp;
  9145. exports.lift = lift;
  9146. exports.liftN = liftN;
  9147. exports.lt = lt;
  9148. exports.lte = lte;
  9149. exports.map = map;
  9150. exports.mapAccum = mapAccum;
  9151. exports.mapAccumRight = mapAccumRight;
  9152. exports.mapObjIndexed = mapObjIndexed;
  9153. exports.match = match;
  9154. exports.mathMod = mathMod;
  9155. exports.max = max;
  9156. exports.maxBy = maxBy;
  9157. exports.mean = mean;
  9158. exports.median = median;
  9159. exports.memoizeWith = memoizeWith;
  9160. exports.merge = merge;
  9161. exports.mergeAll = mergeAll;
  9162. exports.mergeDeepLeft = mergeDeepLeft;
  9163. exports.mergeDeepRight = mergeDeepRight;
  9164. exports.mergeDeepWith = mergeDeepWith;
  9165. exports.mergeDeepWithKey = mergeDeepWithKey;
  9166. exports.mergeLeft = mergeLeft;
  9167. exports.mergeRight = mergeRight;
  9168. exports.mergeWith = mergeWith;
  9169. exports.mergeWithKey = mergeWithKey;
  9170. exports.min = min;
  9171. exports.minBy = minBy;
  9172. exports.modulo = modulo;
  9173. exports.move = move;
  9174. exports.multiply = multiply;
  9175. exports.nAry = nAry;
  9176. exports.negate = negate;
  9177. exports.none = none;
  9178. exports.not = not;
  9179. exports.nth = nth;
  9180. exports.nthArg = nthArg;
  9181. exports.o = o;
  9182. exports.objOf = objOf;
  9183. exports.of = of;
  9184. exports.omit = omit;
  9185. exports.once = once;
  9186. exports.or = or;
  9187. exports.otherwise = otherwise;
  9188. exports.over = over;
  9189. exports.pair = pair;
  9190. exports.partial = partial;
  9191. exports.partialRight = partialRight;
  9192. exports.partition = partition;
  9193. exports.path = path;
  9194. exports.paths = paths;
  9195. exports.pathEq = pathEq;
  9196. exports.pathOr = pathOr;
  9197. exports.pathSatisfies = pathSatisfies;
  9198. exports.pick = pick;
  9199. exports.pickAll = pickAll;
  9200. exports.pickBy = pickBy;
  9201. exports.pipe = pipe;
  9202. exports.pipeK = pipeK;
  9203. exports.pipeP = pipeP;
  9204. exports.pipeWith = pipeWith;
  9205. exports.pluck = pluck;
  9206. exports.prepend = prepend;
  9207. exports.product = product;
  9208. exports.project = project;
  9209. exports.prop = prop;
  9210. exports.propEq = propEq;
  9211. exports.propIs = propIs;
  9212. exports.propOr = propOr;
  9213. exports.propSatisfies = propSatisfies;
  9214. exports.props = props;
  9215. exports.range = range;
  9216. exports.reduce = reduce;
  9217. exports.reduceBy = reduceBy;
  9218. exports.reduceRight = reduceRight;
  9219. exports.reduceWhile = reduceWhile;
  9220. exports.reduced = reduced;
  9221. exports.reject = reject;
  9222. exports.remove = remove;
  9223. exports.repeat = repeat;
  9224. exports.replace = replace;
  9225. exports.reverse = reverse;
  9226. exports.scan = scan;
  9227. exports.sequence = sequence;
  9228. exports.set = set;
  9229. exports.slice = slice;
  9230. exports.sort = sort;
  9231. exports.sortBy = sortBy;
  9232. exports.sortWith = sortWith;
  9233. exports.split = split;
  9234. exports.splitAt = splitAt;
  9235. exports.splitEvery = splitEvery;
  9236. exports.splitWhen = splitWhen;
  9237. exports.startsWith = startsWith;
  9238. exports.subtract = subtract;
  9239. exports.sum = sum;
  9240. exports.symmetricDifference = symmetricDifference;
  9241. exports.symmetricDifferenceWith = symmetricDifferenceWith;
  9242. exports.tail = tail;
  9243. exports.take = take;
  9244. exports.takeLast = takeLast;
  9245. exports.takeLastWhile = takeLastWhile;
  9246. exports.takeWhile = takeWhile;
  9247. exports.tap = tap;
  9248. exports.test = test;
  9249. exports.andThen = andThen;
  9250. exports.times = times;
  9251. exports.toLower = toLower;
  9252. exports.toPairs = toPairs;
  9253. exports.toPairsIn = toPairsIn;
  9254. exports.toString = toString$1;
  9255. exports.toUpper = toUpper;
  9256. exports.transduce = transduce;
  9257. exports.transpose = transpose;
  9258. exports.traverse = traverse;
  9259. exports.trim = trim;
  9260. exports.tryCatch = tryCatch;
  9261. exports.type = type;
  9262. exports.unapply = unapply;
  9263. exports.unary = unary;
  9264. exports.uncurryN = uncurryN;
  9265. exports.unfold = unfold;
  9266. exports.union = union;
  9267. exports.unionWith = unionWith;
  9268. exports.uniq = uniq;
  9269. exports.uniqBy = uniqBy;
  9270. exports.uniqWith = uniqWith;
  9271. exports.unless = unless;
  9272. exports.unnest = unnest;
  9273. exports.until = until;
  9274. exports.update = update;
  9275. exports.useWith = useWith;
  9276. exports.values = values;
  9277. exports.valuesIn = valuesIn;
  9278. exports.view = view;
  9279. exports.when = when;
  9280. exports.where = where;
  9281. exports.whereEq = whereEq;
  9282. exports.without = without;
  9283. exports.xor = xor;
  9284. exports.xprod = xprod;
  9285. exports.zip = zip;
  9286. exports.zipObj = zipObj;
  9287. exports.zipWith = zipWith;
  9288. exports.thunkify = thunkify;
  9289. Object.defineProperty(exports, '__esModule', { value: true });
  9290. }));