1

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)

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I've edited the question a bit to indicate more details about what I'm actually up to, but this solved the problem. Instead of getting args[0] I'm now doing check.apply(null,args) so that I can pass through multiple arguments (this wouldn't have been clear from the code I posted though).
@Erik: You can also splat in a function call (f(array...)) if you don't want to explicitly apply, for example: jsfiddle.net/ambiguous/Gjh7G
Cool, that is much nicer. Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.