0

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

1 Answers1

2

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

Tharabas
  • 3,402
  • 1
  • 30
  • 29
  • Thanks I got it working with that. Though I left the "(a, b, cb) ->" part away while the args where always the same.. Basically SortFunctions = quickSort: path.variableName and sortFunction arg1, arg2, (callback) -> .... – user1969202 Jan 11 '13 at 10:12