0.1.1 • Published 8 years ago

enum-class.js v0.1.1

Weekly downloads
3
License
MIT
Repository
github
Last release
8 years ago

enum-class.js

GitHub license Build Status

NPM

enum-class.js gives JavaScript the power of strongly-typed enums, inspired by modern C++ enum classes, Python namedtuples and Java enums, 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); // true

As such, we get maximum type safety:

console.log(Color.Red === Favorites.Red); // false

But also all the good reflection stuff:

for (let member of Color) {
  console.log(member.name); // Red, Green, Blue
  console.log(member.toString()); // Red, Green, Blue
  console.log(member.value); // undefined, because we didn't pass an object
}

And extensibility:

Color.add('Orange', 'value');

console.log(Color.length === 4); // true
console.log(Color.contains('Orange')); // true
console.log(Color.isMember(Color.Red)); // true
console.log(Color.isMember(Favorites.Google)); // false

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: