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

143
Visualizações
How to efficiently validate all args in Javascript functions?

I work with Javascript (Typescript), more specifically with React. So this question is written in Javascript but it's more like a general question.

I'm trying to refactor some code and extract static methods. Once I extract the method, I find myself checking if all arguments received are valid. This becomes hard to read and, sometimes, the real purpose of the function has only a few lines.

Here's an example of how I would end up writing a method / function

const isGreaterThan = (value1, value2) => {
  if(typeof value1 !== 'number'){
    console.error("Invalid argument. value1 must be a number");
    return 0;
  }
  if(typeof value2 !== 'number'){
    console.error("Invalid argument. value2 must be a number");
    return 0;
  }
  return value1 > value2
}

Now imagine if this method receives an Array

const isGreaterThanAll = (values, value1) => {
  if(!values instanceof Array){
    console.error("Invalid argument. values must be an Array");
    return 0;
  }
  if(!values.every(value => typeof value === 'number')){
    console.error("Invalid argument. elements of values must be numbers");
    return 0;
  }
  if(typeof value1 !== 'number'){
    console.error("Invalid argument. value2 should be type of number");
    return 0;
  }
  return values.every(value => value1 > value);
}

Now imagine passing an Object or an Array of Objects. Depending on the complexity of the arguments, this becomes harder to follow.

Some of my questions are:

  • Which is the best practice to refactor code in this scenario?
  • How can I refactor this kind of code to be more readable?
  • Should I build a method to check arguments?
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

One way to do it is to create a recursive function like this.

const isNumberOrArrayOfNumbers = (x) => {
  if (typeof x === 'number') {
    return true;
  }
  if ( Array.isArray(x) ) {
    return x.every(n => isNumberOrArrayOfNumbers(n));
  }
  return false;
};

const isGreaterThanAll = (values, value1) => {

  let valid = [values, value1].every(a => isNumberOrArrayOfNumbers(a));
  
  if (!valid) {
    console.error('Invalid');
    return Number.NaN;
  }


  return values.every(value => value1 > value);
};

console.log( isGreaterThanAll([1,2,3,5,6,7],12) );
console.log( isGreaterThanAll([1,2,3,5,6,7],4) );
console.log( isGreaterThanAll([1,2,3,"r",5,6,7],12) );

If you're willing to change the signature of the function you could also refactor by making it variadic and using rest operators

That might look something like this:

const isGreaterThanAll = (n, ...m) => {
    let valid = [n, ...m].every(x => typeof x === 'number');
    ...
};
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