MatrixBox()

by Felipe Alfaro

JavaScript

Array.prototype.equalTo = function(testArr) {
    if (this.length != testArr.length) return false;
    for (var i = 0; i < testArr.length; i++) {
        if (this[i].equalTo) { //To test values in nested arrays
            if (!this[i].equalTo(testArr[i])) return false;
        }
        else if (this[i] !== testArr[i]) return false;
    }
    return true;
}

function MatrixBox(rows, cols){
	var cellIdDict = {};
    var rowIdDict = {};
    var colIdDict = {};
    var dataStorageCountId = 0;
    var dataStorage = {};
    var gridMatrix = [];
    var cacheDataId;
	for( var rowIndex = 0; rowIndex < rows.length; rowIndex++ ){
    	var currentRow = [];
        rowIdDict[rows[rowIndex]] = rowIndex;
        for( var colIndex = 0; colIndex < cols.length; colIndex++ ){
        	currentRow.push(false);
        	cellIdDict[ String(rows[rowIndex]) + String(cols[colIndex]) ] = [rowIndex, colIndex];
            if( rowIndex === 0 ){ colIdDict[ cols[colIndex] ] = colIndex; };
        }
        gridMatrix.push(currentRow);
    }
    function writableCellsRange(firstCell,lastCell,exceptionDataId){
    	var cells = [];
        for( var y = firstCell[0]; y <= lastCell[0]; y++ ){
        	for( var x = firstCell[1]; x <= lastCell[1]; x++ ){
            	var yx = [y,x],
                	cell = gridMatrix[y][x];
            	if( cell && cell != exceptionDataId ){
                    return false;
                }else{
                	cells.push(yx);
                }
            }
        }
        return cells;
    }
    function clearInMatrix(cellsArray){
        for( var i = 0; i < cellsArray.length; i++ ){
            gridMatrix[cellsArray[i][0]][cellsArray[i][1]] = false;
        }
    }
    
    this.cell = function(row, col, data){
		var dataId = 'data-'+dataStorageCountId,
        	selectedCell = cellIdDict[row+col],
            cell = gridMatrix[selectedCell[0]][selectedCell[1]];
        if( !cell ){
            dataStorage[dataId] = {
            	value: data,
             ...