Skip to content

Instantly share code, notes, and snippets.

@Lissy93
Last active November 11, 2019 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lissy93/acf635701bf5812431ec07d67d798095 to your computer and use it in GitHub Desktop.
Save Lissy93/acf635701bf5812431ec07d67d798095 to your computer and use it in GitHub Desktop.
Constructs an enumeration with keys equal to their value

A quick function to construct an enumeration which has keys the same as their value 🚀

This used to be part of React, but since it's now been removed (See commit: 56f5115), and some older packages throw an error without it, I'm posting it here in case anyone else needs it.

The first script is a slightly faster version I wrote in TypeScript, but it does exactly the same thing as Facebook's official key-mirror.js which is the one below- so you can use either.

/**
* Copyright Alicia Sykes <https://aliciasykes.com>
* Licensed under MIT X11: https://git.io/Jew4i
*
* Constructs an enumeration with keys equal to their value.
* @param {object} obj
* @return {object}
*/
export function keyMirror(originObj: object) {
if (typeof originObj !== 'object')
throw new Error('keMirror(...): Argument must be an object');
const obj: any = {};
for (const key in originObj) {
if (originObj.hasOwnProperty(key)) obj[key] = key;
}
return obj
}
/**
* Copyright Facebook, Inc.
* Licensed under MIT
*
* @providesModule keyMirror
* @typechecks static-only
*/
"use strict";
var invariant = require('invariant');
/**
* Constructs an enumeration with keys equal to their value.
*
* For example:
*
* var COLORS = keyMirror({blue: null, red: null});
* var myColor = COLORS.blue;
* var isColorValid = !!COLORS[myColor];
*
* The last line could not be performed if the values of the generated enum were
* not equal to their keys.
*
* Input: {key1: val1, key2: val2}
* Output: {key1: key1, key2: key2}
*
* @param {object} obj
* @return {object}
*/
var keyMirror = function(obj) {
var ret = {};
var key;
invariant(
obj instanceof Object && !Array.isArray(obj),
'keyMirror(...): Argument must be an object.'
);
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
module.exports = keyMirror;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment