Using an object literal was all we had in the pre-ES5 days, so Brian Dombrowski, Michael Burkman, and Richard Pringle are all correct that an object literal can serve as a type of namespace just as well as a class with static methods. Here's the object literal format:
const DateUtils = {addDays: (date, numDays) => {
return new Date(date.valueOf() + (numDays*24*60*60*1000));
},diffDays: (date) => {
if (date.constructor.name == 'String')
date = new Date(date);
var nowTS = new Date().valueOf();
var dateTS = date.valueOf();
return Math.ceil((dateTS - nowTS) / (24*60*60*1000));
},format: (date, fmt) => {
if (date == null)
return '';
if (date.constructor.name == 'String')
date = new Date(date);
if (Number.isNaN(date.getFullYear()) ||
Number.isNaN(date.getMonth()) ||
Number.isNaN(date.getDate()))
return '';
switch (fmt) {
case 'YYYY-MM-DD':
let YYYY = (date.getFullYear()).toString();
let MM = (date.getMonth() + 1).toString().padStart(2, '0');
let DD = (date.getDate()).toString().padStart(2, '0');
return `${YYYY}-${MM}-${DD}`
case 'Month Day, Year':
let YYYY = (date.getFullYear()).toString();
let MM = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug',
'Sep','Oct','Nov','Dec'][date.getMonth()];
let DD = (date.getDate()).toString();
return `${MM} ${DD}, ${YYYY}`
default:
throw new Error(`unhandled date format ${fmt}`);
}
}
};
My preference is to use a class with static methods, as shown in the example in my previous remarks.
This is perhaps just a guilty pleasure: I don’t have to use colons, arrow functions, and commas. Also, my text editor provides color highlighting of the static
keyword which helps me visually scan for member functions more quickly. This is admittedly personal preference, but I find this approach to be more commodious and syntactically less cumbersome.
Ultimately it makes no difference in terms of usability whether you use object literals or classes.