Difference between trampoline methods
I recently started learning JS and this is my first dive into the functional language area.
Did the trampoline exercise in the functional-javascript-workshop
npm module and found an interesting difference between my own solution and the official solution. Both work fine, but I don't understand what exactly the practical difference between the two is. I understand my solution well, but don't understand why the other works.
My decision
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 decision
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)
})
}
In particular, I'm interested in the last part - why does the official solution create an anonymous function and not just pass it repeat
?
source to share
Take a look at the trampoline:
function trampoline(fn) {
while(fn && typeof fn === 'function') {
fn = fn()
}
}
Note that it keeps on iterating while fn
is the function it is calling.
So, in theory, you can have as many nested functions and get the same result:
module.exports = function(operation, num) {
trampoline(function() {
return function() {
return function() {
return repeat(operation, num);
};
};
});
};
Demo: http://jsbin.com/yixaliyoye/1/edit
The official solution has one more redundant step than your solution. No real reason for this other than the original author probably found it more readable.
source to share
There really isn't a reason.
Except that the trampoline will make all the calls, while in your version the first call repeat
is outside of it. This could be considered cleaner and could make a real difference when it trampoline
was more complex (like completing the entire execution in a try-catch).
source to share