Skip to content

Commit

Permalink
feature: add OrderedListInterface#prepend
Browse files Browse the repository at this point in the history
This provides the ability of adding a value in front of the ordered list

Signed-off-by: Maximilian Bösing <2189546+boesing@users.noreply.github.com>
  • Loading branch information
boesing committed May 29, 2022
1 parent 0d574ff commit 5d0cac4
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 @@ -396,4 +397,12 @@ public function join(string $separator = ''): string
throw new RuntimeException('Could not join ordered list.', 0, $throwable);
}
}

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 @@ -155,4 +155,12 @@ public function toNativeArray(): array;
* @psalm-return list<TValue>
*/
public function jsonSerialize(): array;

/**
* 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 @@ -1422,4 +1422,16 @@ public function testWillJoinValuesWithSeperator(): void

self::assertSame('foo:bar:baz', $list->join(':'));
}

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 5d0cac4

Please sign in to comment.