Enums in Javascript with ES6

前端 未结 15 1902
青春惊慌失措
青春惊慌失措 2020-12-12 10:42

I\'m rebuilding an old Java project in Javascript, and realized that there\'s no good way to do enums in JS.

The best I can come up with is:

const C         


        
15条回答
  •  我在风中等你
    2020-12-12 11:20

    Here is my implementation of a Java enumeration in JavaScript.

    I also included unit tests.

    const main = () => {
      mocha.setup('bdd')
      chai.should()
    
      describe('Test Color [From Array]', function() {
        let Color = new Enum('RED', 'BLUE', 'GREEN')
        
        it('Test: Color.values()', () => {
          Color.values().length.should.equal(3)
        })
    
        it('Test: Color.RED', () => {
          chai.assert.isNotNull(Color.RED)
        })
    
        it('Test: Color.BLUE', () => {
          chai.assert.isNotNull(Color.BLUE)
        })
    
        it('Test: Color.GREEN', () => {
          chai.assert.isNotNull(Color.GREEN)
        })
    
        it('Test: Color.YELLOW', () => {
          chai.assert.isUndefined(Color.YELLOW)
        })
      })
    
      describe('Test Color [From Object]', function() {
        let Color = new Enum({
          RED   : { hex: '#F00' },
          BLUE  : { hex: '#0F0' },
          GREEN : { hex: '#00F' }
        })
    
        it('Test: Color.values()', () => {
          Color.values().length.should.equal(3)
        })
    
        it('Test: Color.RED', () => {
          let red = Color.RED
          chai.assert.isNotNull(red)
          red.getHex().should.equal('#F00')
        })
    
        it('Test: Color.BLUE', () => {
          let blue = Color.BLUE
          chai.assert.isNotNull(blue)
          blue.getHex().should.equal('#0F0')
        })
    
        it('Test: Color.GREEN', () => {
          let green = Color.GREEN
          chai.assert.isNotNull(green)
          green.getHex().should.equal('#00F')
        })
    
        it('Test: Color.YELLOW', () => {
          let yellow = Color.YELLOW
          chai.assert.isUndefined(yellow)
        })
      })
    
      mocha.run()
    }
    
    class Enum {
      constructor(values) {
        this.__values = []
        let isObject = arguments.length === 1
        let args = isObject ? Object.keys(values) : [...arguments]
        args.forEach((name, index) => {
          this.__createValue(name, isObject ? values[name] : null, index)
        })
        Object.freeze(this)
      }
    
      values() {
        return this.__values
      }
    
      /* @private */
      __createValue(name, props, index) {
        let value = new Object()
        value.__defineGetter__('name', function() {
          return Symbol(name)
        })
        value.__defineGetter__('ordinal', function() {
          return index
        })
        if (props) {
          Object.keys(props).forEach(prop => {
            value.__defineGetter__(prop, function() {
              return props[prop]
            })
            value.__proto__['get' + this.__capitalize(prop)] = function() {
              return this[prop]
            }
          })
        }
        Object.defineProperty(this, name, {
          value: Object.freeze(value),
          writable: false
        })
        this.__values.push(this[name])
      }
    
      /* @private */
      __capitalize(str) {
        return str.charAt(0).toUpperCase() + str.slice(1)
      }
    }
    
    main()
    .as-console-wrapper {
      top: 0;
      max-height: 100% !important;
    }
    
    
    
    
    

提交回复
热议问题