Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

228
Views
How to pass a class constructor as parameter
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?

almost 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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:

  1. 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.

  2. 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).

almost 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!