All files / src/utils MatrixUtils.js

100% Statements 21/21
100% Branches 6/6
100% Functions 5/5
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 496x               17x     17x   1x 1x   1x 1x   15x     17x 80040x   6x 2x   6x 2x   80036x     17x         1x         5x        
const valueDataTypes = Object.freeze({
  ARRAY: "ARRAY",
  OBJECT: "OBJECT",
  OTHER: "OTHER",
});
 
// Create a matrix filled with the given value
function createFilledMatrix(rows, cols, fillValue) {
  const fillMatrix = new Array(rows);
 
  let valueDataType;
  switch (true) {
    case Array.isArray(fillValue):
      valueDataType = valueDataTypes.ARRAY;
      break;
    case typeof fillValue === "object":
      valueDataType = valueDataTypes.OBJECT;
      break;
    default:
      valueDataType = valueDataTypes.OTHER;
  }
 
  for (let i = 0; i < fillMatrix.length; i += 1) {
    switch (valueDataType) {
      case valueDataTypes.ARRAY:
        fillMatrix[i] = new Array(cols).fill().map(() => [...fillValue]);
        break;
      case valueDataTypes.OBJECT:
        fillMatrix[i] = new Array(cols).fill().map(() => ({ ...fillValue }));
        break;
      default:
        fillMatrix[i] = new Array(cols).fill(fillValue);
    }
  }
  return fillMatrix;
}
 
// Create a matrix of all 1, like the ones() function of MATLAB
function ones(rows, cols) {
  return createFilledMatrix(rows, cols, 1);
}
 
// Create a matrix of all 0, like the zeros() function of MATLAB
function zeros(rows, cols) {
  return createFilledMatrix(rows, cols, 0);
}
 
export { createFilledMatrix, ones, zeros };