From 18f3a7ee5ecbbfcf319eb98b8bcc8e1b7f93e8bb Mon Sep 17 00:00:00 2001 From: Andrew Kane Date: Mon, 3 Jun 2024 23:01:28 -0700 Subject: [PATCH] Added Slice method to SparseVector --- sparsevec.go | 9 +++++++++ sparsevec_test.go | 8 ++++++++ 2 files changed, 17 insertions(+) diff --git a/sparsevec.go b/sparsevec.go index d7202b2..8d9672f 100644 --- a/sparsevec.go +++ b/sparsevec.go @@ -30,6 +30,15 @@ func NewSparseVector(vec []float32) SparseVector { return SparseVector{dim: dim, indices: indices, values: values} } +// Slice returns a slice of float32. +func (v SparseVector) Slice() []float32 { + vec := make([]float32, v.dim) + for i := 0; i < len(v.indices); i++ { + vec[v.indices[i]] = v.values[i] + } + return vec +} + // String returns a string representation of the vector. func (v SparseVector) String() string { buf := make([]byte, 0, 13+27*len(v.indices)) diff --git a/sparsevec_test.go b/sparsevec_test.go index 668bae7..b57d890 100644 --- a/sparsevec_test.go +++ b/sparsevec_test.go @@ -2,6 +2,7 @@ package pgvector_test import ( "fmt" + "reflect" "testing" "github.com/pgvector/pgvector-go" @@ -13,3 +14,10 @@ func TestSparseVectorString(t *testing.T) { t.Errorf("Bad string") } } + +func TestSparseVectorSlice(t *testing.T) { + vec := pgvector.NewSparseVector([]float32{1, 0, 2, 0, 3, 0}) + if !reflect.DeepEqual(vec.Slice(), []float32{1, 0, 2, 0, 3, 0}) { + t.Errorf("Bad slice") + } +}