This post is more than 2 years old.
Forgive the title, I'm not sure it best describes the task. I was asked by a reader to consider a simple problem. Given a list of dates, how would you rewrite them so that two (or more) consecutive dates are displayed together? For example, imagine this input.
dates = [(May 1, 2013), (May 4, 2013), (May 5, 2013), (May 7, 2013)]
I want to take this list and join the values that are one day apart. I should end up with:
dates = [(May 1, 2013), (May 4, 2013 - May 5, 2013), (May 7, 2013)]
First I create my sample data and a new array that will store my results.
Now for the real "meat" of the logic. My idea here was to store objects in the new date array. The object contains a first and last property referring to the first and last date. What this allows for is a quick date comparison. If the next item in my source data is one day after the last value in the previous range, than we 'extend' the range by resetting the last property. Otherwise we need to add a new item in the result array.
Finally, let's make this easier to use by doing some formatting on the array elements. We will loop through each item and add a 'formatted' key.
And the result is this:
Ignore our two helper functions on top for now. Our initial seed data is very similar to the ColdFusion one. Instead of using dateNew we use the Date constructor.
Finally, I did my formatting. Again, I could have grabbed a library for this, but instead I simply ran toDateString. My dtFormat function is a bit simple. Almost too simple to even be its own function. But I was imagining that I'd probably want to make formatting a bit more complex in the future. This lets me handle that later.
Note - I switched to Firefox for the screenshot as I think it prints objects nicer in the console.
I've included a zip with the complete code for both examples. Note the CFM has a tag-version as well for older CF engines.