keyMirror.js.flow 1.1 KB

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