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.

45 lines
1.1 KiB

4 years ago
  1. import _curry1 from "./internal/_curry1.js";
  2. import _has from "./internal/_has.js";
  3. import keys from "./keys.js";
  4. /**
  5. * Same as [`R.invertObj`](#invertObj), however this accounts for objects with
  6. * duplicate values by putting the values into an array.
  7. *
  8. * @func
  9. * @memberOf R
  10. * @since v0.9.0
  11. * @category Object
  12. * @sig {s: x} -> {x: [ s, ... ]}
  13. * @param {Object} obj The object or array to invert
  14. * @return {Object} out A new object with keys in an array.
  15. * @see R.invertObj
  16. * @example
  17. *
  18. * const raceResultsByFirstName = {
  19. * first: 'alice',
  20. * second: 'jake',
  21. * third: 'alice',
  22. * };
  23. * R.invert(raceResultsByFirstName);
  24. * //=> { 'alice': ['first', 'third'], 'jake':['second'] }
  25. */
  26. var invert =
  27. /*#__PURE__*/
  28. _curry1(function invert(obj) {
  29. var props = keys(obj);
  30. var len = props.length;
  31. var idx = 0;
  32. var out = {};
  33. while (idx < len) {
  34. var key = props[idx];
  35. var val = obj[key];
  36. var list = _has(val, out) ? out[val] : out[val] = [];
  37. list[list.length] = key;
  38. idx += 1;
  39. }
  40. return out;
  41. });
  42. export default invert;