Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add CoffeeScript friendly argument order to Underscore.js
# Five lines of code that will make your underscore + CoffeeScript use cleaner.
# Creates an underscore function for each function in to_reverse with R (short for Reversed) appended to the name.
# The R version moves the function argument (first argument in normal underscore) to the end,
# so you can write:
$(window).scroll _.throttleR 500, ->
console.log "This print's at most every 500ms"
# Instead of:
$(window).scroll _.throttle ->
console.log "This prints at most every 500ms too"
,
500
# The code (Add immediately after you include underscore.js):
to_reverse = ['bind', 'delay', 'defer', 'throttle', 'debounce']
mixin = {}
for name in to_reverse then do (name) ->
mixin["#{name}R"] = (args..., f) -> _(f)[name](args...)
_.mixin mixin
@jimtla

This comment has been minimized.

Copy link
Owner Author

@jimtla jimtla commented May 7, 2012

Perceptes on HN suggested:

$(window).scroll _.throttle
    -> console.log "This prints at most every 500ms too"
    500

As an alternative. Definitely nicer than my ugly example, but still won't help for long functions.

@danneu

This comment has been minimized.

Copy link

@danneu danneu commented May 7, 2012

I think you need to explicitly parenthesize the throttle() args:

$(window).scroll _.throttle(
  -> console.log "This prints at most every 500 ms too"
  500
)
@jimtla

This comment has been minimized.

Copy link
Owner Author

@jimtla jimtla commented May 7, 2012

Also check out the fork by shaunxcode (https://gist.github.com/2625081) for the key/value varient.

@jimtla

This comment has been minimized.

Copy link
Owner Author

@jimtla jimtla commented May 7, 2012

@danneu - I threw it in the "Try coffeescript" window and it seemed to come out right. Possibly version dependent?

@danneu

This comment has been minimized.

Copy link

@danneu danneu commented May 7, 2012

@jimtla - this compiles for you?

@darklajid

This comment has been minimized.

Copy link

@darklajid darklajid commented May 7, 2012

@danneu @jimtla - this only complains about the missing _ (of course)

Erm.. Enter, to early. But the result is obviously wrong. So I agree with @danneu here, I see no way without parens?
Well.. Or adding a "," after the first line. Like so

@jimtla

This comment has been minimized.

Copy link
Owner Author

@jimtla jimtla commented May 7, 2012

facepalm Yep, this also works, but needs the ugly leading comma. Slightly better than the ending comma?

@danneu

This comment has been minimized.

Copy link

@danneu danneu commented May 8, 2012

The leading comma seems to be idiomatic from my limited exposure to coffeescript and seeing setInterval() in the wild. :o)

You get used to it pretty quickly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment