A short review;
- You use
var
for the function, I would useconst
, actually I would just usefunction
;) - I would use a n inline function that can process a window, otherwise it's hard to tell that you implemented a sliding window
- I would avoid the word
array
in variable names, unless they are an array - You never declare
current
, making it a global
Counter-proposal;
function sumSubArrays(list, k){
const sumWindow = (list) => list.reduce((a, b) => a + b, 0);
let sum = 0;
for(let i = 0; i <= list.length-k; i++){
sum += sumWindow( list.slice(i, i + k) );
}
return sum;
}
let arr = [1,2,3,4,5]
let k = 3;
console.log(27, 27 === sumSubArrays(arr, k));