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?
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.
.....
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.