Summary
glum is a super lightweight Enum library that makes use of Symbols to achieve type-safety.
What if my environment doesn't support ES6?
If you're in a browser, use a polyfill. If you're running in Node, chances are that Symbols are supported: they're supported in all versions after 5.12.0.
Why use Glum?
- Type-safety. When you declare an Enum, members are unique and can't be mimicked by strings, numbers, etc.
- Allows for passing in polyfills
- Don't reinvent the wheel
npm install glum
Or, if in a browser,
<script crossorigin src="https://cdn.jsdelivr.net/npm/glum"></script>
[Note: this will create a global variable called Glum]
We distribute a UMD build, so you can use it with ES modules, CommonJS, AMD, or in the browser
import Enum from 'glum'
// or var Enum = require 'glum'
let FRUIT = new Enum('APPLE', 'ORANGE', 'PEAR')
function nameFruit (fruit) {
if ((fruit = FRUIT.APPLE)) {
console.log("It's an apple")
}
}
console.log(FRUIT.getName(FRUIT.APPLE)) // APPLE
Create a new Enum.
Ex. let fruits = new Enum("APPLE", "ORANGE", "PEAR")
Ex. with polyfill let fruits = new Enum("APPLE", "ORANGE", "PEAR", function(name) {return '@@\_Symbol:' + name})
Check if a member is part of an enum. Note: this will primarily be used to accept function parameters, variables, etc. that must be a member of a certain enum. Ex.
let fruits = new Enum('APPLE', 'ORANGE', 'PEAR')
fruits.has(fruits.APPLE) // true
fruits.has(fruits.HI) // false
Get the name of an enum member. Note: this is usually used to get the name of an Enum member passed as a parameter, variable, etc. Ex.
let fruits = new Enum('APPLE', 'ORANGE', 'PEAR')
fruits.getName(fruits.APPLE) // "APPLE"
Tests can be run with npm test
. Multiple tests check that things return expected results, formatting follows guidelines, and code coverage is at the expected level.
Create an issue to add yours!
Made with ❤️ by @nebrelbug and all these wonderful contributors (emoji key):
This project follows the all-contributors specification. Contributions of any kind are welcome!