keyMirrorRecursive.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * weak
  8. * @typechecks
  9. */
  10. 'use strict';
  11. var invariant = require('./invariant');
  12. /**
  13. * Constructs an enumeration with keys equal to their value. If the value is an
  14. * object, the method is run recursively, including the parent key as a suffix.
  15. * An optional prefix can be provided that will be prepended to each value.
  16. *
  17. * For example:
  18. *
  19. * var ACTIONS = keyMirror({FOO: null, BAR: { BAZ: null, BOZ: null }}});
  20. * ACTIONS.BAR.BAZ = 'BAR.BAZ';
  21. *
  22. * Input: {key1: null, key2: { nested1: null, nested2: null }}}
  23. * Output: {key1: key1, key2: { nested1: nested1, nested2: nested2 }}}
  24. *
  25. * var CONSTANTS = keyMirror({FOO: {BAR: null}}, 'NameSpace');
  26. * console.log(CONSTANTS.FOO.BAR); // NameSpace.FOO.BAR
  27. */
  28. function keyMirrorRecursive(obj, prefix) {
  29. return keyMirrorRecursiveInternal(obj, prefix);
  30. }
  31. function keyMirrorRecursiveInternal(
  32. /*object*/obj,
  33. /*?string*/prefix) /*object*/{
  34. var ret = {};
  35. var key;
  36. !isObject(obj) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'keyMirrorRecursive(...): Argument must be an object.') : invariant(false) : void 0;
  37. for (key in obj) {
  38. if (!obj.hasOwnProperty(key)) {
  39. continue;
  40. }
  41. var val = obj[key];
  42. var newPrefix = prefix ? prefix + '.' + key : key;
  43. if (isObject(val)) {
  44. val = keyMirrorRecursiveInternal(val, newPrefix);
  45. } else {
  46. val = newPrefix;
  47. }
  48. ret[key] = val;
  49. }
  50. return ret;
  51. }
  52. function isObject(obj) /*boolean*/{
  53. return obj instanceof Object && !Array.isArray(obj);
  54. }
  55. module.exports = keyMirrorRecursive;