Page MenuHomeDevCentral

No OneTemporary

diff --git a/src/Collections/BaseVector.php b/src/Collections/BaseVector.php
index 7334cb4..00911a1 100644
--- a/src/Collections/BaseVector.php
+++ b/src/Collections/BaseVector.php
@@ -1,312 +1,343 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Collections;
use ArrayAccess;
use ArrayIterator;
use InvalidArgumentException;
use IteratorAggregate;
use Traversable;
use Keruald\OmniTools\Reflection\CallableElement;
use Keruald\OmniTools\Strings\Multibyte\OmniString;
abstract class BaseVector extends BaseCollection implements ArrayAccess, IteratorAggregate {
///
/// Properties
///
protected array $items;
///
/// Constructors
///
public function __construct (iterable $items = []) {
if (is_array($items)) {
$this->items = $items;
return;
}
foreach ($items as $item) {
$this->items[] = $item;
}
}
public static function from (iterable $items) : static {
return new static($items);
}
///
/// Interact with collection content at key level
///
public function get (int $key) : mixed {
if (!array_key_exists($key, $this->items)) {
throw new InvalidArgumentException("Key not found.");
}
return $this->items[$key];
}
public function getOr (int $key, mixed $defaultValue) : mixed {
return $this->items[$key] ?? $defaultValue;
}
public function set (int $key, mixed $value) : static {
$this->items[$key] = $value;
return $this;
}
public function unset (int $key) : static {
unset($this->items[$key]);
return $this;
}
public function contains (mixed $value) : bool {
return in_array($value, $this->items);
}
///
/// Interact with collection content at collection level
///
public function count () : int {
return count($this->items);
}
public function isEmpty () : bool {
return $this->count() === 0;
}
public function clear () : self {
$this->items = [];
return $this;
}
public function push (mixed $item) : self {
$this->items[] = $item;
return $this;
}
/**
* Append all elements of the specified iterable
* to the current vector.
*
* If a value already exists, the value is still added
* as a duplicate.
*
* @see update() when you need to only add unique values.
*/
public function append (iterable $iterable) : self {
foreach ($iterable as $value) {
$this->items[] = $value;
}
return $this;
}
/**
* Append all elements of the specified iterable
* to the current vector.
*
* If a value already exists, it is skipped.
*
* @see append() when you need to always add everything.
*/
public function update (iterable $iterable) : self {
foreach ($iterable as $value) {
if (!$this->contains($value)) {
$this->items[] = $value;
}
}
return $this;
}
/**
* Replaces a part of the vector by the specified iterable.
*
* @param int $offset Allow to replace a part inside the vector by an iterable with keys starting at 0, by adding the specified offset.
* @param int $len The maximum amount of elements to read. If 0, the read isn't bounded.
*/
public function replace(iterable $iterable, int $offset = 0, int $len = 0) : self {
$itemsCount = 0;
foreach ($iterable as $key => $value) {
$this->items[$key + $offset] = $value;
$itemsCount++;
if ($len > 0 && $itemsCount >= $len) {
break;
}
}
return $this;
}
/**
* Gets a copy of the internal vector.
*
* Scalar values (int, strings) are cloned.
* Objects are references to a specific objet, not a clone.
*
* @return array
*/
public function toArray () : array {
return $this->items;
}
///
/// HOF :: generic
///
public function map (callable $callable) : self {
return new static(array_map($callable, $this->items));
}
public function filter (callable $callable) : self {
$argc = (new CallableElement($callable))->countArguments();
if ($argc === 0) {
throw new InvalidArgumentException(
"Callback should have at least one argument"
);
}
$mode = (int)($argc > 1);
return new static(array_filter($this->items, $callable, $mode));
}
public function mapKeys (callable $callable) : self {
$mappedVector = [];
foreach ($this->items as $key => $value) {
$mappedVector[$callable($key)] = $value;
}
return new static($mappedVector);
}
+ /**
+ * Allows to map each vector elements into key/value pairs
+ * and collect them into a HashMap.
+ *
+ * @param callable $callable A method to return [$key, $value] array
+ *
+ * @return HashMap
+ */
+ public function mapToHashMap (callable $callable) : HashMap {
+ $argc = (new CallableElement($callable))->countArguments();
+
+ $map = new HashMap;
+ foreach ($this->items as $key => $value) {
+ $toAdd = match($argc) {
+ 0 => throw new InvalidArgumentException(self::CB_ZERO_ARG),
+ 1 => $callable($value),
+ default => $callable($key, $value),
+ };
+
+ if (!is_array($toAdd) || count($toAdd) != 2) {
+ throw new InvalidArgumentException(
+ "Callback must return an array with 2 items: [key, value]"
+ );
+ }
+
+ $map->set($toAdd[0], $toAdd[1]);
+ }
+
+ return $map;
+ }
+
public function flatMap (callable $callable) : self {
$argc = (new CallableElement($callable))->countArguments();
$newMap = new static;
foreach ($this->items as $key => $value) {
$toAdd = match($argc) {
0 => throw new InvalidArgumentException(self::CB_ZERO_ARG),
1 => $callable($value),
default => $callable($key, $value),
};
$newMap->append($toAdd);
}
return $newMap;
}
public function filterKeys (callable $callable) : self {
return new static(
array_filter($this->items, $callable, ARRAY_FILTER_USE_KEY)
);
}
public function chunk (int $length): Vector {
return new Vector(array_chunk($this->items, $length));
}
public function slice (int $offset, int $length) : self {
$slice = array_slice($this->items, $offset, $length);
return new static($slice);
}
public function implode(string $delimiter) : OmniString {
return new OmniString(implode($delimiter, $this->items));
}
public function bigrams () : Vector {
return $this->ngrams(2);
}
public function trigrams () : Vector {
return $this->ngrams(3);
}
public function ngrams (int $n) : Vector {
if ($n < 1) {
throw new InvalidArgumentException(
"n-grams must have a n strictly positive"
);
}
if ($n == 1) {
return Vector::from($this->map(fn ($value) => [$value]));
}
$len = $this->count();
if ($len <= $n) {
// We only have one slice.
return Vector::from([$this->items]);
}
return Vector::range(0, $len - $n)
->map(fn($i) => array_slice($this->items, $i, $n));
}
///
/// ArrayAccess
/// Interface to provide accessing objects as arrays.
///
private static function ensureOffsetIsInteger (mixed $offset) {
if (is_int($offset)) {
return;
}
throw new InvalidArgumentException(
"Offset of a vector must be an integer."
);
}
public function offsetExists (mixed $offset) : bool {
self::ensureOffsetIsInteger($offset);
return array_key_exists($offset, $this->items);
}
public function offsetGet (mixed $offset) : mixed {
self::ensureOffsetIsInteger($offset);
return $this->get($offset);
}
public function offsetSet (mixed $offset, mixed $value) : void {
if ($offset === null) {
$this->push($value);
return;
}
self::ensureOffsetIsInteger($offset);
$this->set($offset, $value);
}
public function offsetUnset (mixed $offset) : void {
self::ensureOffsetIsInteger($offset);
$this->unset($offset);
}
///
/// IteratorAggregate
///
public function getIterator () : Traversable {
return new ArrayIterator($this->items);
}
}
diff --git a/tests/Collections/VectorTest.php b/tests/Collections/VectorTest.php
index 4dcdce2..b566313 100644
--- a/tests/Collections/VectorTest.php
+++ b/tests/Collections/VectorTest.php
@@ -1,402 +1,435 @@
<?php
declare(strict_types=1);
namespace Keruald\OmniTools\Tests\Collections;
+use Keruald\OmniTools\Collections\HashMap;
use Keruald\OmniTools\Collections\Vector;
use PHPUnit\Framework\TestCase;
use InvalidArgumentException;
use IteratorAggregate;
use OutOfRangeException;
use Traversable;
/**
* @covers \Keruald\OmniTools\Collections\Vector
* @covers \Keruald\OmniTools\Collections\BaseVector
*/
class VectorTest extends TestCase {
private Vector $vector;
protected function setUp () : void {
$this->vector = new Vector([1, 2, 3, 4, 5]);
}
public function testConstructorWithIterable () : void {
$iterable = new class implements IteratorAggregate {
public function getIterator () : Traversable {
yield 42;
yield 100;
}
};
$vector = new Vector($iterable);
$this->assertEquals([42, 100], $vector->toArray());
}
public function testFrom () : void {
$this->assertEquals([42, 100], Vector::from([42, 100])->toArray());
}
public function testGet () : void {
$vector = new Vector(["a", "b", "c"]);
$this->assertEquals("b", $vector->get(1));
}
public function testGetOverflow () : void {
$this->expectException(InvalidArgumentException::class);
$this->vector->get(800);
}
public function testGetOr () : void {
$vector = new Vector(["a", "b", "c"]);
$this->assertEquals("X", $vector->getOr(800, "X"));
}
public function testSet () : void {
$vector = new Vector(["a", "b", "c"]);
$vector->set(1, "x"); // should replace "b"
$this->assertEquals(["a", "x", "c"], $vector->toArray());
}
public function testContains () : void {
$this->assertTrue($this->vector->contains(2));
$this->assertFalse($this->vector->contains(666));
}
public function testCount () : void {
$this->assertEquals(5, $this->vector->count());
$this->assertEquals(0, (new Vector)->count());
}
public function testClear () : void {
$this->vector->clear();
$this->assertEquals(0, $this->vector->count());
}
public function testIsEmpty () : void {
$this->vector->clear();
$this->assertTrue($this->vector->isEmpty());
}
public function testPush () : void {
$this->vector->push(6);
$this->assertEquals([1, 2, 3, 4, 5, 6], $this->vector->toArray());
}
public function testAppend () : void {
$this->vector->append([6, 7, 8]);
$this->assertEquals([1, 2, 3, 4, 5, 6, 7 ,8], $this->vector->toArray());
}
public function testUpdate () : void {
$this->vector->update([5, 5, 5, 6, 7, 8]); // 5 already exists
$this->assertEquals([1, 2, 3, 4, 5, 6, 7 ,8], $this->vector->toArray());
}
public function testMap () : void {
$actual = $this->vector
->map(function ($x) { return $x * $x; })
->toArray();
$this->assertEquals([1, 4, 9, 16, 25], $actual);
}
public function testMapKeys () : void {
$vector = new Vector(["foo", "bar", "quux", "xizzy"]);
$filter = function ($key) {
return 0; // Let's collapse our array
};
$actual = $vector->mapKeys($filter)->toArray();
$this->assertEquals(["xizzy"], $actual);
}
public function testFlatMap () : void {
$expected = [
// Squares and cubes
1, 1,
4, 8,
9, 27,
16, 64,
25, 125
];
$callback = function ($n) {
yield $n * $n;
yield $n * $n * $n;
};
$actual = $this->vector->flatMap($callback)->toArray();
$this->assertEquals($expected, $actual);
}
public function testFlatMapWithKeyValueCallback() : void {
$vector = new Vector(["foo", "bar", "quux", "xizzy"]);
$callback = function (int $key, string $value) {
yield "$key::$value";
yield "$value ($key)";
};
$expected = [
"0::foo",
"foo (0)",
"1::bar",
"bar (1)",
"2::quux",
"quux (2)",
"3::xizzy",
"xizzy (3)",
];
$actual = $vector->flatMap($callback)->toArray();
$this->assertEquals($expected, $actual);
}
public function testFlatMapWithCallbackWithoutArgument() : void {
$this->expectException(InvalidArgumentException::class);
$callback = function () {};
$this->vector->flatMap($callback);
}
+ public function testMapToHashMap () : void {
+ $expected = [
+ 1 => 1,
+ 2 => 4,
+ 3 => 9,
+ 4 => 16,
+ 5 => 25,
+ ];
+
+ $fn = fn($value) => [$value, $value * $value];
+ $map = $this->vector->mapToHashMap($fn);
+
+ $this->assertInstanceOf(HashMap::class, $map);
+ $this->assertEquals($expected, $map->toArray());
+ }
+
+ public function testMapToHashMapWithCallbackWithoutArgument() : void {
+ $this->expectException(InvalidArgumentException::class);
+
+ $callback = function () {};
+ $this->vector->mapToHashMap($callback);
+ }
+
+ public function testMapToHashMapWithBadCallback () : void {
+ $this->expectException(InvalidArgumentException::class);
+
+ $callback = fn($key, $value) : bool => false; // not an array
+
+ $this->vector->mapToHashMap($callback);
+ }
+
+
public function testFilter () : void {
$vector = new Vector(["foo", "bar", "quux", "xizzy"]);
$filter = function ($item) {
return strlen($item) === 3; // Let's keep 3-letters words
};
$actual = $vector->filter($filter)->toArray();
$this->assertEquals(["foo", "bar"], $actual);
}
public function testFilterWithBadCallback () : void {
$this->expectException(InvalidArgumentException::class);
$badFilter = function () {};
$this->vector->filter($badFilter);
}
public function testFilterKeys () : void {
$filter = function ($key) {
return $key % 2 === 0; // Let's keep even indices
};
$actual = $this->vector
->filterKeys($filter)
->toArray();
$this->assertEquals([0, 2, 4], array_keys($actual));
}
public function testChunk () : void {
$vector = new Vector([1, 2, 3, 4, 5, 6]);
$this->assertEquals(
[[1, 2], [3, 4], [5, 6]],
$vector->chunk(2)->toArray()
);
}
public function testSlice () : void {
$actual = $this->vector->slice(2, 3);
$this->assertEquals([3, 4, 5], $actual->toArray());
}
public function testImplode() : void {
$actual = (new Vector(["a", "b", "c"]))
->implode(".")
->__toString();
$this->assertEquals("a.b.c", $actual);
}
public function testImplodeWithoutDelimiter() : void {
$actual = (new Vector(["a", "b", "c"]))
->implode("")
->__toString();
$this->assertEquals("abc", $actual);
}
public function testExplode() : void {
$actual = Vector::explode(".", "a.b.c");
$this->assertEquals(["a", "b", "c"], $actual->toArray());
}
public function testExplodeWithoutDelimiter() : void {
$actual = Vector::explode("", "a.b.c");
$this->assertEquals(["a.b.c"], $actual->toArray());
}
///
/// n-grams
///
public function testBigrams() : void {
$expected = Vector::from([
[1, 2],
[2, 3],
[3, 4],
[4, 5],
]);
$this->assertEquals($expected, $this->vector->bigrams());
}
public function testTrigrams() : void {
$expected = Vector::from([
[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
]);
$this->assertEquals($expected, $this->vector->trigrams());
}
public function testNgrams() : void {
$expected = Vector::from([
[1, 2, 3, 4],
[2, 3, 4, 5],
]);
$this->assertEquals($expected, $this->vector->ngrams(4));
}
public function testNgramsWithN1 () : void {
$expected = Vector::from([
[1],
[2],
[3],
[4],
[5],
]);
$this->assertEquals($expected, $this->vector->ngrams(1));
}
private function provideLowN () : iterable {
yield [0];
yield [-1];
yield [PHP_INT_MIN];
}
/**
* @dataProvider provideLowN
*/
public function testNgramsWithTooLowN ($n) : void {
$this->expectException(InvalidArgumentException::class);
$this->vector->ngrams($n);
}
private function provideLargeN () : iterable {
yield [5];
yield [6];
yield [PHP_INT_MAX];
}
/**
* @dataProvider provideLargeN
*/
public function testNgramsWithTooLargeN ($n) : void {
$expected = Vector::from([
[1, 2, 3, 4, 5],
]);
$this->assertEquals($expected, $this->vector->ngrams($n));
}
///
/// ArrayAccess
///
public function testArrayAccessFailsWithStringKey () : void {
$this->expectException(InvalidArgumentException::class);
$this->vector["foo"];
}
public function testOffsetExists () : void {
$this->assertTrue(isset($this->vector[0]));
$this->assertFalse(isset($this->vector[8]));
}
public function testOffsetSetWithoutOffset () : void {
$this->vector[] = 6;
$this->assertEquals(6, $this->vector[5]);
}
public function testOffsetSet () : void {
$this->vector[0] = 9;
$this->assertEquals(9, $this->vector[0]);
}
public function testOffsetUnset () : void {
unset($this->vector[2]);
$expected = [
0 => 1,
1 => 2,
// vector[2] has been unset
3 => 4,
4 => 5,
];
$this->assertEquals($expected, $this->vector->toArray());
}
///
/// IteratorAggregate
///
public function testGetIterator () : void {
$this->assertEquals([1, 2, 3, 4, 5], iterator_to_array($this->vector));
}
///
/// WithCollection trait
///
public function testFirst () : void {
$this->assertEquals(1, $this->vector->first());
}
public function testFirstWhenEmpty () : void {
$vector = new Vector;
$this->expectException(OutOfRangeException::class);
$vector->first();
}
public function testFirstOr () : void {
$this->assertEquals(1, $this->vector->firstOr(2));
}
public function testFirstOrWhenEmpty () : void {
$vector = new Vector;
$this->assertEquals(2, $vector->firstOr(2));
}
}

File Metadata

Mime Type
text/x-diff
Expires
Mon, Nov 25, 03:12 (21 h, 13 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2259420
Default Alt Text
(20 KB)

Event Timeline