/**
* @param {number[]} code
* @param {number} k
* @return {number[]}
*/
var decrypt = function (code, k) {
return code.map((value, index) => {
let leftIndex, rightIndex;
if (k > 0) {
leftIndex = index + 1;
rightIndex = index + 1 + k;
} else if (k < 0) {
leftIndex = index + k;
rightIndex = index;
} else {
leftIndex = rightIndex = index;
}
return sum(code, leftIndex, rightIndex);
})
};
// 计算array在区间[leftIndex, rightIndex)的和
function sum(array, leftIndex, rightIndex) {
const { length } = array;
let count = rightIndex - leftIndex,
sum = 0;
while (count-- > 0) {
leftIndex = (leftIndex + length) % length;
sum += array[leftIndex];
leftIndex++;
}
return sum;
}