Skip to content

Instantly share code, notes, and snippets.

@3assy2018
Last active July 5, 2020 12:36
Show Gist options
  • Save 3assy2018/e9a2b38a4b9bc93fd07e64c60672014b to your computer and use it in GitHub Desktop.
Save 3assy2018/e9a2b38a4b9bc93fd07e64c60672014b to your computer and use it in GitHub Desktop.
This function calculates change percentage between 2 pairs of values and accumulates the average and the last iterated value as previous value in the next iteration.
calculateAccumulativeAverageChangePercentage(set, initial) {
let deltaObj = set.reduce((total, currentValue) => {
let currentChange = (currentValue - total.prevValue) / Math.abs(total.prevValue);
let averageMode = total.change != 0 ? 2 : 1;
return {
change: (currentChange + total.change) / (averageMode),
prevValue: currentValue
};
}, {change: 0, prevValue: initial});
deltaObj.change = Math.abs(deltaObj.change) * 100;
return deltaObj;
}
@ahmedelgabri
Copy link

calculateAccumulativeAverageChangePercentage(set, initial) {
        return set.reduce((total, currentValue) => {
            let currentChange = (currentValue - total.prevValue) / Math.abs(total.prevValue);
            let averageMode = total.change != 0 ? 2 : 1;

            Object.assign(total,  {
                change: Math.abs((currentChange + total.change) / averageMode) * 100 ,
                prevValue: currentValue
            });

            return total;
        }, {change: 0, prevValue: initial});
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment