How to implement array.any()
and array.all()
methods in Coffeescript?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With