keyMirrorRecursive.js.flow 1.7 KB

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