Skip to content

Instantly share code, notes, and snippets.

@cultofmetatron
Created September 16, 2014 18:30
Show Gist options
  • Save cultofmetatron/0587165b32635be5ce42 to your computer and use it in GitHub Desktop.
Save cultofmetatron/0587165b32635be5ce42 to your computer and use it in GitHub Desktop.
loop-recur
//assume args is an array
var partial = function(fn, args1) {
return function() {
var args2 = Array.protoype.slice.call(arguments);
return fn.apply(this. args1.concat(args2));
};
};
var loop = function(fn) {
return function() {
var self = this;
var args = Array.prototype.slice.call(arguments);
args.pop(); //the last argument is a callback
var cb = Array.prototype.slice.call(arguments, -1)[0]
var recur = function() {
var recurArgs = Array.prototype.slice.call(arguments);
//this clears the callstack
setTimeout(function() {
try {
var result = fn.apply(self, [recur].concat(recurArgs));
if (result !== undefined) {
cb(null, result);
}
} catch(err) {
cb(err, null);
}
}, 0);
}
try {
var result = fn.apply(self,[recur].concat(args));
if (result !== undefined) {
cb(null, result);
}
} catch(err) {
cb(err, null);
}
}
};
module.exports = loop;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment