Skip to content

Instantly share code, notes, and snippets.

@TehShrike
Created October 20, 2012 22:15
Show Gist options
  • Save TehShrike/3925018 to your computer and use it in GitHub Desktop.
Save TehShrike/3925018 to your computer and use it in GitHub Desktop.
Knowing when a recursion tree is finished
var functionThatCallsItselfMultipleTimes = function(starting_number) {
if (starting_number === 1) {
console.log("THING DONE!")
} else {
var roughly_half_the_number = Math.floor(starting_number / 2)
functionThatCallsItselfMultipleTimes(starting_number - roughly_half_the_number)
functionThatCallsItselfMultipleTimes(roughly_half_the_number)
}
}
functionThatCallsItselfMultipleTimes(7)
console.log("The recursive function was just called.")
var wrapUpRecursiveFunction = function(fun, cb) {
var running = 0
return function() {
running++
fun.apply(this, Array.prototype.slice.call(arguments))
running--
if (running === 0) {
cb()
}
}
}
var callThisAfterAllTheRecursionIsDone = function() {
console.log("All things done!")
}
functionThatCallsItselfMultipleTimes = wrapUpRecursiveFunction(functionThatCallsItselfMultipleTimes,
callThisAfterAllTheRecursionIsDone)
functionThatCallsItselfMultipleTimes(9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment