Function Currying in CoffeeScript

Sage Griffin

Have you had a function that takes two arguments, but you want to pass the second argument in later? Here’s one possible example:

updateUsers = (db, users) ->
  _.map(users, (user) -> updateUser(db, user))

updateUser = (db, user) -> db.update("users", name: user.name)

This is messy, and extremely hard to parse mentally. However, we can make this a bit cleaner using function currying. Originally worked out by Haskell Curry, function currying is the act of taking a function that takes multiple arguments, and replacing it with a chain of functions that take a single argument each.

Curried functions take advantage of closures to emulate multiple arguments. In some functional languages, such as Haskell or the lambda calculus, curried functions are the only way to pass multiple arguments to functions.

If we curry our updateUser function, our code becomes much more readable.

updateUsers = (db, users) ->
  _.map(users, updateUser(db))

updateUser = (db) -> (user) -> db.update("users", name: user.name)

The resulting JavaScript for our updateUser function will look like this:

var updateUser = function(db) {
  return function(user) {
    return db.update("users", { name: user.name });
  };
};

It’s a simple trick, but a prime example of how CoffeeScript’s syntax can make certain tasks much cleaner!