0

I have a file called helpers.js which contains the following

var helpers = {
  add: function(a,b){
    return a+b;
  },
  sub: function(a,b){
    return a-b;
  },
  mult: function(a,b){
    return a*b;
  },
  div: function(a,b){
    return a/b;
  },
  math: function(a,b,callback){
    return callback(a,b);
  }
};

module.exports = helpers;

In my app.js I am including

var express = require("express"),
app = express(),
ejs = require("ejs"),
helpers = require("./helpers");

and am trying to have a user pass in the name of a function as a parameter with this code here:

app.get('/number/:num1/:num2/:operation', function(req,res){

  var a = parseInt(req.params.num1);
  var b = parseInt(req.params.num2);
  var operation = req.params.operation;
  var result = helpers.operation(a,b);


  res.render('math', {result: result});
});

Since the variable operation is a string, I am getting the error Object # has no method 'operation'. Is there any way to convert this parameter into a function? Or is there a better way to try to do this? Thanks!

epg388
  • 137
  • 2
  • 9

1 Answers1

1

You can access the function with helpers[operation], just make sure that it's a valid function name first, otherwise you will get a TypeError exception.

var result = helpers[operation](a, b);
ldmat
  • 935
  • 1
  • 6
  • 15