JSFiddle - React, Tailwind, and code Playground

by Denys Biliaiev

JavaScript

"use strict"

class Matrix {
    constructor(n) {
        this.matrix = [];
        this.n = n;
        var num = 1;
        
        for (var i = 0; i < n; i++){
            this.matrix[i] = [];

            for (var j = 0; j < n; j++, num++){
                this.matrix[i][j] = num;
            }
        }

        if (this.n % 2 == 0) {
            this.y = Math.floor(n / 2 - 1);
        } else {
            this.y = Math.floor(n / 2);
        }

        this.centerLine = this.matrix[this.y];
        this.x = Math.floor(this.centerLine.length / 2);

        this.countSteps = {
            left: 1,
            right: 2,
            top: 2,
            down: 1,
        }
    }

    goTo(way) {
        var result = [];

        for (var step = 1; step <= this.countSteps[way]; step++) {
            way == 'left' ? this.x-- : this.x;
            way == 'right' ? this.x++ : this.x;
            way == 'top' ? this.y-- : this.y;
            way == 'down' ? this.y++: this.y;

            if (!this.matrix[this.y][this.x]) break;
            result.push(this.matrix[this.y][this.x]);
        }
        this.countSteps[way] += 2;

        return result;
    }

    read() {
        var result = [];
        result.push(this.centerLine[this.x]);

        while (true) {
            result = result.concat(this.goTo('left'));
            if (!this.matrix[this.y][this.x]) break;

            result = result.concat(this.goTo('down'));
            if (!this.matrix[this.y][this.x]) break;

            result = result.concat(this.goTo('right'));
            if (!this.matrix[this.y][this.x]) break;

            result = result.concat(this.goTo('top'));
            if (!this.matrix[this.y][this.x]) break;
        }
        return result;
    }
}

var matrix = new Matrix(9);
console.log(matrix.read());