Skip to content

Commit

Permalink
Merge pull request #159 from boesing/feature/orderedlist-prepend
Browse files Browse the repository at this point in the history
feature: add `OrderedListInterface#prepend`
  • Loading branch information
boesing authored May 29, 2022
2 parents ebc0130 + a8c980f commit 07dd20e
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/OrderedList.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use function array_slice;
use function array_udiff;
use function array_uintersect;
use function array_unshift;
use function array_values;
use function assert;
use function hash;
Expand Down Expand Up @@ -408,4 +409,12 @@ public function findFirstMatchingIndex(callable $filter): ?int

return null;
}

public function prepend($value): OrderedListInterface
{
$instance = clone $this;
array_unshift($instance->data, $value);

return $instance;
}
}
8 changes: 8 additions & 0 deletions src/OrderedListInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,4 +166,12 @@ public function jsonSerialize(): array;
* @return 0|positive-int|null
*/
public function findFirstMatchingIndex(callable $filter): ?int;

/**
* Adds an item at the beginning of the list.
*
* @param TValue $value
* @return OrderedListInterface<TValue>
*/
public function prepend($value): self;
}
12 changes: 12 additions & 0 deletions tests/GenericOrderedListTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1445,4 +1445,16 @@ public function testWillReturnNullWhenNoItemMatchesFilter(): void

self::assertNull($list->findFirstMatchingIndex(static fn (int $value) => $value % 2 !== 0));
}

public function testWillPrependValueToTheList(): void
{
/** @var OrderedListInterface<non-empty-string> $list */
$list = new GenericOrderedList([
'bar',
'baz',
]);

$list = $list->prepend('foo');
self::assertSame(['foo', 'bar', 'baz'], $list->toNativeArray());
}
}

0 comments on commit 07dd20e

Please sign in to comment.