Skip to content

Instantly share code, notes, and snippets.

@Baozi2
Created March 13, 2018 05:41
Show Gist options
  • Save Baozi2/c33a4f0d8eb1edc1d360b9c005e526ee to your computer and use it in GitHub Desktop.
Save Baozi2/c33a4f0d8eb1edc1d360b9c005e526ee to your computer and use it in GitHub Desktop.
给定数组 和 间距 计算 平均值得算法
function calAVG(array, interval){
if(!(Array.isArray(array))) throw '参数异常'
for(let ele of array){
if(isNaN(parseFloat(ele))){
throw '数组中有不能转换为数字的元素'
}
}
const result = [],
INTERVAL = interval || 1,
reducer = (accumulator, currentValue) => accumulator + currentValue;
let arrayLength = array.length;
if(arrayLength <= interval){
console.info(array.reduce(reducer))
result.push(array.reduce(reducer)/arrayLength);
return result;
}
for(let[index, value] of array.entries()){
let endIndex = index + INTERVAL,
currentArray = array.slice(index, endIndex + 1);
if(endIndex >= arrayLength){
result.push(currentArray.reduce(reducer)/(currentArray.length))
break;
}
result.push(currentArray.reduce(reducer)/(INTERVAL + 1));
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment