How to use destructuring assignment to define enumerations in ES6?

前端 未结 2 388
Happy的楠姐
Happy的楠姐 2021-01-11 12:43

You can use destructuring assignment to define enumerations in ES6 as follows:

var [red, green, blue] = [0, 1, 2];
         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-11 13:18

    Use a generator

    function* enumerator() {
      let i = 0;
      while (true) yield i++;
    };
    
    let [red,green,blue] = enumerator();
    console.log(red, green, blue); // 0 1 2
    
    let [a,b,c,d,e] = enumerator();
    console.log(a,b,c,d,e); // 0 1 2 3 4

    The generator is flexible making this pretty neat for implementing different types of enums – for example, these cute bitmask enums

    function* bitmask() {
      let i = 0;
      while (i < 32) yield 1 << i++;
      throw Error("bitmask enumerator exceeds 32 bits");
    }
    
    let [R,W,X] = bitmask();
    
    const read = p => (p & R) !== 0;
    const write = p => (p & W) !== 0;
    const exec = p => (p & X) !== 0;
    
    {
      let p = R | W; // read and write only
      console.log("can read?", read(p));   // true
      console.log("can write?", write(p)); // true
      console.log("can exec?", exec(p));   // false
    }
    
    {
      let p = R | X; // read and execute only
      console.log("can read?", read(p));    // true
      console.log("can write?", write(p));  // false
      console.log("can exec?", exec(p));    // true
    }

提交回复
热议问题