Last active
August 9, 2022 17:15
-
-
Save ahamed/95a93a7535201d1966eca88ddfe9aa46 to your computer and use it in GitHub Desktop.
Create a JavaScript representation of "Enum".
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* β 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