Question

I'm having trouble checking whether two strings are equal when one of them was passed through a splat argument. Because coffeescript uses strict comparisons, and because it makes a copy of the arguments when they go through a splat, I can't get the strings to compare properly without resorting to backticks. Is there a better way? Here's a minimal piece of code that demonstrates the problem:

check=(arg) ->
  if arg == 'foo' then "'#{arg}'=='foo'" else "'#{arg}'!='foo'"

emit=(args...) ->
  check(args)

console.log(emit('foo'))
console.log(check('foo'))

The output from this will be as follows:

> coffee mincase.coffee
'foo'!='foo'
'foo'=='foo'

EDIT: mu is too short gave me the key, so the revised working code looks like this (everything is the same except emit)

emit=(args...)->
  check.apply(null,args)
Was it helpful?

Solution

When you use a splat, the splat puts the splatted arguments into an array. For example:

f = (x...) -> console.log(x instanceof Array)
f(6)

will give you a true in the console. The fine manual isn't so fine in this case, it doesn't exactly spell it out, it assumes that you understand how JavaScript's arguments object works and leaves out the explicit splat puts your arguments into an array part.

So you end up passing an array to check and an array compared with a string using CoffeeScript's == (or JavaScript's ===) will never be true.

If you want emit to check the first argument, then you need to say so:

emit = (args...) -> check(args[0])

Demo: http://jsfiddle.net/ambiguous/TBndM/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top