Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rileyjshaw/02c5a8135dd3b1368918 to your computer and use it in GitHub Desktop.
Save rileyjshaw/02c5a8135dd3b1368918 to your computer and use it in GitHub Desktop.
MIT
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Stepping through recursion</title>
</head>
<body>
<p>Stepping through recursion</p>
<button class="stepper">Click me for next step!</button>
<button class="isOne">Click me if there's a 1 in this batch!</button>
<script src="main.js"></script></script>
</body>
</html>
var urls = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 1, 0], [0, 0, 0, 1, 1, 0, 1, 0].reverse()];
var stack = [];
var current = [];
var visited = [];
function wasTrue () {
var half = Math.floor(current.length / 2);
// if length is one, move the URL to the visited list
if (!half) visited.push(current.pop());
// else split it in two and push it to the stack
else stack.push(current.slice(0, half), current.slice(half));
}
function step () {
var currentLength = current.length;
// if there's nothing on the stack, grab the next chunk
if (!stack.length) stack.push(urls.pop());
current = stack.pop();
if (currentLength !== 8 && currentLength === current.length) {
wasTrue();
step();
} else p.textContent = current;
}
var p = document.querySelector('p');
document.querySelector('.stepper').addEventListener('click', step, false);
document.querySelector('.isOne').addEventListener('click', wasTrue, false);

Stepping through a recursive function

Toy example that shows how a user can step through a recursive function. Pretty simple; just implement your own stack instead of relying on the call-stack. I used this technique to traverse the link tree in my visited vector reaction game.

License: MIT

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment