Pass date-methods like getTime() as callback

Viewed 121

I want to pass Date-object methods such as getMinutes(), getTime() or getDay() as a callback in a function such as:

formatDate = (date, callback) => {
    date.callback()
}

or more advanced:

formatDateArray = (dateArray, callback) => {
        dateArray.map(date => date.callback())
    }

What are my alternatives?

3 Answers

You can use Fuction.prototype.call to call the Date method by passing the date object as the this argument:

const getTime = Date.prototype.getTime;
const getDay = Date.prototype.getDay;
const getMinutes = Date.prototype.getMinutes

formatDateArray = (dateArray, callback) => {
  return dateArray.map(date => callback.call(date))
}

console.log(formatDateArray([new Date(), new Date('August 17, 2020 03:24:00')], getTime));
console.log(formatDateArray([new Date(), new Date('August 17, 2020 03:24:00')], getDay));
console.log(formatDateArray([new Date(), new Date('August 17, 2020 03:24:00')], getMinutes));

Try:

date[callback]()

var date=new Date();

var callbacks=["toLocaleString", "getFullYear", "valueOf"];

callbacks.forEach(cb=>console.log(cb+": "+date[cb]()));

I would use a curried function for this: the first call takes your callback (and some other optional parameters; more on that later), the second call takes your date:

const formatDate = (fn, ...args) => date => fn.apply(date, args);

We can use it with Date#getDate:

const getDate = formatDate(Date.prototype.getDate);

Because getDate is now a function that "waits" for its last parameter (i.e. a date) you can also use it with Array#map:

// moon landing dates
const apollo11 = new Date('1969-07-20');
const apollo12 = new Date('1969-11-21');

getDate(apollo11);
//=> 20

[apollo11, apollo12].map(getDate);
//=> [20, 21];

Some date methods do take parameters e.g. Date#toLocaleDateString. It would be a shame to not be able to use them. Because they are provided before the actual date we can create specialised functions:

const toUsDate = formatDate(Date.prototype.toLocaleDateString, 'en-US');
const toGbDate = formatDate(Date.prototype.toLocaleDateString, 'en-GB');

toUsDate(apollo11); //=> "7/20/1969"
toGbDate(apollo11); //=> "20/07/1969"
Related