Tuesday, July 24th, 2007
Functional JavaScript
<>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:
-
-
map('x*x', [1,2,3,4])
-
// → [1, 4, 9, 16]
-
select('>2', [1,2,3,4])
-
// → [3, 4]
-
reduce('x*2+y', 0, [1,0,1,0])
-
// → 10
-
map(guard('2*', not('%2')), [1,2,3,4])
-
// → [1, 4, 3, 8]
-
-
until('>100', 'x*x')(2)
-
// → 256
-
-
var squareUntil = until.partial(_, 'x*x');
-
var square2Until = squareUntil.uncurry().flip().curry(2);
-
var firstSquare2Over = compose(square2Until, 'n -> i -> i> n');
-
firstSquare2Over(100)
-
// → 256
-








Wild!
Meaning no disrespect to Master Steele, but…http://w3future.com/html/beyondJS/
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
“compare” is what I meant, no way to edit comments
Dojo also has a map and a reduce (which I wrote quite a while ago…) and they’re native in FF 3.