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

144
Views
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 answers
Answer question

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 Report

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 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!