Created
June 26, 2017 07:11
-
-
Save Daniel-Hug/6ec686498f3cecf5009fbaf663dea50c to your computer and use it in GitHub Desktop.
JS function: create 2d array or multidimensional matrix w/o constructor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// create 2d array or multidimensional matrix | |
function createMatrix() { | |
var matrix = []; | |
matrix.add = function(val, i1, i2/*, ...*/) { | |
var cur = matrix, curI; | |
// loop from 2nd argument to 2nd to last | |
for (var i = 1; i < arguments.length - 1; i++) { | |
curI = arguments[i]; | |
// add an empty array in the current array of the matrix at every index | |
// before and including the current index until a defined value is reached | |
for (var j = curI; j >= 0 && !(curI in cur); j--) { | |
cur[j] = []; | |
} | |
cur = cur[curI]; | |
} | |
curI = arguments[i]; | |
cur[curI] = val; | |
// add an empty array in the current array of the matrix at every | |
// index before the added value until another defined value is reached | |
for (var k = curI - 1; k >= 0 && !(curI in cur); k--) { | |
cur[k] = []; | |
} | |
}; | |
return matrix; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment