enum-class.js
enum-class.js
gives JavaScript the power of strongly-typed enums, inspired by modern C++ enum class
es, Python namedtuples
and Java enum
s, with dynamic JavaScript sugar sprinkled on top.
Usage
Similar to the flexibility of the namedtuple
constructor in Python, you can pass the members as ['A', 'B', 'C']
, 'A, B, C'
or 'A B C'
:
const Color = EnumClass('Color', 'Red, Green, Blue');
const Food = EnumClass('Food', 'Ham Spam');
But also optionally associate values with the enum members:
const Favorites = EnumClass('Food', {
Red: function() { console.log('Every member has a value!'); },
Spaghetti: [1, 2, 3],
Google: "I'm immutable after configuration."
});
The special thing is that members of enum classes are ... instances of themselves :scream:
console.log(Color.Red instanceof Color);
As such, we get maximum type safety:
console.log(Color.Red === Favorites.Red);
But also all the good reflection stuff:
for (let member of Color) {
console.log(member.name);
console.log(member.toString());
console.log(member.value);
}
And extensibility:
Color.add('Orange', 'value');
console.log(Color.length === 4);
console.log(Color.contains('Orange'));
console.log(Color.isMember(Color.Red));
console.log(Color.isMember(Favorites.Google));
Installing
$ npm install enum-class.js
Hacketry
Tests with ava, docs with ESDoc, transpilation with Babel and compilation/compression with Closure. Easy life, smiles and champagne with:
$ gulp
The source is small and modern, so feel free to hack around.
License
This project is released under the MIT License. For more information, see the LICENSE file.
Warning
This is my first ever JavaScript/Node project, so I have absolutely no idea what the hell I'm doing.
Authors
Peter Goldsborough + cat :heart: