Skip to content

Instantly share code, notes, and snippets.

@captainbrosset
Created March 5, 2021 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save captainbrosset/4d103d54fa6b9192ddb6d0f4886114a8 to your computer and use it in GitHub Desktop.
Save captainbrosset/4d103d54fa6b9192ddb6d0f4886114a8 to your computer and use it in GitHub Desktop.
Code snippets for the "How we built the DevTools Tooltips" article
// Our list of all segments. Each one being an object like
// {start: {x, y}, end: {x, y}}
const allSegments = [...];
// Start at the first segment.
const orderedSegments = [allSegments[0]];
while (true) {
// The previous segment.
const previous = orderedSegments[orderedSegments.length - 1];
// Looking at the list of remaining segments, select the one that starts
// where the previous one ends.one ends.
const next = allSegments.find(segment => {
const alreadyUsed = orderedSegments.includes(segment);
return !alreadyUsed &&
segment.start.x === previous.end.x &&
segment.start.y === previous.end.y;
});
if (!next) {
// Handling the special case where we couldn't find the next segment.
// This can only happen if the original elements did not intersect.
throw new Error("Polygons don't intersect, add an offset");
break;
}
// Store the next segment.
orderedSegments.push(next);
// Once we've found all of the segments, we can exit the loop.
if (orderedSegments.length === allSegments.length) {
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment