From cac352926a401fed840bab53ec2c1af4cf4b3996 Mon Sep 17 00:00:00 2001 From: Osama Ansar Date: Tue, 13 Oct 2026 01:12:18 +0500 Subject: [PATCH] Fixed parsing of empty sparsevec in SparseVector An all-zero sparsevec is returned by Postgres as {}/n. Splitting the empty body on ',' gave [''], so the constructor pushed parseInt('') - 1 and parseFloat(undefined), leaving NaN in indices and values. --- src/sparse-vector.js | 13 ++++++++----- tests/sparse-vector.test.js | 10 ++++++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/sparse-vector.js b/src/sparse-vector.js index fac13e5..5e8d73d 100644 --- a/src/sparse-vector.js +++ b/src/sparse-vector.js @@ -72,11 +72,14 @@ export class SparseVector { this.dimensions = parseInt(parts[1]); - const elements = parts[0].slice(1, -1).split(','); - for (const element of elements) { - const ep = element.split(':', 2); - this.indices.push(parseInt(ep[0]) - 1); - this.values.push(parseFloat(ep[1])); + // all-zero vectors are {}/n + const body = parts[0].slice(1, -1); + if (body !== '') { + for (const element of body.split(',')) { + const ep = element.split(':', 2); + this.indices.push(parseInt(ep[0]) - 1); + this.values.push(parseFloat(ep[1])); + } } } diff --git a/tests/sparse-vector.test.js b/tests/sparse-vector.test.js index 9923ac8..d448fa4 100644 --- a/tests/sparse-vector.test.js +++ b/tests/sparse-vector.test.js @@ -10,6 +10,16 @@ test('fromSql', () => { assert.deepEqual(vec.values, [1, 2, 3]); }); +test('fromSqlEmpty', () => { + const vec = new SparseVector('{}/3'); + assert.deepEqual(vec.toArray(), [0, 0, 0]); + assert.equal(vec.dimensions, 3); + assert.deepEqual(vec.indices, []); + assert.deepEqual(vec.values, []); + assert.equal(vec.toPostgres(), '{}/3'); + assert.deepEqual(Object.keys(vec.toArray()), ['0', '1', '2']); +}); + test('fromDense', () => { const vec = new SparseVector([1, 0, 2, 0, 3, 0]); assert.equal(vec.toPostgres(), '{1:1,3:2,5:3}/6');