JSFiddle - React, Tailwind, and code Playground
JavaScript
var Spiral = (function() {
var numberElements, maxX, maxY, actualX, actualY, position, content, elements;
var initMax = function() {
maxX = Math.floor(Math.sqrt(numberElements));
for (; maxX < numberElements; ++maxX) {
if (numberElements % maxX == 0) {
break;
}
}
maxY = numberElements / maxX;
};
var moveForward = function() {
if (!elements[actualY]) {
elements[actualY] = [];
}
elements[actualY][actualX] = content++;
switch (position) {
case 0:
if (actualX == (maxX - depth - 1)) {
++actualY; ++position;
break;
}
++actualX;
break;
case 1:
if (actualY == (maxY - depth - 1)) {
--actualX; ++depth; ++position;
break;
}
++actualY;
break;
case 2:
if (actualX == (depth - 1)) {
--actualY; ++position;
break;
}
--actualX;
break;
case 3:
if (actualY == depth) {
++actualX; position = 0;
break;
}
--actualY;
break;
}
};
generate = function() {
while (content < numberElements) {
moveForward();
}
};
init = function(number) {
numberElements = number;
actualX = actualY = depth = content = position = 0;
elements = [];
initMax();
generate();
};
var spiral = {
getRootElement: function() {
return document.body;
...