Luis Martins
Luis Martins

Reputation: 1481

loop starting from given index

Considering the following javascript, what's the best way to write this loop in coffee script, given the initial index is greater than 0:

function mixin(target, source, methods) {
  for (var i = 2, l = arguments.length; i < l; i++){
    var method = arguments[i];
    target[method] = source[method].bind(source)
  }
}

Automatic code converters suggest use a while loop like this:

mixin = (target, source, methods) ->
  i = 2
  l = arguments.length

while i < l
  method = arguments[i]
  target[method] = source[method].bind(source)
  i++

Is there a cleaner way to do this?

Upvotes: 1

Views: 495

Answers (2)

mu is too short
mu is too short

Reputation: 434635

You'd usually use a splat in CoffeeScript when defining your mixing function:

The JavaScript arguments object is a useful way to work with functions that accept variable numbers of arguments. CoffeeScript provides splats ..., both for function definition as well as invocation, making variable numbers of arguments a little bit more palatable.

So you'd say:

mixin = (target, source, methods...) ->
  # splat ----------------------^^^
  for method in methods
    target[method] = source[method].bind(source)

and your problem goes away. The splat in the argument list will collect all the arguments after source into a methods array for you so you won't have to worry about arguments at all; the splat also makes the function's signature nice and obvious.

Upvotes: 3

jcollum
jcollum

Reputation: 46579

Use an exclusive range (triple dot, excludes the number at the highest.

for i in [2...arguments.length]
  method = arguments[i]
  target[method] = source[method].bind(source)

If you have 5 things in your args, this will hit indexes 2, 3 and 4.

Upvotes: 3

Related Questions