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

148
Visualizações
Creating Decorators in Javascript

I am trying to learn decorator concept

I am doing this

function calculateArea(length, width){
  return length * width;
}

function checkData(fn){
  return function(...args){
    if(args.length != 2){
      return false;
    }
    return fn(...args)
  }
}

let checked = checkData(calculateArea(2,3));

I am getting this error Uncaught TypeError: fn is not a function
Also what is the purpose of returning a function here?

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

0

The idea behind your code is to enhance/wrap any function that wants two parameters by making sure it returns false if the number of parameters is not exactly 2.

To make your code example work, you need to pass a reference to the calculateArea function to checkdata, which will return an "enriched" function that does the aforementioned, and only then call it:

function calculateArea(length, width){
  return length * width;
}

function fullName(firstName, lastName) {
  return `${firstName} ${lastName}`;
}

function checkData(fn){
  return function(...args){
    if(args.length != 2){
      return false;
    }
    return fn(...args)
  }
}

let checked = checkData(calculateArea)(2,3);
console.log(checked);

let myName = checkData(fullName)('John', 'Doe');
console.log(myName);

Using this concept allows to reduce redundancy in your code. As you can see, I don't do any checks inside calculateArea or fullName functions, and using checkData I still easily get functions that return false if the number of arguments is not exactly two.

about 4 years ago · Juan Pablo Isaza Relatório

0

.....

let checked = checkData(calculateArea(2,3));

The argument "calculateArea(2,3)" is getting run first so it returns the result of (length*width) and not a function.

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