As the data for a date/temperature scatter-plot, I wanted to be able to key the data with a date-like string, and the following is the structure I devised:
var dateTemperatures = {
'[2016,8,29]': {low: 63, high: 94},
'[2016,9,2]': {low: 59, high: 81},
'[2016,9,1]': {low: 58, high: 85}
}
The idea being that I could call JSON.parse on the keys, and have the arguments necessary to create a date. Then I found this Stackoverflow answer as to how to create an object, using a combination of both apply
and new .... ()
, and in particular used the following substituting Something
with Date
:
var s = new (Function.prototype.bind.apply(Something, [null, a, b, c]));
And it works like a charm, for instance in the following function I devised for ordering the "Date" keys:
function orderTemperatureDates(dateTemperatures) {
var orderedDates = [];
for (var temperatureDate in dateTemperatures) {
var YMD = JSON.parse(temperatureDate);
YMD.unshift(null); //standard first argument to .apply()
orderedDates.push(new (Function.prototype.bind.apply(Date, YMD)));
}
return orderedDates.sort(function(a,b){return a.getTime() - b.getTime()});
}
CONSOLE/LOG/OUTPUT:
[Thu Sep 29 2016 00:00:00 GMT-0500 (Central Daylight Time), Sat Oct 01 2016 00:00:00 GMT-0500 (Central Daylight Time), Sun Oct 02 2016 00:00:00 GMT-0500 (Central Daylight Time)]
Going back to the example line from the referenced Stackoverflow answer though, how does this work? Because my understanding, per documentation here, is that null
can be the first argument to apply
followed by the remaining arguments, but in the example and in my code, null and all of the remaining arguments are part of one and the same array.