An implementation of python-like enums in JavaScript.
npm install python-enumThis is the repository for the python-enum npm package. This package was created as a tool to facilitate the migration of projects written in python to javascript. As such, it serves the usecase of providing a python-like api (functional-api) to enum objects in javascript, including the int-enum.
The following code examples demonstrate the JavaScript analogs of the Python enum module.
Python:
``
import enum as Enum
Animal = Enum.Enum('Animal', 'ANT BEE CAT DOG')
print(Animal)
IntAnimal = Enum.IntEnum('IntAnimal','ANT BEE CAT DOG')
list(IntAnimal)
JavaScript:
`
import Enum from 'python-enum'const Animal = Enum.Enum('Animal', 'ANT BEE CAT DOG')
console.log(Animal)
// ƒ [object Function]
console.log(Animal.ANT)
// Animal {val: 1, key: "ANT"}
console.log(Animal.ANT.value)
// 1
Animal.toArray()
// (4) [Animal, Animal, Animal, Animal]
const IntAnimal = Enum.IntEnum('IntAnimal','ANT BEE CAT DOG')
IntAnimal.toArray()
// (4) [IntAnimal, IntAnimal, IntAnimal, IntAnimal]
console.log(IntAnimal.ANT.value)
// 1
IntAnimal.ANT + 1
// 2
IntAnimal.ANT.CAT === IntAnimal.CAT
// true
`Note: IntEnum values behave like integers in other ways you’d expect.
Derived Enumerations
$3
The first variation of Enum that is provided is also a subclass of int. Members of an IntEnum can be compared to integers; by extension, integer enumerations of different types can also be compared to each other:Python
`
from enum import IntEnum
class Shape(IntEnum):
CIRCLE = 1
SQUARE = 2
class Request(IntEnum):
POST = 1
GET = 2Shape == 1
False
Shape.CIRCLE == 1
True
Shape.CIRCLE == Request.POST
True
`JavaScript
`
import IntEnum from 'python-enum'const Shape = IntEnum('Shape', {
CIRCLE: 1,
SQUARE: 2,
})
const Request = IntEnum('Request', {
POST: 1,
GET: 2,
})
Shape === 1
// false
Shape.CIRCLE === 1
// True
Shape.CIRCLE === Request.POST
// True
`$3
You can check class type like so:
Python
`
foo = new Enum.Enum('foo', { 'a': 1 })
print(isinstance(foo, Enum.EnumMeta))
True
`JavaScript
`
const foo = new Enum.Enum('foo', { a: 1 })
console.log(foo instanceof Enum.EnumMeta)
// true
`Supported
_sunder_ names*
_missing_ – a lookup function used when a value is not found; may be overriddenJavaScript
`
const foo = Enum.IntEnum('foo', {
_missing_: function _missing_() { return 10 },
a: 1,
b: 2,
c: 3,
})
``As of right now (3/17/2020) I will only be implementing the necessary Python enum module features for my own use. If you need additional enum features to be ported over from python you can make an issue or make a pull request.
For other feeback not strictly related to bugs or feature requests you can leave a comment here