keyMirror.js 1.1 KB

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