jashkenas/coffeescript

In Operator - IndexOf

Opened this issue · 1 comments

The In Operator seems to have been broken for a while...

if 'github.com' in "https://github.com/jashkenas/coffeescript/issues/5481"
    alert 'Found'

Does not work (using the version on https://coffeescript.org/)

It renders to

var indexOf = [].indexOf;

if (indexOf.call("https://github.com/jashkenas/coffeescript/issues/5481", 'github.com') >= 0) {
  alert('found');:
}

Which doesn´t work:

indexOf.call("https://github.com/jashkenas/coffeescript/issues/5481", 'github.com')
-1
indexOf.call('github.com', "https://github.com/jashkenas/coffeescript/issues/5481")
-1

This works though

"https://github.com/jashkenas/coffeescript/issues/5481".indexOf('github.com')
37

That´s in chrome, not sure when indexOf.call is kinda broken

I believe this is intended behavior for CoffeeScript. It's intended to treat a string like an array of characters, and test membership according to those characters. Thus x in y tests for membership of a character x in a string y. For example:

console.log 'g' in 'github.com' # true
console.log 'x' in 'github.com' # false

As you discovered, "git" in "github.com" returns false, because "git" isn't a character.

(I had thought that this matched Python behavior, but it doesn't.)

Relevant quotes from the documentation:

You can use in to test for array presence, and of to test for JavaScript object-key presence.

All together now:

CoffeeScript JavaScript
... ...
a in b [].indexOf.call(b, a) >= 0

(FWIW, Civet includes an x is in y operator that means y.includes(x), which does substring testing.)