ES6 read-only enums that can map value to name

前端 未结 3 634
长情又很酷
长情又很酷 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:19

    This does a pretty good job, IMHO.

    function Enum(a){
      let i = Object
        .keys(a)
        .reduce((o,k)=>(o[a[k]]=k,o),{});
    
      return Object.freeze(
        Object.keys(a).reduce(
          (o,k)=>(o[k]=a[k],o), v=>i[v]
        )
      );
    } // y u so terse?
    
    const FOO = Enum({
      a: 0,
      b: 1,
      c: "banana"
    });
    
    console.log(FOO.a, FOO.b, FOO.c);            // 0 1 banana
    console.log(FOO(0), FOO(1), FOO("banana"));  // a b c
    
    try {
      FOO.a = "nope";
    }
    catch (e){
      console.log(e);
    }
    

提交回复
热议问题