JSFiddle - React, Tailwind, and code Playground

by dumptyd

JavaScript

var input_string = 'law';

const matrixB = [
  [1, 2, 3, 4, 5],
  [6, 7, 8, 9, 10],
  [11, 12, 13, 14, 15],
  [16, 17, 18, 19, 20],
  [21, 22, 23, 24, 25]
];


Array.prototype.rotate = function() {
  this.push(this.shift());
  return this;
}

function matrixEncoding(str) {
  const matrixA = [
    ['a', 'b', 'c', 'd', 'e'],
    ['f', 'g', 'h', 'i', 'j'],
    ['k', 'l', 'm', 'n', 'o'],
    ['p', 'r', 's', 't', 'u'],
    ['v', 'w', 'q', 'y', 'z']
  ];

  const out = str.split('').map(char => {
    let rIdx, cIdx;
    for (let i = 0; i < matrixA.length; ++i) {
      cIdx = matrixA[i].indexOf(char);
      if (~cIdx) {
        rIdx = i;
        break;
      }
    }

		const charCode = matrixB[rIdx][cIdx];
		
    matrixA[rIdx].rotate();
		
    cIdx = cIdx === 0 ? matrixA[rIdx].length - 1 : cIdx - 1;

    matrixA.map(row => row[cIdx]).rotate().forEach((newChar, currRowIdx) => {
      matrixA[currRowIdx][cIdx] = newChar;
    });

    return charCode;
  });

  return out.join(' ');
}

var output = matrixEncoding(input_string);
console.log(output);