keyMirrorRecursive.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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*/
  33. obj,
  34. /*?string*/
  35. prefix)
  36. /*object*/
  37. {
  38. var ret = {};
  39. var key;
  40. !isObject(obj) ? process.env.NODE_ENV !== "production" ? invariant(false, 'keyMirrorRecursive(...): Argument must be an object.') : invariant(false) : void 0;
  41. for (key in obj) {
  42. if (!obj.hasOwnProperty(key)) {
  43. continue;
  44. }
  45. var val = obj[key];
  46. var newPrefix = prefix ? prefix + '.' + key : key;
  47. if (isObject(val)) {
  48. val = keyMirrorRecursiveInternal(val, newPrefix);
  49. } else {
  50. val = newPrefix;
  51. }
  52. ret[key] = val;
  53. }
  54. return ret;
  55. }
  56. function isObject(obj)
  57. /*boolean*/
  58. {
  59. return obj instanceof Object && !Array.isArray(obj);
  60. }
  61. module.exports = keyMirrorRecursive;