-
Notifications
You must be signed in to change notification settings - Fork 188
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
generalize transpose to arrays of arrays [[]], arrays of objects [{}]…
…, objects of arrays {[]} and objects of objects {{}}. closes #48
- Loading branch information
Showing
3 changed files
with
52 additions
and
11 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,30 @@ | ||
import min from "./min.js"; | ||
|
||
export default function(matrix) { | ||
if (!(n = matrix.length)) return []; | ||
for (var i = -1, m = min(matrix, length), transpose = new Array(m); ++i < m;) { | ||
for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n;) { | ||
row[j] = matrix[j][i]; | ||
// matrix is a key-value store of lines, themselves key-value stores of data. | ||
// dimension y of the incoming matrix | ||
const y = Object.keys(matrix); | ||
if (!y.length) return []; | ||
|
||
// dimension x of the incoming matrix | ||
const line0 = matrix[y[0]], | ||
x = new Set(Object.keys(line0)), | ||
transpose = line0.length ? [] : {}; | ||
|
||
// prepare the transpose matrix with x as first dimension | ||
for (const k of x) { | ||
transpose[k] = matrix.length ? [] : {}; | ||
} | ||
for (const [i, line] of Object.entries(matrix)) { | ||
for (const k of x) { | ||
// checks that each key is present in the line, otherwise: | ||
// - remove that key from the transpose (for lines already read) | ||
// - remove it from x (ignores it in future lines) | ||
if (!(k in line)) { | ||
delete transpose[k]; | ||
x.delete(k); | ||
} else { | ||
transpose[k][i] = line[k]; | ||
} | ||
} | ||
} | ||
return transpose; | ||
} | ||
|
||
function length(d) { | ||
return d.length; | ||
} |
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