Skip to content

Commit

Permalink
Added Slice method to SparseVector
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Jun 4, 2024
1 parent bafc9b7 commit 18f3a7e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
9 changes: 9 additions & 0 deletions sparsevec.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
8 changes: 8 additions & 0 deletions sparsevec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package pgvector_test

import (
"fmt"
"reflect"
"testing"

"github.com/pgvector/pgvector-go"
Expand All @@ -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")
}
}

0 comments on commit 18f3a7e

Please sign in to comment.