Alex Rivera | Logout

How to implement array.any() and array.all() methods in Coffeescript?

Asked 2011-08-23T04:19:22.840
12

How to implement array.any() and array.all() methods in Coffeescript?

Edit
Report

1 Answer

6

Check out underscore.js, which provides you with _.any and _.all methods (a.k.a. _.some and _.every) that will run in any major JS environment. Here's how they're implemented in CoffeeScript in underscore.coffee:

_.some = (obj, iterator, context) ->
  iterator ||= _.identity
  return obj.some iterator, context if nativeSome and obj.some is nativeSome
  result = false
  _.each obj, (value, index, list) ->
    _.breakLoop() if (result = iterator.call(context, value, index, list))
  result

_.every = (obj, iterator, context) ->
  iterator ||= _.identity
  return obj.every iterator, context if nativeEvery and obj.every is nativeEvery
  result = true
  _.each obj, (value, index, list) ->
    _.breakLoop() unless (result = result and iterator.call(context, value, index, list))
  result

(These depend on _.each, which is a straightforward iteration method, and _.breakLoop, which just throws an exception.)

answered 2011-08-23T16:38:30.977

Your Answer