Skip to content

Commit 63b64ed

Browse files
committed
chore: ensure that getNonZeros sort data if format is required
1 parent eac75af commit 63b64ed

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

src/index.js

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,17 @@ export class SparseMatrix {
288288
return this;
289289
}
290290

291+
/**
292+
* Returns the non-zero elements of the matrix in coordinate (COO), CSR, or CSC format.
293+
*
294+
* @param {Object} [options={}] - Options for output format and sorting.
295+
* @param {'csr'|'csc'} [options.format] - If specified, returns the result in CSR or CSC format. Otherwise, returns COO format.
296+
* @param {boolean} [options.sort] - If true, sorts the non-zero elements by their indices.
297+
* @returns {Object} If no format is specified, returns an object with Float64Array `rows`, `columns`, and `values` (COO format).
298+
* If format is 'csr', returns { rows, columns, values } in CSR format.
299+
* If format is 'csc', returns { rows, columns, values } in CSC format.
300+
* @throws {Error} If an unsupported format is specified.
301+
*/
291302
getNonZeros(options = {}) {
292303
const cardinality = this.cardinality;
293304
/** @type {Float64Array} */
@@ -297,19 +308,19 @@ export class SparseMatrix {
297308
/** @type {Float64Array} */
298309
const values = new Float64Array(cardinality);
299310

300-
const { format, sort = false } = options;
311+
const { format, sort = format !== undefined } = options;
301312

302313
let idx = 0;
303314
this.withEachNonZero((i, j, value) => {
304315
rows[idx] = i;
305316
columns[idx] = j;
306317
values[idx] = value;
307318
idx++;
308-
}, sort || format);
319+
}, sort);
309320

310321
if (!format) return { rows, columns, values };
311322

312-
if (!['csr', 'csc'].includes(format.toLowerCase())) {
323+
if (!['csr', 'csc'].includes(format)) {
313324
throw new Error(`format ${format} is not supported`);
314325
}
315326

@@ -1501,10 +1512,10 @@ function csrToCsc(csrMatrix, numCols) {
15011512
/**
15021513
* Converts a matrix from Coordinate (COO) format to Compressed Sparse Row (CSR) format.
15031514
* @param {Object} cooMatrix - The matrix in COO format with properties: values, columns, rows.
1504-
* @param {number} [nbRows=9] - The number of rows in the matrix.
1515+
* @param {number} nbRows - The number of rows in the matrix.
15051516
* @returns {{rows: Float64Array, columns: Float64Array, values: Float64Array}} The matrix in CSR format.
15061517
*/
1507-
function cooToCsr(cooMatrix, nbRows = 9) {
1518+
function cooToCsr(cooMatrix, nbRows) {
15081519
const { values, columns, rows } = cooMatrix;
15091520
const csrRowPtr = new Float64Array(nbRows + 1);
15101521
const length = values.length;

0 commit comments

Comments
 (0)