mergeWithKey.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import _curry3 from "./internal/_curry3.js";
  2. import _has from "./internal/_has.js";
  3. /**
  4. * Creates a new object with the own properties of the two provided objects. If
  5. * a key exists in both objects, the provided function is applied to the key
  6. * and the values associated with the key in each object, with the result being
  7. * used as the value associated with the key in the returned object.
  8. *
  9. * @func
  10. * @memberOf R
  11. * @since v0.19.0
  12. * @category Object
  13. * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}
  14. * @param {Function} fn
  15. * @param {Object} l
  16. * @param {Object} r
  17. * @return {Object}
  18. * @see R.mergeDeepWithKey, R.merge, R.mergeWith
  19. * @example
  20. *
  21. * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r
  22. * R.mergeWithKey(concatValues,
  23. * { a: true, thing: 'foo', values: [10, 20] },
  24. * { b: true, thing: 'bar', values: [15, 35] });
  25. * //=> { a: true, b: true, thing: 'bar', values: [10, 20, 15, 35] }
  26. * @symb R.mergeWithKey(f, { x: 1, y: 2 }, { y: 5, z: 3 }) = { x: 1, y: f('y', 2, 5), z: 3 }
  27. */
  28. var mergeWithKey =
  29. /*#__PURE__*/
  30. _curry3(function mergeWithKey(fn, l, r) {
  31. var result = {};
  32. var k;
  33. l = l || {};
  34. r = r || {};
  35. for (k in l) {
  36. if (_has(k, l)) {
  37. result[k] = _has(k, r) ? fn(k, l[k], r[k]) : l[k];
  38. }
  39. }
  40. for (k in r) {
  41. if (_has(k, r) && !_has(k, result)) {
  42. result[k] = r[k];
  43. }
  44. }
  45. return result;
  46. });
  47. export default mergeWithKey;