I've been working on a function that generates an array of ten Innings (objects with beginning and end times) through a loop. For example.
- The Game starts Monday at 12:00 AM, and ends Saturday at 12:00AM
- The Game is comprised of 10 12-hour Innings
- Inning 1 starts Monday at 12:00 AM and ends 12:00PM the same day, when Inning 2 begins.
You get the idea. Times are kept with Moment.js.
I've written the code that I expected to handle this, but the functionality is broken. See my function logic notes at bottom. Here is a JSFiddle demonstrating the code and results, and here is the function:
//Define the Game's Time Frame
var Game = new Object(); // Object that holds all game data
var end = { // what time does the game end?
"moment": moment().days(6).hour(0).minute(0).second(0)
};
var beginning = { // what time does the game start?
"moment": moment().days(1).hour(0).minute(0).second(0)
};
// I'm going to over-do the commenting here for debugging:
// assign start and end times to each of 10 innings
function generateInnings() {
// create an inning object to assign start and end to
var inning = new Object();
// create array to assign each of 10 inning objects to
Game.innings = new Array();
// shortcut for calculating game time span
var gameHours = 120;
// ten innings in a game. how many hours each?
var inningHours = gameHours / 10;
// for 10 intervals of x, generate each inning
for (x = 0; x < 10; x++) {
//inning starts when?
inning.start = beginning.moment.add("hours", (inningHours * x));
// inning ends when?
inning.end = inning.start.add("hours", inningHours);
// attach inning object to Game.innings array
Game.innings[x] = inning;
// JSFiddle Output
log("Inning " + x + " Starts: " + inning.start.calendar());
// JSFiddle Output
log("Inning " + x + " Ends: " + inning.end.calendar());
}
}
generateInnings();
Result:
- Inning 0 Starts: Last Monday at 12:00 PM
- Inning 0 Ends: Last Monday at 12:00 PM
- Inning 1 Starts: Last Tuesday at 12:00 PM
- Inning 1 Ends: Last Tuesday at 12:00 PM
- Inning 2 Starts: Last Thursday at 12:00 AM
- Inning 2 Ends: Last Thursday at 12:00 AM
- ... need we go further?
What's causing this (very) incorrect output?
Function logic (this is not code, but notes):
beginning = 12:00AM Mon
for (x=0;x<10;x++){ //do this x10
start = beginning plus (12hrs * current loop interval)
console.log("Inning" + current loop interval + " start: " + start);
}
for x = 0, start = beginning + (12 * 0) hours // = still Monday 12:00 AM
for x = 1, start = beginning + (12 * 1) hours // = Monday 12:00 PM
for x = 2, start = beginning + (12 * 2) hours // = Tuesday 12:00 AM
I thought I had built a pretty solid, fundamental function. I just can't see an issue in the logic, it must be the Moment syntax.