r/coffeescript • u/xjohnseanx • Nov 14 '14
Passing functions as parameters
Hey I am working through http://eloquentjavascript.net/ and decided to use coffeescript. However, I am having some issues getting a few of the examples to work.
function forEach(array, action) {
for (var i = 0; i < array.length; i++)
action(array[i]);
}
forEach(["Wampeter", "Foma", "Granfalloon"], console.log);
// → Wampeter
// → Foma
// → GranfalloonHow would you write something like this using coffeescript? I already tried http://js2coffee.org/ after not being able to come up with a solution myself
4
Upvotes
View all comments
Show parent comment
2
u/DavidBonnet Nov 14 '14
Specifying the context with a
thatargument is the most flexible way (using the function'sbindmethod seriously hinders performance).Note however that the proposed implementation of
forEachwill return an array whose items are the result of eachaction(item)call, which is costly to build. To avoid that, add areturnstatement at the end. I would also use CoffeeScript's ability to set default values to function arguments to avoid unnecessary computations in theforloop. In the end, it should look like this:A call would look like this: