keyMirror.js.flow 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 keyMirror
  8. * @typechecks static-only
  9. */
  10. 'use strict';
  11. var invariant = require('./invariant');
  12. /**
  13. * Constructs an enumeration with keys equal to their value.
  14. *
  15. * For example:
  16. *
  17. * var COLORS = keyMirror({blue: null, red: null});
  18. * var myColor = COLORS.blue;
  19. * var isColorValid = !!COLORS[myColor];
  20. *
  21. * The last line could not be performed if the values of the generated enum were
  22. * not equal to their keys.
  23. *
  24. * Input: {key1: val1, key2: val2}
  25. * Output: {key1: key1, key2: key2}
  26. *
  27. * @param {object} obj
  28. * @return {object}
  29. */
  30. var keyMirror = function (obj) {
  31. var ret = {};
  32. var key;
  33. invariant(obj instanceof Object && !Array.isArray(obj), 'keyMirror(...): Argument must be an object.');
  34. for (key in obj) {
  35. if (!obj.hasOwnProperty(key)) {
  36. continue;
  37. }
  38. ret[key] = key;
  39. }
  40. return ret;
  41. };
  42. module.exports = keyMirror;