Leo Gee
Leo Gee

Reputation: 43

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? :)

Upvotes: 3

Views: 210

Answers (2)

Mulan
Mulan

Reputation: 135327

Using Function is an anti-pattern. It's one degree away from eval and there's always a better way to write things, especially considering JavaScript already supports first-class functions -

const add = (a, b) => a + b
const multiply = (a, b) => a * b

console.log("your sum is: " + add(3,7))
console.log("your product is: " + multiply(3,7))

your sum is: 10
your product is: 21

If instead you want to access functions using "+" and "*" strings, you can create a simple lookup and throw an Error when a particular operation is not supported -

const operations = { 
  "+": (a, b) => a + b,
  "*": (a, b) => a * b 
}
  
function simpleOperations(op) {
  const f = operations[op]
  if (f == null)
    throw Error(`unsupported operation: ${op}`)
  return f
}
  
const add = simpleOperations("+")
const multiply = simpleOperations("*")

console.log("your sum is: " + add(3,7))
console.log("your product is: " + multiply(3,7))

const divide = simpleOperations("/")  // <- not yet implemented

your sum is: 10
your product is: 21
Error: unsupported operation: /

Implementing a simple calculator is a great way to learn how to write your first programming language. If this sort of thing interests you, see this related Q&A.

Upvotes: 3

CertainPerformance
CertainPerformance

Reputation: 370929

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));

Upvotes: 4

Related Questions