且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ES6只读枚举可以将值映射到名称

更新时间:2023-09-11 10:37:16

我将使用地图,以便您的枚举值可以是任何类型,而不是将其强制为字符串。

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]);

以确保枚举值正确使用。只使用一个字符串,你不能保证一些代码没有简单地传递一个正常的字符串,恰好与一个枚举值相同。如果您的值始终是字符串或符号,您还可以将Map简单地替换为简单对象。

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.