Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffeescript - Finding substring with "in"

Tags:

coffeescript

In Coffeescript the following gives true

"s" in "asd" # true

but this gives false

"as" in "asd" # false
  • Why is this?
  • It happens with strings with more than 1 character?
  • Is in not suited for this task?
like image 872
Enrique Moreno Tent Avatar asked Sep 22 '16 13:09

Enrique Moreno Tent


1 Answers

x in y syntax from coffeescript expects y to be an array, or array like object. Given a string, it will convert it into an array of characters (not directly, but it will iterate over the string's indexes as if it were an array).

So your use of in:

"as" in "asd"
# => false

is equivalent to

"as" in ["a","s","d"]
# => false

This way it is much easier to see why it returns false.

The little book of coffeescript has this to say on in:

Includes

Checking to see if a value is inside an array is typically done with indexOf(), which rather mind-bogglingly still requires a shim, as Internet Explorer hasn't implemented it.

var included = (array.indexOf("test") != -1)

CoffeeScript has a neat alternative to this which Pythonists may recognize, namely in.

included = "test" in array

Behind the scenes, CoffeeScript is using Array.prototype.indexOf(), and shimming if necessary, to detect if the value is inside the array. Unfortunately this means the same in syntax won't work for strings. We need to revert back to using indexOf() and testing if the result is negative:

included = "a long test string".indexOf("test") isnt -1

Or even better, hijack the bitwise operator so we don't have to do a -1 comparison.

 string   = "a long test string"
 included = !!~ string.indexOf "test"

Personally, I would say that the bitwise hack isn't very legible, and should be avoided.

I would write your check with either indexOf:

"asd".indexOf("as") != -1
# => true

or with a regex match:

/as/.test "asd"
# => true

or if you are using ES6, use String#includes()

like image 131
caffeinated.tech Avatar answered Oct 14 '22 00:10

caffeinated.tech