Skip to content

Instantly share code, notes, and snippets.

@ahamed
Last active August 9, 2022 17:15
Show Gist options
  • Save ahamed/95a93a7535201d1966eca88ddfe9aa46 to your computer and use it in GitHub Desktop.
Save ahamed/95a93a7535201d1966eca88ddfe9aa46 to your computer and use it in GitHub Desktop.
Create a JavaScript representation of "Enum".
/**
* βœ… Function for creating an `enum` representation in JavaScript.
*
* This function will receive a plain object
* [key: string]: number | string | boolean.
* You've created the enum with a valid object and it will return you a
* Proxy. You are not able to extend the proxy anymore.
*
* @author πŸ“© Sajeeb Ahamed <[email protected]>
*
*/
export const createEnum = (structure) => {
if (structure === null || typeof structure !== 'object' || Array.isArray(structure)) {
throw Error(`'${structure}' is not a valid enum structure.`);
}
for (const key in structure) {
if (!['number', 'string', 'boolean'].includes(typeof structure[key])) {
throw Error(
`You are only allowed to use 'number', 'string' or 'boolean' types, but you are using '${JSON.stringify(
structure[key]
)}'`
);
}
}
return new Proxy(structure, {
set(target, prop) {
if (Reflect.has(target, prop)) {
throw Error(`Cannot assign to '${prop}' because it is a read-only property.`);
} else {
throw Error(`Property '${prop}' does not exist on the enum structure.`);
}
},
get(target, prop) {
return Reflect.get(target, prop);
},
});
};
//------------------------------------------ Create an Enum --------------------------------------------------------
/**
* πŸŽ‰ Use the createEnum function. Here the Status is a non-extendable enum Proxy.
* πŸ”– You are not able to change any property of add a new property.
*/
const Status = createEnum({
PENDING: 'pending',
ACCEPTED: 'accepted',
REJECTED: 'rejected',
});
// ❌ Invalid assignment
Status.PENDING = 'loading'; //Error: Cannot assign to 'PENDING' because it is a read-only property.
Status.NEW_VALUE = 'new-value'; //Error: Property 'NEW_VALUE' does not exist on the enum structure.
const user = {
id: '3423',
name: 'John Doe',
email: '[email protected]',
status: Status.PENDING,
};
// βœ… The condition is true
if (user.status === Status.PENDING) {
console.log('Pending user');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment