Reputation: 80
I have a variable on the server side that changes depending on a request from the client side which determines which function to use. The function looks otherwise similar to each other except that it starts calls for a different function. Therefore I was thinking if I could replace the function names with a variable.
Example of what I'm thinking:
sortFunction = req.body.sortValue
path.sortFunction arg1, arg2, (callback) -> if err ... else ...
Upvotes: 0
Views: 36
Reputation: 3422
You can always access the properties of any JavaScript/CoffeeScript Object
by their name:
# suppose you have an object, that contains your sort functions
sortFunctions =
quickSort: (a, b, cb) -> ...
bubbleSort: (a, b, cb) -> ...
insertionSort: (a, b, cb) -> ...
# you can access those properties of sortFunction
# by using the [] notation
sortFunctionName = req.body.sortValue
sortFunction = sortFunctions[sortFunctionName]
# this might return no value, when 'sortFunctionName' is not present in your object
# you can compensate that by using a default value
sortFunction ?= sortFunctions.quickSort
# now use that function as you would usually do
sortFunction arg1, arg2, (err, data) -> if err ... else ...
Hope that helps ;)
Upvotes: 2