16Oct

# Now I get mapping and currying…

Posted by Elf Sternberg as Coffeescript, javascript

Okay, so I’m slow to the party.  Forgive me.  I was reading Reginald Braithewaite’s Javascript Allonge and I understood where he was heading long before he got there, and the lightbulbs were going off in my head, and although his technique for getting there was far more verbose than my own, I finally grokked the big point. It’s a classic programmer’s rule of productivity: If you find yourself doing something more than twice, automate it!

We do this all the time with makefiles and functions, but Braithwaite’s book brought the question down to the micro level: If you have to apply the same transformation to three different arrays, or if you have to apply three transformations to the same array, why are you doing it like this:

```somenumbers = [....]
squared = somenumbers.map (x) -> x * x
cubed = _somenumbers.map (x) -> x * x * X
halved = somenumbers.map (x) -> x / 2
```

When you could do this?

```somenumbers
toMap = (a) -> (f) -> a.map(f)
[squared, cubed, halved] = [
((x) -> x * x),
((x) -> x * x * x),
```

By creating a function that already has the array to process, and then processing it multiple times, you prevent the emergence of typos in your code caused by repeatedly typing the variable name. And you accurately put the point of your code in the left-hand column once, which is very attractive to me.

This is good stuff, man. And Coffeescript is so much more expressive than Javascript in the same realm. Imagine writing toMap in JS:

```function toMap(a) {
return function toMap(f) {
return a.map(f);
}
}
```

A lot of clutter to express what Coffeescript expresses so cleanly.

October 2013
M T W T F S S
« Sep   Jan »
123456
78910111213
14151617181920
21222324252627
28293031