Objective

Create a SquareMatrix class in JavaScript to create and easily work with square matrices.

Difficulty

Easy

Description

In the exercises, we created a couple of functions to accomplish some common matrix operations such as addition, multiplication, rotation and transposition.

Now, you have to encapsulate all those into one single utility — the SquareMatrix class.

Let's explore what bells and whistles do we need to give to this class.

The SquareMatrix class defines two instance properties:

  1. array — holds the array used to represent the underlying matrix.
  2. n — holds the length of the matrix (which is same in both dimensions, since we're dealing with square matrics).

Apart from these properties, the class defines a total of six instance methods, four of which follow from the previous exercises, as described below:

  1. add(squareMatrixInstance) — adds the calling matrix to squareMatrixInstance (another instance of SquareMatrix) and returns the sum. This method creates and returns a new matrix (instance of SquareMatrix). It doesn't mutate either the calling matrix or the squareMatrixInstance argument.
  2. multiply(squareMatrixInstance) — multiplies the calling matrix to squareMatrixInstance and returns back the product. Akin to sum(), this method creates and returns a new matrix, and doesn't mutate either the calling matrix or the squareMatrixInstance argument.
  3. copy() — copies the calling matrix and returns back the copy.
  4. fill(value) — replaces each element of the calling matrix with value. In other words, the calling matrix is 'filled' up with the given value. The calling matrix is mutated. Nothing is returned by this method.
  5. rotateBy90() — rotates the calling matrix clockwise by 90°. The calling matrix is mutated. Nothing is returned by this method.
  6. transpose() — tranposes the calling matrix. The calling matrix is mutated. Nothing is returned by this method as well.

Note that the first three methods — add(), multiply() and copy() — are non-mutating i.e. they don't modify the original calling matrix in any way. A new matrix is returned at the end.

Similarly, the last three methods — fill(), rotateBy90() and transpose() — are mutating i.e. they modify the original calling matrix. Nothing is returned at the end.

When the constructor function SquareMatrix() is called with a single integer argument n, an n x n array is created with each element initialized to 0, and this array stored in the array property. In the meanwhile, the property n is initialized as well.

Otherwise, it's assumed that the function is called with an array as argument, and henceforth, the array is used as-is to create the matrix i.e. the given array argument is set as the value of the array property and n is updated likewise.

Given all these details, you have to create this SquareMatrix class in JavaScript using the idea of constructors and prototypes.