What is keymirror?
The keymirror npm package is a utility that creates an object with values mirroring its keys. This is particularly useful for defining constants, especially in scenarios like Redux action types, where you want to avoid typos and ensure consistency.
What are keymirror's main functionalities?
Create an object with mirrored keys and values
This feature allows you to create an object where the keys are mirrored as values. This is useful for defining constants in a way that avoids typos and ensures consistency.
const keyMirror = require('keymirror');
const actionTypes = keyMirror({
CREATE_USER: null,
DELETE_USER: null,
UPDATE_USER: null
});
console.log(actionTypes); // { CREATE_USER: 'CREATE_USER', DELETE_USER: 'DELETE_USER', UPDATE_USER: 'UPDATE_USER' }
Other packages similar to keymirror
enumify
The enumify package provides a way to create enums in JavaScript. Unlike keymirror, which simply mirrors keys to values, enumify allows for more complex enum definitions, including methods and properties on the enum instances.
object-key-mirror
The object-key-mirror package is very similar to keymirror. It also creates an object with keys mirrored as values. The main difference is in the API and implementation details, but the core functionality remains the same.
constants
The constants package allows you to define constants in a more flexible way compared to keymirror. It supports nested objects and provides additional utilities for working with constants.
KeyMirror
Create an object with values equal to its key names.
I thought react/lib/keyMirror
was useful and wanted to reuse it without any dependencies.
This is not my code, this is property of Facebook.
Usage
npm install keymirror
var keyMirror = require('keyMirror');
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}
I sometimes use this with lodash - use the following upon your first use of lodash to mix it in:
var _ = require('lodash');
_.mixin({keyMirror: require('keyMirror')});