adjust.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import _concat from "./internal/_concat.js";
  2. import _curry3 from "./internal/_curry3.js";
  3. /**
  4. * Applies a function to the value at the given index of an array, returning a
  5. * new copy of the array with the element at the given index replaced with the
  6. * result of the function application.
  7. *
  8. * @func
  9. * @memberOf R
  10. * @since v0.14.0
  11. * @category List
  12. * @sig Number -> (a -> a) -> [a] -> [a]
  13. * @param {Number} idx The index.
  14. * @param {Function} fn The function to apply.
  15. * @param {Array|Arguments} list An array-like object whose value
  16. * at the supplied index will be replaced.
  17. * @return {Array} A copy of the supplied array-like object with
  18. * the element at index `idx` replaced with the value
  19. * returned by applying `fn` to the existing element.
  20. * @see R.update
  21. * @example
  22. *
  23. * R.adjust(1, R.toUpper, ['a', 'b', 'c', 'd']); //=> ['a', 'B', 'c', 'd']
  24. * R.adjust(-1, R.toUpper, ['a', 'b', 'c', 'd']); //=> ['a', 'b', 'c', 'D']
  25. * @symb R.adjust(-1, f, [a, b]) = [a, f(b)]
  26. * @symb R.adjust(0, f, [a, b]) = [f(a), b]
  27. */
  28. var adjust =
  29. /*#__PURE__*/
  30. _curry3(function adjust(idx, fn, list) {
  31. var len = list.length;
  32. if (idx >= len || idx < -len) {
  33. return list;
  34. }
  35. var _idx = (len + idx) % len;
  36. var _list = _concat(list);
  37. _list[_idx] = fn(list[_idx]);
  38. return _list;
  39. });
  40. export default adjust;