Tuesday, July 24th, 2007

Functional JavaScript

Category: JavaScript, Library

<>p>Oliver Steele has a new library called Functional JavaScript that defines the standard higher-order functions (map, reduce, filter) as well as functions for partial function application and function-level programming: curry, partial, compose, guard, and until. Finally, it introduces “string lambdas”, which let you write ‘x -> x+1′, ‘x+1′, or even ‘+1′ as synonyms for function(x) {return x+1}.

His documentation / API page also has a living interpreter within, so you can test how functional you are.

If this looks fun to you, check it out:

javascript
< view plain text >
  1. map('x*x', [1,2,3,4])
  2. //  â†’ [1, 4, 9, 16]
  3. select('>2', [1,2,3,4])
  4. //  â†’ [3, 4]
  5. reduce('x*2+y', 0, [1,0,1,0])
  6. //  â†’ 10
  7. map(guard('2*', not('%2')), [1,2,3,4])
  8. //  â†’ [1, 4, 3, 8]
  9.  
  10. until('>100', 'x*x')(2)
  11. //  â†’ 256
  12.  
  13. var squareUntil = until.partial(_, 'x*x');
  14. var square2Until = squareUntil.uncurry().flip().curry(2);
  15. var firstSquare2Over = compose(square2Until, 'n -> i -> i > n');
  16. firstSquare2Over(100)
  17. //  â†’ 256

Related Content:

5 Comments »

Comments feed TrackBack URI

Wild!

Comment by Theo — July 24, 2007

Meaning no disrespect to Master Steele, but…http://w3future.com/html/beyondJS/

Comment by Tom Trenka — July 24, 2007

Whatever, even the example at http://w3future.com/html/beyondJS/ doesn’t work on firefox… and give me a break, as if:
document.body.onmousemove = Function.from(“star”, “moveTo”).delay(1000).using(
“+”.using(
Function.from(event, ×),
“*”.using(“radius”, Function.from(Math, “sin”, “angle”))),
“+”.using(
Function.from(event, “y”),
“*”.using(“radius”, Function.from(Math, “cos”, “angle”)))
).curry({
radius: 30,
angle: function() {return (new Date)/50;}.asValue()
}).gate(Function.from(“doStar”.element(),”checked”));

IS more readable than:
#
map(‘x*x’, [1,2,3,4])
#
// → [1, 4, 9, 16]

Of course no disrespect to Steele, cause they don’t even compate

Comment by Chad — July 25, 2007

“compare” is what I meant, no way to edit comments

Comment by Chad — July 25, 2007

Dojo also has a map and a reduce (which I wrote quite a while ago…) and they’re native in FF 3.

Comment by Gavin Doughtie — July 27, 2007

Leave a comment

You must be logged in to post a comment.