alp123
alp123

Reputation: 189

Javascript runtime optimizing array modifications

I have a problem optimizing the runtime for my code. Ideally, what I'm trying to achieve is that all the operations below is performed in a single loop, so that I don't have to run through the dataset many times as I'm doing now (very large dataset!)

The code is transforming aggData to an array on the following format: [0: 0, 1: 0, 2: 0, 3: 43, 4: 121, 5: 0, ....], where each number represents a year in the interval, if the interval is (1800-2020) 0 will represent the count for 1800, 1 will be 1801 and so on ..

aggData is an array of objects on the following format: {key_as_string: "1900-01-01T00:00:00.000Z", key: -2208988800000, doc_count: 17}. The start-year is the first year with a doc_count higher than 0.

Below I provide a description of what each step does as the code is now:

Here I am changing the format of each object in the list to be : {year: number, count: number}

 const formatAggData = aggData
        .map((item: AggData) => {
            return { year: moment(item.key_as_string).year(), count: item.doc_count };
        });

This function creates an array of objects with the from as start year and to as end year, if the year already exists in existingArray it uses the count from there, if not it sets count to 0.

    function fillYears(from: number, to: number, existingArray: YearCount[]) {
        const existingObject: { [year: string]: number } = { year: null };
        existingArray.map((x: YearCount) => (existingObject[x.year] = x.count));

        const yearsArray = [];
        for (let i = from; i <= to; i++) {
            yearsArray.push({
                year: i,
                count: existingObject[i] || 0,
            });
        }

        return yearsArray;
    }

Converts year values to count-values, where the first year in the list will be 0 with the corresponding value, second will be 1 with corresponding value and so on..

    const resultList = fillYears(min, max, formatAggData).map(
        (item: YearCount) => item.count,
    );

Upvotes: 0

Views: 38

Answers (1)

paco
paco

Reputation: 106

I was looking at you code. can't you do it like this? it looks like you don't need to know the year at this moment

function fillYears(from: number, to:number, existingYears: YearCount[]) {
    for (let i = from; i <= to; i++) {
      yearsArray.push({
          year: i,
          count: existingYears[i].doc_count || 0,
      });
  }
}

Upvotes: 1

Related Questions