Mariano Molina
Mariano Molina

Reputation: 190

Variables changing in Loop

I have this loop which calls for some info from an API, and then loops through it to add it to a simple array.

Promise.all(promisses.map(o => API.functionName(o))).then((p) => {
    var i = startingDate;
    p.forEach(res =>{
        res.forEach(function(value) {
            rankExport.push({
                "teamName" : value.team.name,
                "teamId": value.team.id,
                "position" : value.place,
                "points" : value.points,
                "posChange" : value.change,
                "rankDay" : i.getDate(),
                "rankMonth" : i.getMonth() + 1,
                "rankYear" : i.getFullYear(),
                "date" : i,
            });
        });
        i = add_weeks(i,1)
    });
    saveRankings(rankExport, i);
})

This is the add_weeks function:

function add_weeks(date, n)  {
    return new Date(date.setDate(date.getDate() + (n * 7)));      
};

One of the key datapoints is the date, which I'm saving in the array as a day, month, year and complete date.

Problem is, this is the outcome I'm getting:

[
  {
    teamName: 'Team',
    teamId: 6665,
    position: 1,
    points: 1000,
    posChange: 0,
    rankDay: 27,
    rankMonth: 1,
    rankYear: 2020,
    date: 2020-02-03T03:00:00.000Z
  },

There are immediately two problems:

1- There are two different dates: 27/01/2020 and 03/02/2020 which are a week apart. But why? They are coming from the same variable (i).

2- The dates are shifted a week (should be startingDate = 20/01/2020), which is confusing given that my add_weeks formula should be performed after the loops since they aren't asynchronous, right?

Help! Thanks =)

Upvotes: 0

Views: 56

Answers (1)

Jason Goemaat
Jason Goemaat

Reputation: 29194

I assume the problem is in your add_weeks() function which isn't shown. If you call something like setYear() on your date object it will modify the date in place. I'm betting your add_weeks() function doesn't properly copy the date. See this code:

var i = new Date();
var a = {date: i};
i = new Date();
var b = {date: i};
i.setYear(1999);
var c = {date: i};
console.log(JSON.stringify({ a, b, c }, null, 2));

Result is b also shows 1999 because setYear() modified the date:

{
  "a": {
    "date": "2020-09-03T20:34:18.284Z"
  },
  "b": {
    "date": "1999-09-03T20:34:18.284Z"
  },
  "c": {
    "date": "1999-09-03T20:34:18.284Z"
  }
}

To fix that, in your add_weeks() function create a new date, ala:

var dt = new Date();
var newDate = new Date(dt.getTime());
newDate.setYear(1999);
console.log(dt, newDate);
-- shows different dates

Upvotes: 3

Related Questions