Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

coffeescript

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

like image 506
Gavin Avatar asked Aug 23 '11 04:08

Gavin


1 Answers

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.)

like image 79
Trevor Burnham Avatar answered Oct 31 '22 01:10

Trevor Burnham