Equivalent Ruby .Times in Coffeescript

Equivalent Ruby .times in Coffeescript

console.log 'hi' for [1..3]

To also handle 0 correctly:

console.log 'hi' for [1..n] if n

Or with prototype magic:

Number::times = (fn) ->
do fn for [1..@valueOf()] if @valueOf()
return
3.times -> console.log 'hi'

Note that the second method isn't recommended because changing the Number prototype has global effects.

Edit: Changed according to @BrianGenisio's comment (.prototype. -> ::)

Edit 2: fixed handling of 0, thanks @Brandon

equivalent of ruby Hash#reject in coffeescript

Unfortunately CoffeeScript comprehensions always generate arrays. You could use Underscore's object method to transform a [key, value] array into an object:

obj = {a:1, b:2, c:3, d:4}
_.object([k, v] for k, v of obj when v <= 2) # -> {a:1, b:2}

I'd recommend you code your own method for this specific purpose though:

reject = (obj, predicate) ->
res = {}
res[k] = v for k, v of obj when not predicate k, v
res

reject {a:1, b:2, c:3, d:4}, (k, v) -> v > 2 # -> {a:1, b:2}

Is there a CoffeeScript equivalent to the ruby koans?

Did you try Googling "CoffeeScript Koans"? :)

https://github.com/sleepyfox/coffeescript-koans

(They're powered by Jasmine.)

How to convert for loop / while to beautiful coffeescript

force.tick() for i in [1..50]

Transpiles down to:

var i, _i;

for (i = _i = 1; _i <= 50; i = ++_i) {
force.tick();
}

If you don't care about the counter var (it's not used in your example) then:

force.tick() for [1..50]

Which transpiles to:

var _i;

for (_i = 1; _i <= 50; _i++) {
force.tick();
}

Generating Javascript from coffeescript equivalent to manual javascript in _.each underscore

Your JavaScript:

_.each(this.collection.models, function (student) {
$(this.el).append(new StudCloneItemView({ model: student }).el);
}, this);

and what your => CoffeeScript produces:

var _this = this; // This is somewhere above your _.each in the generated JS
_.each(this.collection.models, function(student) {
return $(_this.el).append(new Item({
model: student
}.el));
});

are functionally equivalent. You don't need the context argument to _.each since the => generates an alias for this (called _this) that is used inside the callback.


As an aside, Backbone collections have various Underscore methods mixed in so you don't have to say _.each(@collection.models, ...), you can use each directly on the collection:

@collection.each (student) =>
@$el.append(new StudCloneItemView(model: student).el)

I've also switched to the pre-built $el that your view already has, there's no need to build a new jQuery object on each iteration.

Are there any good underscore.js alternatives that extend the core js classes?

Found one myself! http://sugarjs.com/

(and yes, I do realize extending native classes essentially forks the language... that is my motive...)



Related Topics



Leave a reply



Submit