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

341
Visualizações
Cast a variable based on the data type of another variable

I would like to have a function which casts a variable based on its "reference" type variable. I guess the function would take two parameters cast(x, ref), where x is the variable to cast accordingly to the data type of ref. So for example:

let myVar = cast(3, "helloworld");
console.log(myVar); // "3"

let myNewVar = cast(myVar, 32423n);
console.log(myNewVar); // 3n

Right now, I've only managed to transform numbers to bigints if the ref is a bigint

const cast = (n, ref) => typeof ref === "number" ? n : BigInt(n)

It would be nice to cast a variable to the data type of another variable.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

// Cast will attempt to force cast something (n) into the type of
// something else (ref)
const cast = (n, ref) => {
  switch(typeof(ref)) // All major types and how to convert them
  {
    case "boolean": return Boolean(n);
    case "number": return Number(n);
    case "bigint": return BigInt(n);
    case "string": return String(n);
    case "symbol": return Symbol(n);
    case "undefined": return undefined;
    default: return n; // If none of the above is the type, we return n
  }
}

// Example: 2 is an int, and the reference is a string, so we cast an int 
// to a string, this could be done with various types more complexly
let a = 2
let b = "hello"

a = cast(a, b)
console.log(a, typeof(a)) // 2, string
about 4 years ago · Juan Pablo Isaza 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