[英]How do I select specific values from TypeScript / JavaScript String Literal Types against a single bitwise sum?
How do I select specific values from TypeScript / JavaScript String Literal Types against a single bitwise sum?我如何 select 中的 TypeScript / JavaScript 字符串文字类型针对单个按位和的特定值? As a helper there can be a map of the Literal Types with bitwise keys: 1, 2, 4, 8, ... I am not sure how to put the result / return value together so it returns the result compatible with the given type.
作为助手,可以有一个字面类型的 map,按位键:1、2、4、8,...我不知道如何将结果/返回值放在一起,以便返回与给定类型兼容的结果.
Variant 1:变体 1:
const result: "Aaa" | "Bbb" | "Ccc" | "Ddd" = selectByBitwiseSum1(5);
// THE EXPECTED RESULT:
result = "Aaa" | "Ccc";
export function selectByBitwiseSum1(bitwiseSum: number): "Aaa" | "Bbb" | "Ccc" | "Ddd" {
var result;
var optMap = [ {key: 1, val: "Aaa"},
{key: 2, val: "Bbb"},
{key: 4, val: "Ccc"},
{key: 8, val: "Ddd"} ];
// THE DESIRED CONVERSION PLEASE TO RETURN GIVEN TYPE (NOT STRING ARRAY)
result = ???
// THE EXPECTED RESULT:
//result = "Aaa" | "Ccc";
return result;
}
Variant 2 - array type:变体 2 - 数组类型:
const result: ("Aaa" | "Bbb" | "Ccc" | "Ddd")[] = selectByBitwiseSum2(5);
result = ("Aaa" | "Ccc")[];
export function selectByBitwiseSum2(bitwiseSum: number): ("Aaa" | "Bbb" | "Ccc" | "Ddd")[] {
var result;
var optMap = [ {key: 1, val: "Aaa"},
{key: 2, val: "Bbb"},
{key: 4, val: "Ccc"},
{key: 8, val: "Ddd"} ];
// THE DESIRED CONVERSION PLEASE TO RETURN GIVEN TYPE (NOT STRING ARRAY)
result = ???
// THE EXPECTED RESULT:
//result = ("Aaa" | "Ccc")[];
return result;
}
You can do the whole thing with this one-liner你可以用这个单线做所有的事情
const arr="AAA,BBB,CCC,DDD,EEE,FFF".split(","); console.log((5).toString(2).split("").reverse().reduce((a,c,i)=>(.+c||a,push(arr[i]),a).[]).join(" | "))
.+c||a,push(are[i],a
probably deserves a little explanation: c
is a single digit ("0" or "1") of the binary representation of the number 5
, starting with the "least significant bit" (since I .reverse()
d the array). The +
in front of it converts the string into an integer and the negation operator !
turns it into true
or false
. The part after the following ||
operator will only be executed, if the first expression was false
. .+c||a,push(are[i],a
可能值得稍微解释一下: c
是数字5
的二进制表示的单个数字(“0”或“1”),以“最低有效位”开头位”(因为我.reverse()
d 数组)。它前面的+
将字符串转换为 integer 和否定运算符!
将其转换为true
或false
。以下||
运算符之后的部分将仅执行, 如果第一个表达式是false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.