JSFiddle - React, Tailwind, and code Playground

by jrab227

JavaScript

function Matrix(arrs) {
	this.arrs = arrs;
  this.rows = arrs.length;
  this.cols = arrs[0].length;
}

Matrix.prototype.get = function(row, col) {
	return this.arrs[row][col];
}

Matrix.prototype.minor = function(row, col) {

	let newArrs = this.arrs.reduce(function(agg, nextRow, index) {
  	if (index === row) {
    	return agg;
    }
    agg.push(nextRow.slice(0, col).concat(nextRow.slice(col+1)));
    return agg;
  }, []);
	
	return new Matrix(newArrs);
}

function det(matrix) {
	let selectedRow = 0;
	if (matrix.rows == 1 && matrix.cols == 1) {
  	return matrix.get(0, 0);
  }
  return matrix.arrs[selectedRow]
    .reduce(function(agg, value, col) {

      return agg + (Math.pow(-1, selectedRow + col) *
          value * det(matrix.minor(selectedRow, col)) );
    }, 0);
  
}

var m = new Matrix([ [-2, 2, -3], [-1, 1, 3], [2, 0, -1] ]);

console.log(det(m));