Skip to content

Instantly share code, notes, and snippets.

@lbn
Last active April 28, 2024 11:25
Show Gist options
  • Save lbn/3d6963731261f76330af to your computer and use it in GitHub Desktop.
Save lbn/3d6963731261f76330af to your computer and use it in GitHub Desktop.
Pretty print a matrix in ES6
"use strict"
function matprint(mat) {
let shape = [mat.length, mat[0].length];
function col(mat, i) {
return mat.map(row => row[i]);
}
let colMaxes = [];
for (let i = 0; i < shape[1]; i++) {
colMaxes.push(Math.max.apply(null, col(mat, i).map(n => n.toString().length)));
}
mat.forEach(row => {
console.log.apply(null, row.map((val, j) => {
return new Array(colMaxes[j]-val.toString().length+1).join(" ") + val.toString() + " ";
}));
});
}
// Try it!
let a = [[1,2,3],[4,5555555555555555555555,1],[0.000000000006, 7, 8]];
matprint(a)
/*
1 2 3
4 5.555555555555556e+21 1
6e-12 7 8
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment