Reputation: 30
0:{entry_counts: 2000, week_end_date: "2016-09-01"} 1:{entry_counts: 10000, week_end_date: "2016-09-08"} 2:{entry_counts: 20000, week_end_date: "2016-09-22"} 3:{entry_counts: 40000, week_end_date: "2016-09-29"} 4:{entry_counts: 150000, week_end_date: "2016-10-13"}
Upvotes: 0
Views: 56
Reputation: 1434
Since your dates don't contain any sort of timezone or even time data it will be treated as UTC timezone. We don't really need moment to help us out on this one.
You are also using very long references in your code which make it harder to read and more prone to errors. (for example: data.entryDetails[0].entry_counts[count].entry_counts;
)
I would suggest cutting this down using some variables. This also make it easier to check if the value is valid or even defined.
When working with time and incrementing time, valueOf is very useful. I wrote a quick script for you. I'm sure it can be improved with some error checking and making sure the data is defined. Other than this it should be useful for you!
Happy holidays!
var countData = [ {entry_counts: 2000, week_end_date: "2016-09-01"},{entry_counts: 10000, week_end_date: "2016-09-08"},{entry_counts: 20000, week_end_date: "2016-09-22"},{entry_counts: 40000, week_end_date: "2016-09-29"},{entry_counts: 150000, week_end_date: "2016-10-13"} ]
var today = ( new Date() ).valueOf()
var currentEntry = parseEntry( countData.shift() )
var nextEntry = parseEntry( countData.length ? countData.shift() : null )
var viewsArray = []
var datesArray = []
var time = currentEntry.dateValue
while( time <= today ){
// update currentEntry data used to the most up-to-date data we have
if( nextEntry && time > nextEntry.dateValue ) {
while( nextEntry && time > nextEntry.dateValue ){
currentEntry = nextEntry
nextEntry = parseEntry( countData.length ? countData.shift() : null )
}
}
viewsArray.push( currentEntry.views )
datesArray.push( new Date( time ) )
time += daysInMilliseconds(7)
}
console.log( viewsArray )
function parseEntry( entry ) {
if( !entry ) return null
entry.date = new Date( entry.week_end_date )
entry.dateValue = entry.date.valueOf()
entry.views = entry.entry_counts
return entry
}
function daysInMilliseconds( days ) {
return days * 24 * 60 * 60 * 1000
}
Upvotes: 1