HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Determining if a target string is found in an array of strings

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
determiningtargetarrayfoundstringsstring

Problem

I wrote this simple function in CoffeeScript to see if elements are found in an array:

isFoundIn = (searchTerm, arrayToSearch) ->
  returnVal = false
  for a in arrayToSearch
    returnVal = true if searchTerm is a
  returnVal


Usage:

isFoundIn('james', ['robert', 'michael', 'james'])`


would return true.

I know in Ruby it is very concise and readable to do this:

myArr = ['robert', 'michael', 'james']
myArr.include? 'james'


Are there some strategies to refactor this to make it more readable or more like CoffeeScript?

Solution

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

Code Snippets

isFoundIn = (term, array) -> array.indexOf(term) isnt -1
Array::include = (term) -> @indexOf(term) isnt -1
isFoundIn = (searchTerm, arrayToSearch) ->
      for a in arrayToSearch
        return true if searchTerm is a
      false

Context

StackExchange Code Review Q#26091, answer score: 6

Revisions (0)

No revisions yet.