Spiral Matrices in JavaScript

Published: Mar 18, 2019

Last updated: Mar 18, 2019

This blog assumes a global install of mocha, although that can also be installed locally. chai is also required as the assertion library - install as a dev dependency.

Writing tests

Create sm.mocha.js.

1const lib = require("./index");
2const chai = require("chai");
3const { expect } = chai;
4
5describe("spiral matrix", function () {
6 it("should return correct for 2", function () {
7 let target = [
8 [1, 2],
9 [4, 3],
10 ];
11 const res = lib.matrix(2);
12
13 expect(res).to.deep.equal(target);
14 });
15
16 it("should return correct for 3", function () {
17 let target = [
18 [1, 2, 3],
19 [8, 9, 4],
20 [7, 6, 5],
21 ];
22 const res = lib.matrix(3);
23
24 expect(res).to.deep.equal(target);
25 });
26
27 it("should return correct for 0", function () {
28 let target = [];
29 const res = lib.matrix(0);
30
31 expect(res).to.deep.equal(target);
32 });
33});

Main js file

Create index.js:

/** * Build a 2D matrix based on size n and return * integers spiralling down from n*n * * @param {*} n Matrix size */ let matrix = (n) => { const mat = []; for (let i = 0; i < n; i++) { mat.push([]); } let count = 1; let startCol = 0; let endCol = n - 1; let startRow = 0; let endRow = n - 1; while (startRow <= endRow && startCol <= endCol) { // top row for (let i = startCol; i <= endCol; i++) { mat[startRow][i] = count; count++; } startRow++; // right col down for (let i = startRow; i <= endRow; i++) { mat[i][endCol] = count; count++; } endCol--; // bottow row rtl for (let i = endCol; i >= startCol; i--) { mat[endRow][i] = count; count++; } endRow--; // start col btt for (let i = endRow; i >= startRow; i--) { mat[i][startCol] = count; count++; } startCol++; } return mat; }; module.exports = { matrix, };

Testing

Change into directory and run mocha sm.mocha.js.

Personal image

Dennis O'Keeffe

Byron Bay, Australia

Share this post

Recommended articles

Dennis O'Keeffe

2020-present Dennis O'Keeffe.

All Rights Reserved.