Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Function() constructor as a closure

I'm trying to do something like this:

function simpleOperations(operation) {
    let myFanction = new Function('a', 'b', 'a ' + operation + ' b');
    return myFanction
}

let sum = simpleOperations("+")
let multiplicate = simpleOperations("*")

console.log("your sum is: " + sum(3,7));
console.log("your product is: " + multiplicate(3,7));

and instead of getting:

your sum is: 10
your product is: 21

I'm getting this:

your sum is: undefined
your product is: undefined

Do you have any thoughts on how to fix it? :)

like image 423
Leo Gee Avatar asked Aug 29 '26 05:08

Leo Gee


1 Answers

The text body of the function needs to return the value, otherwise your a + b or a * b etc will just be an unused expression.

function simpleOperations(operation) {
    let myFanction = new Function('a', 'b', 'return a ' + operation + ' b');
    return myFanction
}

let sum = simpleOperations("+")
let multiplicate = simpleOperations("*")

console.log("your sum is: " + sum(3,7));
console.log("your product is: " + multiplicate(3,7));
like image 190
CertainPerformance Avatar answered Aug 31 '26 18:08

CertainPerformance