我有一个常量数组,像这样:
const pie_values = [20,10,5,5,10];
挑战在于根据整数输入来转换上述数组。
(5) => [5, 15, 10, 5, 5, 10]
(21) => [20, 1, 9, 5, 5, 10]
(31) => [20, 10, 1, 4, 5, 10]
输入5将从pie_values的第一个索引中取出5。但它仍然剩下15。
输入21可以从索引0中取20,从索引2中取1,剩余9个
我想你能看到这是怎么回事。所以(0)和(50)将返回原始的pie_values。
现在的挑战是创建一个函数,在几行代码上进行循环构建,而不是基于5个if语句。如果pie_values被扩展,该函数仍应正常工作。
我有一个使用if语句的方法,但后者是不可行的。对于这种类型的问题,有什么好的方法?
首先,我定义了一个辅助函数:
//Returns summation of pie value
// totalPieValues(1) = 20
// totalPieValues(2) = 30
// totalPieValues(3) = 35
// totalPieValues(4) = 40
// totalPieValues(5) = 50
function totalPieValues(max) {
let result = 0;
for (let i = 0; i < max; i++) {
result += PIE_VALUES[i];
}
return result;
}
然后我开始编写函数getPieArray,利用了这个辅助函数。但是我现在遇到了困难。
function getPieArray(wp) {
for (let i = 0; i < PIE_VALUES.length; i++) {
if (wp == 0 || wp == totalPieValues(i)) {
return PIE_VALUES;
}
}
let result = [];
for (let i = 1; i <= PIE_VALUES.length; i++) {
if (wp > totalPieValues(PIE_VALUES.length - i)) {
result.push(PIE_VALUES[i]);
} else if () {
result.push(wp - totalPieValues(3));
} else {
result.push(PIE_VALUES[i] - (value - totalPieValues(3)));
}
}
return result;
}
我已经编写并且可用的代码如下:
//Returns array of exact values needed to show in pie chart
export function getPieValues(wp) {
//1 => [1, 19, 10, 5, 5, 10]
//24 => [20, 4, 1, 5, 5, 10]
//31 => [20, 10, 1, 5, 5, 5, 10]
let result;
if (wp == 0) {
result = PIE_VALUES;
} else if (wp < totalPieValues(1)) {
result = [wp - totalPieValues(0), PIE_VALUES[0] - wp, PIE_VALUES[1], PIE_VALUES[2], PIE_VALUES[3], PIE_VALUES[4]];
} else if (wp == totalPieValues(1)) {
result = PIE_VALUES;
} else if (wp < totalPieValues(2)) {
result = [PIE_VALUES[0], wp - totalPieValues(1), PIE_VALUES[1] - (wp - PIE_VALUES[0]), PIE_VALUES[2], PIE_VALUES[3], PIE_VALUES[4]];
} else if (wp == totalPieValues(2)) {
result = PIE_VALUES;
} else if (wp < totalPieValues(3)) {
result = [PIE_VALUES[0], PIE_VALUES[1], wp - totalPieValues(2), PIE_VALUES[2] - (wp - totalPieValues(2)), PIE_VALUES[3], PIE_VALUES[4]];
} else if (wp == totalPieValues(3)) {
result = PIE_VALUES;
} else if (wp < totalPieValues(4)) {
result = [PIE_VALUES[0], PIE_VALUES[1], PIE_VALUES[2], wp - totalPieValues(3), PIE_VALUES[3] - (wp - totalPieValues(3)), PIE_VALUES[4]];
} else if (wp == totalPieValues(4)) {
result = PIE_VALUES;
} else if (wp < totalPieValues(5)) {
result = [PIE_VALUES[0], PIE_VALUES[1], PIE_VALUES[2], PIE_VALUES[3], wp - totalPieValues(4), PIE_VALUES[4] - (wp - totalPieValues(4))];
} else if (wp == totalPieValues(5)) {
result = PIE_VALUES;
}
return result;
}