spiral-boxes-solution.js

47 lines | 1.027 kB Blame History Raw Download
const boxSize = 40;
const stepSize = boxSize + boxSize / 4;
let x = center() - boxSize / 2;
let y = center() - boxSize / 2;
let turns = 0;
let currentDirection = 0;
let currentStep = 1;
let stepsInCurrentDirection = 1;

while (!isOutsizeCanvas()) {
    box(x, y, boxSize, boxSize);
    moveAccordingToDirection();
    setNextStepAndDirection();
}

function isOutsizeCanvas() {
    return (x + stepSize) > width() ||
           (y + stepSize) > height();
}

function moveAccordingToDirection() {
    switch (currentDirection) {
        case 0:
            x += stepSize;
            break;
        case 1:
            y -= stepSize;
            break;
        case 2:
            x -= stepSize;
            break;
        case 3:
            y += stepSize;
            break;
    }
}

function setNextStepAndDirection() {
    if (currentStep % stepsInCurrentDirection == 0) {
        currentDirection = (currentDirection + 1) % 4;
        turns++;
        if (turns % 2 == 0) {
            stepsInCurrentDirection++;
        }
    }
    currentStep++;
}