Functional JavaScript

Written by on July 24th, 2007 in Ajax News.

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.  

Source: Ajaxian
Original Article: http://feeds.feedburner.com/~r/ajaxian/~3/136919349/functional-javascript

Leave a Reply

You must be logged in to post a comment.



Site Navigation