I need to do some advanced array sorting in CoffeeScript and I came across the thenBy.js micro-library which perfectly fit my needs. It's written in JavaScript, so I translated it to CoffeeScript so that I could use it inline in my .coffee file, and I ran into some problems with the translation. This doesn't work:
firstBy = ->
# mixin for the `thenBy` property
extend = (f) ->
f.thenBy = tb
return f
# adds a secondary compare function to the target function (`this` context)
#which is applied in case the first one returns 0 (equal)
#returns a new compare function, which has a `thenBy` method as well
tb = (y) ->
x = this
return extend((a, b) ->
return x(a, b) or y(a, b)
)
return extend
However, if I wrap with parens and put on trailing parens, it does work:
### Notice the starting paren
firstBy = (->
# mixin for the `thenBy` property
extend = (f) ->
f.thenBy = tb
return f
# adds a secondary compare function to the target function (`this` context)
#which is applied in case the first one returns 0 (equal)
#returns a new compare function, which has a `thenBy` method as well
tb = (y) ->
x = this
return extend((a, b) ->
return x(a, b) or y(a, b)
)
return extend
)() ### <- Notice the ending parens
I'm having a no luck understanding why putting those trailing parens on the thing causes it to work. I understand that I have an anonymous function, and I'm then calling it with those parens (see this answer), but why does that work?