Source: app/util/lineChartUtils/trendLine.js

/**
 * Calculate a prediction based on the average difference in data points
 * http://classroom.synonym.com/calculate-trendline-2709.html
 *
 * @method trendLine
 * @param {Array<{x:number, y:number}>} points
 * @returns {number}
 */

function trendLine(points) {
  const a = points.length * points.map(({ x, y }) => x * y).reduce((p, c) => p + c, 0);
  const b =
    points.map(({ x }) => x).reduce((p, c) => p + c, 0) *
    points.map(({ y }) => y).reduce((p, c) => p + c, 0);
  // eslint-disable-next-line no-shadow
  const c = points.length * points.map(({ x }) => Math.pow(x, 2)).reduce((p, c) => p + c, 0);
  const d = Math.pow(
    // eslint-disable-next-line no-shadow
    points.map(({ x }) => x).reduce((p, c) => p + c, 0),
    2,
  );
  return (a - b) / (c - d);
}

export default trendLine;