Created
March 13, 2018 05:41
-
-
Save Baozi2/c33a4f0d8eb1edc1d360b9c005e526ee to your computer and use it in GitHub Desktop.
给定数组 和 间距 计算 平均值得算法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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