The Clockwise Spiral - Solution

The Clockwise Spiral - Solution

On se retrouve aujourd'hui pour la solution du précédent #KataOfTheWeek proposé par Hicham en début de semaine !

Voici une proposition de solution en Javascript :

const createSpiral = n => {
    if (!Number.isInteger(n) || n < 1) return []
    let returnArray = []

    for (let i = 0; i < n; i++) {
        returnArray[i] = Array(n)
    }

    let topBoundary = 0;
    let bottomBoundary = n-1;
    let leftBoundary = 0;
    let rightBoundary =  n-1;
    let counter = 1;
    let direction = 'LEFT';
    let x = 0;
    let y = 0;

    while (topBoundary <= bottomBoundary && leftBoundary <= rightBoundary) {
        if (direction === "LEFT" && x <= rightBoundary) {
            returnArray[y][x++] = counter++
        } else if (direction === "LEFT" && x > rightBoundary) {
            direction = "DOWN"
            x = rightBoundary
            y = ++topBoundary
        } else if (direction === 'DOWN' && y <= bottomBoundary) {
            returnArray[y++][x] = counter++
        } else if (direction === 'DOWN' && y > bottomBoundary) {
            direction = 'RIGHT'
            x = --rightBoundary
            y = bottomBoundary
        } else if (direction === 'RIGHT' && x >= leftBoundary) {
            returnArray[y][x--] = counter++
        } else if (direction === 'RIGHT' && x < leftBoundary) {
            direction = 'UP'
            x = leftBoundary
            y = --bottomBoundary
        }  else if (direction === 'UP' && y >= topBoundary) {
            returnArray[y--][x] = counter++
        } else if (direction === 'UP' && y < topBoundary) {
            direction = 'LEFT'
            x = ++leftBoundary
            y = topBoundary
        }
    }
    return returnArray
}

A bientôt pour un nouveau #KataOfTheWeek !