Skip to content

Instantly share code, notes, and snippets.

@will1471
Created August 2, 2019 19:31
Show Gist options
  • Save will1471/b7f8752ab1f8462bc9a81a667acfd638 to your computer and use it in GitHub Desktop.
Save will1471/b7f8752ab1f8462bc9a81a667acfd638 to your computer and use it in GitHub Desktop.
Vector using psalm.dev template annotations.
<?php
/**
* @template T
*/
class ImmutableVector
{
/**
* @psalm-var T[]
*/
private $items;
/**
* @psalm-param T[] $items
*/
public function __construct(array $items)
{
$this->items = $items;
}
/**
* @template R
* @psalm-param callable(T):R $function
* @psalm-return ImmutableVector<R>
*/
public function map(callable $function): ImmutableVector
{
return new ImmutableVector(array_map($function, $this->items));
}
/**
* @psalm-param callable(T):bool $function
* @psalm-return ImmutableVector<T>
*/
public function filter(callable $function): ImmutableVector
{
return new ImmutableVector(array_filter($this->items, $function));
}
/**
* @pslam-param callable(T):void $function
* @psalm-return ImmutableVector<T>
*/
public function each(callable $function): self
{
foreach ($this->items as $item) {
$function($item);
}
return $this;
}
/**
* @template R
* @psalm-param callable(R,T):R $function
* @psalm-param R $start
* @psalm-return R
*/
public function reduce(callable $function, $start)
{
$tmp = $start;
foreach ($this->items as $item) {
$tmp = $function($tmp, $item);
}
return $tmp;
}
/**
* @psalm-return ImmutableVector<T>
*/
public function slice(int $from, int $to = -1): ImmutableVector
{
$index = 0;
$a = [];
foreach ($this->items as $item) {
if ($index >= $from && ($index < $to || $to === -1)) {
$a[] = $item;
} elseif ($index >= $to && $to >= 0) {
break;
}
$index++;
}
return new ImmutableVector($a);
}
/**
* @psalm-return ImmutableVector<T>
*/
public function take(int $amount): ImmutableVector
{
return $this->slice(0, $amount);
}
/**
* @psalm-return ImmutableVector<T>
*/
public function drop(int $amount): ImmutableVector
{
return $this->slice($amount);
}
/**
* @psalm-return T[]
*/
public function toArray(): array
{
return array_values($this->items);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment