Expanding on my comment above:
Your isFoundIn
function can be rewritten as simply
isFoundIn = (term, array) -> array.indexOf(term) isnt -1
indexOf
uses the strict ===
comparison, which is what CoffeeScript also uses for is
- i.e. it's equivalent to your code.
One could extend the native JS Array prototype with a include
function to more closely mimic Ruby. In CoffeeScript, it'd be written as
Array::include = (term) -> @indexOf(term) isnt -1
Then you can do [1, 2, 3].include(3)
and such. But extending native prototypes is generally frowned upon, and I can't recommend it. Tempting though.
As for your original function, you could just do an explicit return right away if the searchTerm
is found - no need to loop through the rest of the array
isFoundIn = (searchTerm, arrayToSearch) ->
for a in arrayToSearch
return true if searchTerm is a
false
The point is moot, though, as indexOf
does it all for you
Addendum: I do like the ?
hack you used to fully match Ruby's method name, but it is still just that: A hack. You're effectively adding undefined
as a possible return value for what should be a straight boolean. It'll also absorb errors (as that's its purpose) where e.g. the object responds to indexOf
just fine, but - for whatever reason - hasn't been extended with the include
function. So it's easy to get false negatives (unless you explicitly start checking for undefined
and branch if that's the case and... well, the code fogs up quick)
So again, definite points for creativity - wish I'd thought of it - but I personally wouldn't go near it in production code
indexOf
function. While there's no exact match for Ruby'sinclude?
in JavaScript, a simplearray.indexOf(term) isnt -1
will give you the same result. – Flambino May 13 '13 at 5:04_(myArr).contains("james") #=> true
. I imagine having to write JS without all those extensions and I get the chills... – tokland May 13 '13 at 8:05