Skip to content

Instantly share code, notes, and snippets.

@DungGramer
Created October 31, 2022 04:13
Show Gist options
  • Save DungGramer/93240df1fd539f8f9769f6836526bd0e to your computer and use it in GitHub Desktop.
Save DungGramer/93240df1fd539f8f9769f6836526bd0e to your computer and use it in GitHub Desktop.
export const createEnum = (keys, values, isUnique) => {
if (!keys) return {};
if (values === undefined || !Array.isArray(values)) {
if (Array.isArray(keys)) {
const enumObj = {};
for (const key of keys) {
enumObj[key] = isUnique ? Symbol(key) : key;
}
return Object.freeze(enumObj);
}
if (typeof keys === 'object') {
return Object.freeze(keys);
}
throw new Error('Invalid keys');
}
if (Array.isArray(keys) && Array.isArray(values)) {
if (keys.length !== values.length) {
throw new Error('Keys and values must be the same length');
}
const enumObj = {};
for (let i = 0; i < keys.length; ++i) {
enumObj[keys[i]] = values[i];
}
return Object.freeze(enumObj);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment