Created
January 23, 2012 17:27
-
-
Save timruffles/1664373 to your computer and use it in GitHub Desktop.
Wraps function that yields (is called with) multiple values with the Enumerable API (js 1.6 Array methods)
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 Enumerable | |
| constructor: (@fn,bind) -> | |
| if bind | |
| fn = @fn | |
| @fn = -> fn.apply(bind,arguments) | |
| map: (transform) -> | |
| results = [] | |
| @fn -> | |
| results.push transform( | |
| if arguments.length == 1 | |
| arguments[0] | |
| else | |
| [].slice.call(arguments,0) | |
| ) | |
| results | |
| ["forEach","reduce","filter","every","some"].forEach (method) -> | |
| Enumerable::[method] = -> | |
| mapped = @map (x) -> x | |
| mapped[method].apply(mapped,arguments) | |
| oddArray = [1,2,3,4,5,5,6] | |
| oddArray.allTheThings = oddArray.forEach | |
| enumer = new Enumerable(oddArray.allTheThings,oddArray) | |
| console.log "map",re = enumer.map((x) -> x) | |
| console.log "ev", re = enumer.every(([el,i,a]) -> el % 2 == 0), re == false | |
| console.log "sm", re = enumer.some(([el,i,a]) -> el % 2 == 0), re == true | |
| console.log "fi", re = enumer.filter(([el,i,a]) -> el % 2 == 0), re.length == 3 | |
| console.log "re", re = enumer.reduce(((s,[el,i,a]) -> s + el),0), re == 26 | |
| Number::times = (fn) -> | |
| n = 0 | |
| fn(n) while(n < this && n += 1) | |
| null | |
| once = new Enumerable(Number::times,1) | |
| console.log once.map((x) -> 2*x*x) | |
| thrice = new Enumerable(Number::times,3) | |
| console.log thrice.map((x) -> x*x) | |
| console.log thrice.reduce(((s,el) -> s + el),0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment