Caculate trendline datapoints in TypeScript

If you want to calculate trendline datapoints in TypeScript, you can use the following code:

 

 

 

Code

 

module helpers.math {
'use strict';
/**
 * Based off: https://github.com/Tom-Alexander/regression-js/blob/master/src/regression.js
 * @param known_y - Array of numbers representing the y-axis values, [1, 2, ...].
 * @param known_x - Optional array of numbers representing the x-axis values, when not supplied this parameter will be [1,2,..."y-axis values total count"].
 */

export function trend(known_y: Array<number>, known_x?: Array<number>): Array<number> {

const ylength = known_y.length;

// When "x-axis values" are not supplied, generate it as [1,2,..."y-axis values total count"].

if (!known_x) {
     known_x = [];

for (let xcounter = 0; xcounter < ylength; xcounter++) {
        known_x.push(xcounter + 1);
     }
 }

// The "data" should be in the format [[x[0], y[0]], [x[1], y[1]]], ...].

const data = [];

for (let ycounter = 0; ycounter < ylength; ycounter++) {
     data.push([known_x[ycounter], known_y[ycounter]]);
 }

let n = 0;

const results = [];
const sum = [0, 0, 0, 0, 0];
for (; n < data.length; n++) {
if (data[n][1] != null) {
         sum[0] += data[n][0];
         sum[1] += data[n][1];
         sum[2] += data[n][0] * data[n][0];
         sum[3] += data[n][0] * data[n][1];
         sum[4] += data[n][1] * data[n][1];
     }
 }

const gradient = (n * sum[3] - sum[0] * sum[1]) / (n * sum[2] - sum[0] * sum[0]);
const intercept = (sum[1] / n) - (gradient * sum[0]) / n;
for (let i = 0, len = data.length; i < len; i++) {
const trendY = data[i][0] * gradient + intercept;
     results.push(trendY);
 }

return results;
 }
}

 

 

 

Unit Test

 

const trend = helpers.math.trend;
'use strict';
describe('zvdz.helpers.calculate.trend', function () {
 it('given an array of points it should return an array of points representing the trendline of the given points.', function () {
    const known_y = [1,2,3,4,5,6];
     expect(trend(known_y)).toEqual([1, 2, 3, 4, 5, 6]);
 });
});

Leave a Reply

Your email address will not be published. Required fields are marked *