On a recent project, I was tasked initially with modifying an events.js
file that loaded data from JSON.
Rolling 18 Months
Basically, they wanted me to filter the events list so that only events within the last 18 months showed.
The Data
The data looked something like this ...
[
{
"name": "A Conference",
"type": "conference",
"displayDate": "April 1, 2020",
"sortDate": "2020/04/01"
},
{
"name": "Another Conference",
"type": "conference",
"displayDate": "March 24, 2020",
"sortDate": "2020/03/24"
}
]
The Solution
The original code looked like this ...
module.getEvents = function () {
return $.getJSON('events.json', function (data) {
module.events = data.sort(sortByProperty('sortDate')).reverse();
});
};
At some point in time, I added a function (deltaData
) to my inventory. If anyone out there knows where this came from I would be happy to attribute it here. To fit this functionality, it became ...
module.deltaDate = function (start_date, days, months, years) {
var date = new Date(start_date);
date.setDate(date.getDate() + days);
date.setMonth(date.getMonth() + months);
date.setFullYear(date.getFullYear() + years);
return date;
};
From here, I needed to calculate back 18 months ...
module.setFilterDate = function () {
var today = new Date();
var dayChange = 0;
var monthChange = -18;
var yearChange = 0;
return module.deltaDate(today, dayChange, monthChange, yearChange);
};
Then, the original getEvents
function transformed as follows. This function now filters, then sorts the incoming JSON data ...
module.getEvents = function () {
var filterDate = module.setFilterDate();
return $.getJSON('\\events.json', function (data) {
var filtered = data.filter(function(item) {
return new Date(item.sortDate) > filterDate;
});
module.events = filtered.sort(sortByProperty('sortDate')).reverse();
});
};
Conclusion
While this change was relatively simple, I wanted to document this functionality for my own future use. I hope you found this article interesting.