From 38923c05959264e11a6dd92490922984da6fd757 Mon Sep 17 00:00:00 2001
From: Andrew Kane <andrew@ankane.org>
Date: Mon, 24 Jun 2024 20:45:01 -0700
Subject: [PATCH] Sort indices for SparseVector

---
 src/SparseVector.php       | 3 ++-
 tests/SparseVectorTest.php | 5 ++++-
 2 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/src/SparseVector.php b/src/SparseVector.php
index ea1a68a..41a702b 100644
--- a/src/SparseVector.php
+++ b/src/SparseVector.php
@@ -34,9 +34,10 @@ public static function fromDense($value)
 
     public static function fromMap($map, $dimensions)
     {
+        // okay to update in-place since parameter is not a reference
+        ksort($map);
         $indices = [];
         $values = [];
-        // no need to sort since binary format is not supported
         foreach ($map as $i => $v) {
             $fv = floatval($v);
             if ($fv != 0) {
diff --git a/tests/SparseVectorTest.php b/tests/SparseVectorTest.php
index e72f889..777cdda 100644
--- a/tests/SparseVectorTest.php
+++ b/tests/SparseVectorTest.php
@@ -16,8 +16,11 @@ public function testFromDense()
 
     public function testFromMap()
     {
-        $embedding = SparseVector::fromMap([2 => 2, 4 => 3, 0 => 1, 3 => 0], 6);
+        $map = [2 => 2, 4 => 3, 0 => 1, 3 => 0];
+        $embedding = SparseVector::fromMap($map, 6);
         $this->assertEquals([1, 0, 2, 0, 3, 0], $embedding->toArray());
+        $this->assertEquals([0, 2, 4], $embedding->indices());
+        $this->assertEquals([2, 4, 0, 3], array_keys($map));
     }
 
     public function testFromString()