Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

227
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda