Created
December 16, 2012 04:05
-
-
Save srikumarks/4303229 to your computer and use it in GitHub Desktop.
Getting the dimensions of a multidimensional JS array.
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
// Assumes a valid matrix and returns its dimension array. | |
// Won't work for irregular matrices, but is cheap. | |
function dim(mat) { | |
if (mat instanceof Array) { | |
return [mat.length].concat(dim(mat[0])); | |
} else { | |
return []; | |
} | |
} | |
// Makes a validator function for a given matrix structure d. | |
function validator(d) { | |
return function (mat) { | |
if (mat instanceof Array) { | |
return d.length > 0 | |
&& d[0] === mat.length | |
&& every(mat, validator(d.slice(1))); | |
} else { | |
return d.length === 0; | |
} | |
}; | |
} | |
// Combines dim and validator to get the required function. | |
function getdim(mat) { | |
var d = dim(mat); | |
return validator(d)(mat) ? d : false; | |
} | |
// Checks whether predicate applies to every element of array arr. | |
// This ought to be built into JS some day! | |
function every(arr, predicate) { | |
var i, N; | |
for (i = 0, N = arr.length; i < N; ++i) { | |
if (!predicate(arr[i])) { | |
return false; | |
} | |
} | |
return true; | |
} | |
// Test code from Stackoverflow answer | |
// http://stackoverflow.com/questions/13814621/how-can-i-get-the-dimensions-of-a-multidimensional-javascript-array/13832026#13832026 | |
console.log(getdim(123)); // [] | |
console.log(getdim([1])); // [1] | |
console.log(getdim([1, 2])); // [2] | |
console.log(getdim([1, [2]])); // false | |
console.log(getdim([[1, 2], [3]])); // false | |
console.log(getdim([[1, 2],[1, 2]])); // [2, 2] | |
console.log(getdim([[1, 2],[1, 2],[1, 2]])); // [3, 2] | |
console.log(getdim([[[1, 2, 3],[1, 2, 4]],[[2, 1, 3],[4, 4, 6]]])); // [2, 2, 3] | |
console.log(getdim([[[1, 2, 3], [1, 2, 4]], [[2, 1], [4, 4]]])); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment