如何使用解析赋值来定义ES6中的枚举? [英] How to use destructuring assignment to define enumerations in ES6?
问题描述
您可以使用解构赋值来定义ES6中的枚举,如下所示:
var [red ,绿色,蓝色] = [0,1,2];
相反,我希望解构任务的右侧是动态的。例如:
var MAX_ENUM_SIZE = 32;
var ENUM = new Array(MAX_ENUM_SIZE); (var i = 0; i ENUM [i] = i;
var [red,green,blue] = ENUM;
不幸的是,这似乎是一个黑客。如果我想在未来更大的枚举呢?因此,我正在考虑使用迭代器使用解构赋值,如下所示:
var [red,绿色,蓝色] =枚举(/ *我不想指定大小* /);
但是,我不认为可以使用迭代器使用解析赋值[需要引用] ] 。有没有办法完成这个目标?
使用生成器
function * enumerator(){let i = 0; while(true)yield i ++;}; let [red,green,blue] =枚举器(); console.log(红,绿,蓝); // 0 1 2let [a,b,c,d,e] =枚举器(); console.log(a,b,c,d,e); // 0 1 2 3 4
非常漂亮的实现不同类型的枚举 - 例如,这些可爱的位掩码枚举
function * bitmask(){i = 0;而(i <32)产生1 <我++; throw(bitmask枚举器超过32位);} 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 |瓦; //读写只有console.log(可以读?,read(p)); // true console.log(can write?,write(p)); // true console.log(can exec?,exec(p)); // false} {let p = R | X; //只读和执行console.log(可以读?,read(p)); // true console.log(can write?,write(p)); // false console.log(can exec?,exec(p)); // true}
You can use destructuring assignment to define enumerations in ES6 as follows:
var [red, green, blue] = [0, 1, 2];
Instead, I'd like the right hand side of the destructuring assignment to be dynamic. For example:
var MAX_ENUM_SIZE = 32;
var ENUM = new Array(MAX_ENUM_SIZE);
for (var i = 0; i < MAX_ENUM_SIZE; i++) ENUM[i] = i;
var [red, green, blue] = ENUM;
Unfortunately, this seems like a hack. What if I want a bigger enumeration in the future? Hence, I was thinking of using destructuring assignment with an iterator as follows:
var [red, green, blue] = enumeration(/* I don't want to specify size */);
However, I don't think it's possible to use destructuring assignment with iterators[citation needed]. Is there any way to accomplish this goal?
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() {
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
}
这篇关于如何使用解析赋值来定义ES6中的枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!