Last active
August 29, 2015 14:10
-
-
Save epitron/feee30955a6b2c530f7f to your computer and use it in GitHub Desktop.
Extending JavaScript's Array object in CoffeeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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