Activate your free membership today | Log-in

Tuesday, July 24th, 2007

Functional JavaScript

Category: JavaScript, Library

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:
  1.  
  2. map('x*x', [1,2,3,4])
  3. //  → [1, 4, 9, 16]
  4. select('>2', [1,2,3,4])
  5. //  → [3, 4]
  6. reduce('x*2+y', 0, [1,0,1,0])
  7. //  → 10
  8. map(guard('2*', not('%2')), [1,2,3,4])
  9. //  → [1, 4, 3, 8]
  10.  
  11. until('>100', 'x*x')(2)
  12. //  → 256
  13.  
  14. var squareUntil = until.partial(_, 'x*x');
  15. var square2Until = squareUntil.uncurry().flip().curry(2);
  16. var firstSquare2Over = compose(square2Until, 'n -> i -> i> n');
  17. firstSquare2Over(100)
  18. //  → 256
  19.  

Posted by Dion Almaer at 11:46 am

+++--
3.7 rating from 24 votes

7 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

I like this, it’s a fun idea and I wish I could be programming like this.

Joseph, Freelancer currently working on the india sildenafil project.

Comment by JosephL — March 17, 2008

thank you

العاب باربي
موقع باربي

Comment by afth — May 6, 2008

Leave a comment

You must be logged in to post a comment.