keyMirrorRecursive.js.flow 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. * @providesModule keyMirrorRecursive
  8. * @flow weak
  9. * @typechecks
  10. */
  11. 'use strict';
  12. var invariant = require("./invariant");
  13. /**
  14. * Constructs an enumeration with keys equal to their value. If the value is an
  15. * object, the method is run recursively, including the parent key as a suffix.
  16. * An optional prefix can be provided that will be prepended to each value.
  17. *
  18. * For example:
  19. *
  20. * var ACTIONS = keyMirror({FOO: null, BAR: { BAZ: null, BOZ: null }}});
  21. * ACTIONS.BAR.BAZ = 'BAR.BAZ';
  22. *
  23. * Input: {key1: null, key2: { nested1: null, nested2: null }}}
  24. * Output: {key1: key1, key2: { nested1: nested1, nested2: nested2 }}}
  25. *
  26. * var CONSTANTS = keyMirror({FOO: {BAR: null}}, 'NameSpace');
  27. * console.log(CONSTANTS.FOO.BAR); // NameSpace.FOO.BAR
  28. */
  29. function keyMirrorRecursive<T>(obj: T, prefix?: ?string): T {
  30. return keyMirrorRecursiveInternal(obj, prefix);
  31. }
  32. function keyMirrorRecursiveInternal(
  33. /*object*/
  34. obj,
  35. /*?string*/
  36. prefix)
  37. /*object*/
  38. {
  39. var ret = {};
  40. var key;
  41. invariant(isObject(obj), 'keyMirrorRecursive(...): Argument must be an object.');
  42. for (key in obj) {
  43. if (!obj.hasOwnProperty(key)) {
  44. continue;
  45. }
  46. var val = obj[key];
  47. var newPrefix = prefix ? prefix + '.' + key : key;
  48. if (isObject(val)) {
  49. val = keyMirrorRecursiveInternal(val, newPrefix);
  50. } else {
  51. val = newPrefix;
  52. }
  53. ret[key] = val;
  54. }
  55. return ret;
  56. }
  57. function isObject(obj)
  58. /*boolean*/
  59. {
  60. return obj instanceof Object && !Array.isArray(obj);
  61. }
  62. module.exports = keyMirrorRecursive;