Reputation: 1967
const x = [new Date(), 1663761716, (new Date()).toJSON()];
const y = x.map((v) => new Date(v));
console.log(y);
The code above transforms an array of Date, number, string into an array of 3 Dates.
My question is the second line. Of course it is already short enough, but it feels stupid to call a function in a lambda with the same parameter. There should be something like:
const y = x.map(Date.constructor);
But this doesn't work. Is there any way to pass a constructor as a parameter?
Upvotes: 4
Views: 604
Reputation: 1074285
Unfortunately, there's no shortcut for it. What you have is what you should do (either directly inline like that, or a reusable named function that does it). There are two reasons for that:
Because of the need for new
. There's no way to say to map
"here's Date
, but call it using new
instead of just calling it normally" (other than what you're doing, using a wrapper function). (There was once a proposal for a way to do it, but it never progressed.) And you do need to call Date
using new
for your use case; calling Date
without new
returns a string representation of the date, not a Date
object.
Because map
passes three arguments to the callback function, and Date
treats being called with three arguments differently from how it treats being called with one argument. You want the one argument version in your case. See the answers to the question here for details (that question forces on parseInt
, but it's the same problem — the function doing different things depending on how many arguments are provided).
Upvotes: 1