Search code examples
javascriptnode.jscoffeescriptfor-comprehension

Coffeescript array comprehension skip value


I have an RPC library that I am porting to coffeescript. One of the things that it has to do is reorder function call parameters to make sure that they are in the correct order. To do this I have written an "array comprehension" that looks like this:

argValues = for param in paramNames
                if param of args
                    args[param]
                else if param isnt 'cb'
                    throw new Error "Missing argument for paramater '#{param}' of procedure '#{func}'"
        argValues[-1..-1] = cb

The 'cb' param is taken by all the remote procedures to provide results via a callback. This needs to be skipped by the comprehension because the client doesn't provide this callback (the server does so that the results can be encoded and written for return to the client). My issue is that the comprehension is putting in the value 'undefined' for this, so I have to replace the undefined with my callback using the clunky [-1..-1] syntax. What I would rather do is skip over it and call argValues.push cb.

Is there a way to have a comprehension skip a value like this?


Solution

  • There is a when clause you can use with loops but the fine manual only includes it in some examples. when allows you to apply conditions to the loop variables before the loop body is executed.

    If you want to skip params that aren't in args then

    for param in paramNames when param !of args
        args[param]