Skip to content

Commit

Permalink
Improved SparseVector constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Jun 26, 2024
1 parent 05ba5f6 commit fe918cd
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
20 changes: 16 additions & 4 deletions src/SparseVector.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,24 @@ class SparseVector

public function __construct($value, $dimensions = null)
{
$numArgs = func_num_args();

if (is_string($value)) {
if ($numArgs > 1) {
throw new \InvalidArgumentException("Extra argument");
}

$this->fromString($value);
} elseif (!is_null($dimensions)) {
$this->fromMap($value, $dimensions);
} else {
$this->fromDense($value);
if (!is_array($value)) {
throw new \InvalidArgumentException("Expected array");
}

if ($numArgs > 1) {
$this->fromMap($value, $dimensions);
} else {
$this->fromDense($value);
}
}
}

Expand All @@ -27,7 +39,7 @@ private function fromDense($value)

foreach ($value as $i => $v) {
if ($v != 0) {
$this->indices[] = $i;
$this->indices[] = intval($i);
$this->values[] = floatval($v);
}
}
Expand Down
16 changes: 16 additions & 0 deletions tests/SparseVectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,22 @@ public function testFromString()
$this->assertEquals([1, 2, 3], $embedding->values());
}

public function testFromStringDimensions()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Extra argument');

new SparseVector('{1:1,3:2,5:3}/6', 6);
}

public function testInvalidInteger()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Expected array');

new SparseVector(1);
}

public function testToString()
{
$embedding = new SparseVector([1, 0, 2, 0, 3, 0]);
Expand Down

0 comments on commit fe918cd

Please sign in to comment.