Skip to content

Instantly share code, notes, and snippets.

@emilong
Created May 14, 2017 17:17
Show Gist options
  • Save emilong/9de5cdf3177545ec02d214c7185702fd to your computer and use it in GitHub Desktop.
Save emilong/9de5cdf3177545ec02d214c7185702fd to your computer and use it in GitHub Desktop.
Return promises from a tree growing algorithm to get all the endpoints
// render the given branch, which is specified by its startingPoint, length, and angle
// If there are more branches to grow, grow randomly to the left and right
function growBranch({ startingPoint, length, angle, remainingBranches }) {
endingPoint = computeEndpoint({ startingPoint, length, angle });
renderBranch({ startingPoint, endingPoint });
const newRemainingBranches = remainingBranches - 1;
if (newRemainingBranches <= 0) {
// Return the endingPoint immediately: we know the end of this branch.
// We return this as a promise that can be resolved immediately so
// we're consistent in returning a promise from this function
return Promise.resolve(endingPoint);
}
// Use Promise.all to guarantee that we'll return the endpoints only once
// both directions, left and right have completed.
return Promise.all(
["left", "right"].map(direction => {
const newAngle = computeRandomAngle(direction);
const newLength = shrinkBranchLength(length);
// Wrap setTimeout in a promise so that we can captured the value returned
// by the recursive growBranch() call.
return new Promise(resolve => {
// after a delay...
setTimeout(function() {
// make the resolution of the promise be whatever growBranch returned
resolve(
growBranch({
startingPoint: endingPoint,
length: newLength,
angle: newAngle,
remainingBranches: newRemainingBranches
})
);
}, DELAY);
});
})
// Promise.all resolves to an array, but we need to flatten it out because
// otherwise we'll get a tree of arrays and we just want a flat array of
// endpoints
).then(flatten);
}
// Starts off the tree by growing the first "branch," i.e. the trunk itself
function growTree() {
return growBranch({
startingPoint: GROUND,
length: TRUNK_LENGTH,
angle: STRAIGHT_UP,
remainingBranches: TREE_COMPLEXITY
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment