I've started learning JS recently, and this is my first dive into functional language territory.
Was doing the "trampoline" exercise in the functional-javascript-workshop
npm module, and came across an interesting difference between my own solution and the official solution. Both work perfectly fine, but I'm at a loss as to what exactly is the practical difference between them. I understand my own solution pretty well, but don't exactly understand why the other one works too.
My Solution
function repeat(op, num) {
var _repeat = function() {
if (num <= 0) return;
op();
return repeat(op, --num);
};
return _repeat;
}
function trampoline(f) {
while (f instanceof Function) {
f = f();
}
return f;
}
module.exports = function(op, num) {
return trampoline(repeat(op, num));
};
Official Solution
function repeat(operation, num) {
return function() {
if (num <= 0) return
operation()
return repeat(operation, --num)
}
}
function trampoline(fn) {
while(fn && typeof fn === 'function') {
fn = fn()
}
}
module.exports = function(operation, num) {
trampoline(function() {
return repeat(operation, num)
})
}
Specifically, I'm curious about the last part - why does the official solution create an annonymous function instead of just passing repeat
?
Take a look at the trampoline:
Notice how it keeps iterating as long as
fn
is a function, which it invokes.So theoretically you can have as many nested functions and get the same result:
Demo: http://jsbin.com/yixaliyoye/1/edit
The Official solution has one more redundant step than your solution. No real reason for it, other than the original author probably thought it looked more readable.