我不能把那段代码从Java脚本转换成打字脚本.
问题是转换...扩散运算符.
function calculateCombinations(first, next, ...rest) {
if (rest.length) {
next = calculateCombinations(next, ...rest);
}
return first.flatMap(a => next.map(b => [a, b].flat()));
}
a1 = ['A', 'B']
a2 = ['+', '-']
a3 = ['1', '2']
a4 = ['X', 'Y', 'Z']
// Show possibile combinations
calculateCombinations(a1, a2, a3, a4); // give me an array of 24 combinations
Attempt 至 conversion 至 TS:个
function calculateCombinationsTS(first: any[], next: any[], ...rest: any[]) {
if (rest.length) {
next = calculateCombinationsTS(next, ...rest);
}
return first.flatMap(a => next.map(b => [a, b].flat()));
}
TS2556: A spread argument must either have a tuple type or be passed 至 a rest parameter.个
如果我改变了
next = calculateCombinationsTS(next, ...rest);
至
next = calculateCombinationsTS(next, rest);
该函数给出了一个错误结果,因为REST是作为数组的数组传递的,而不是参数列表
Example of output:个
nCombo = (a1 * a2 * a3 * a4) = 24 possibilities
[
[ 'A', '+', '1', 'X' ], [ 'A', '+', '1', 'Y' ],
[ 'A', '+', '1', 'Z' ], [ 'A', '+', '2', 'X' ],
[ 'A', '+', '2', 'Y' ], [ 'A', '+', '2', 'Z' ],
[ 'A', '-', '1', 'X' ], [ 'A', '-', '1', 'Y' ],
[ 'A', '-', '1', 'Z' ], [ 'A', '-', '2', 'X' ],
[ 'A', '-', '2', 'Y' ], [ 'A', '-', '2', 'Z' ],
[ 'B', '+', '1', 'X' ], [ 'B', '+', '1', 'Y' ],
[ 'B', '+', '1', 'Z' ], [ 'B', '+', '2', 'X' ],
[ 'B', '+', '2', 'Y' ], [ 'B', '+', '2', 'Z' ],
[ 'B', '-', '1', 'X' ], [ 'B', '-', '1', 'Y' ],
[ 'B', '-', '1', 'Z' ], [ 'B', '-', '2', 'X' ],
[ 'B', '-', '2', 'Y' ], [ 'B', '-', '2', 'Z' ]
]