Skip to content

Instantly share code, notes, and snippets.

@epitron
Last active August 29, 2015 14:10
Show Gist options
  • Save epitron/feee30955a6b2c530f7f to your computer and use it in GitHub Desktop.
Save epitron/feee30955a6b2c530f7f to your computer and use it in GitHub Desktop.
Extending JavaScript's Array object in CoffeeScript
class Array
all: (f)->
for e in this
return false unless f(e)
true
any: (f)->
for e in this
return true if f(e)
false
reduce: (f)->
accum = f(this[0], this[1])
for e in this[2..-1]
accum = f(accum, e)
accum
sum: ->
this.reduce (a,b)-> a + b
sum_by: (f)->
this.reduce (a,b)->
f(a) + f(b)
alert [1,2,3,4].sum()
alert [1,2,3,4].reduce( (a,b)-> a + b )
alert [1,2,3,4].sum_by( (x)-> x * 2 )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment