invertObj.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import _curry1 from "./internal/_curry1.js";
  2. import keys from "./keys.js";
  3. /**
  4. * Returns a new object with the keys of the given object as values, and the
  5. * values of the given object, which are coerced to strings, as keys. Note
  6. * that the last key found is preferred when handling the same value.
  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
  15. * @see R.invert
  16. * @example
  17. *
  18. * const raceResults = {
  19. * first: 'alice',
  20. * second: 'jake'
  21. * };
  22. * R.invertObj(raceResults);
  23. * //=> { 'alice': 'first', 'jake':'second' }
  24. *
  25. * // Alternatively:
  26. * const raceResults = ['alice', 'jake'];
  27. * R.invertObj(raceResults);
  28. * //=> { 'alice': '0', 'jake':'1' }
  29. */
  30. var invertObj =
  31. /*#__PURE__*/
  32. _curry1(function invertObj(obj) {
  33. var props = keys(obj);
  34. var len = props.length;
  35. var idx = 0;
  36. var out = {};
  37. while (idx < len) {
  38. var key = props[idx];
  39. out[obj[key]] = key;
  40. idx += 1;
  41. }
  42. return out;
  43. });
  44. export default invertObj;