JSFiddle - React, Tailwind, and code Playground

by Spencer Smith

HTML

<svg viewBox="0 0 200 200" width="300px">
  <!-- <path d="M0,0 L10,0 L10,10 L0,10" stroke="white" stroke-width="5px" stroke-linecap="round" stroke-linejoin="round" fill="none"></path> -->
</svg>

CSS

body {
  background-color: whitesmoke;
  background-color: #222;
}
svg {
  background-color: #222;
  border-radius: 4px;
  margin: 0 auto;
  display: block;
}

JavaScript

const svg = document.querySelector('svg');

const DIMENTION = 40;
const LINE_WIDTH = 3;
const DELAY = 10;

const start = 0;
let end = 0;
let longestDist = 0;
const graph = [];
const tree = [];
const visited = {};

// add nodes to graph
for (let i = 0; i < DIMENTION * DIMENTION; i++) {
  graph.push({
    index: i,
    to: [],
  });
}

// add edges
for (let i = 0; i < DIMENTION * DIMENTION; i++) {
  const node = graph[i];
  const { up, down, left, right } = getNeighbors(i);
  const edges = [up, down, right, left].filter(e => e);
  node.edges = edges;
}

explore(start, 0);
draw();

function explore(index, dist) {
  visited[index] = true;
  const neighbors = getNeighbors(index);

  // keep track of the node furthest from start that's on the edge
  if (neighbors.length < 4 && dist > longestDist) {
    longestDist = dist;
    end = index;
  }

  for (let i = 0; i < neighbors.length; i++) {
    const next = neighbors[i];
    if (!visited[next]) {
      tree.push([index, next, dist]); // add pair to tree
      explore(next, dist + 1);
    }
  }
}

function getNeighbors(index) {
  const { row, column } = toRowColumn(index);
  const up = toIndex(row - 1, column);
  const down = toIndex(row + 1, column);
  const left = toIndex(row, column - 1);
  const right = toIndex(row, column + 1);
  return shuffle([up, down, left, right].filter(n => n));
}

function toRowColumn(index) {
  const row = Math.floor(index / DIMENTION);
  const column = index % DIMENTION;
  return { row, column };
}

function toIndex(row, column) {
  if (row < 0 || row >= DIMENTION) return null;
  if (column < 0 || column >= DIMENTION) return null;
  return (row * DIMENTION) + column;
}

function shuffle(array){
  for(let i = 0; i < array.length; i++){
    const randomIndex = Math.floor(Math.random() * array.length);
    const temp = array[i];
    array[i] = array[randomIndex];
    array[randomIndex] = temp;
  }
  return array;
}

async function draw() {

  const adjust = LINE_WIDTH / 2; // used to make...