ES6 read-only enums that can map value to name

前端 未结 3 639
长情又很酷
长情又很酷 2021-02-07 07:55

I would like to define an enum-like structure in JS, but have two requirements:

  1. The values be read-only, i.e. no users can assign to them.
  2. The values (0, 1
3条回答
  •  庸人自扰
    2021-02-07 08:28

    I'd use a Map so that your enum values can be any type, rather than having them coerced into strings.

    function Enum(obj){
        const keysByValue = new Map();
        const EnumLookup = value => keysByValue.get(value);
    
        for (const key of Object.keys(obj)){
            EnumLookup[key] = obj[key];
            keysByValue.set(EnumLookup[key], key);
        }
    
        // Return a function with all your enum properties attached.
        // Calling the function with the value will return the key.
        return Object.freeze(EnumLookup);
    }
    

    If your enum is all strings, I'd also probably change one line to:

    EnumLookup[key] = Symbol(obj[key]);
    

    to ensure that the enum values are being used properly. Using just a string, you have no guarantee that some code hasn't simply passed a normal string that happens to be the same as one of your enum values. If your values are always strings or symbols, you could also swap out the Map for a simple object.

提交回复
热议问题