From c0c03b9cae090cffdb8c6beee37ebc59e9828955 Mon Sep 17 00:00:00 2001 From: Julien Rosset Date: Fri, 29 Sep 2023 12:44:28 +0200 Subject: [PATCH] Add IImmutableCollection::fill and IImmutableCollection::fillWithKeys --- src/Collections/IImmutableCollection.php | 23 +++++++++++++++++++++++ src/Collections/ImmutableCollection.php | 22 ++++++++++++++++++++++ tests/test.php | 8 +++++++- 3 files changed, 52 insertions(+), 1 deletion(-) diff --git a/src/Collections/IImmutableCollection.php b/src/Collections/IImmutableCollection.php index 48b76b2..c2eb358 100644 --- a/src/Collections/IImmutableCollection.php +++ b/src/Collections/IImmutableCollection.php @@ -178,6 +178,29 @@ interface IImmutableCollection extends IteratorAggregate, JsonSerializable, Seri */ public static function split (string $value, string $separator); + /** + * Create a collection filled with the same element + * + * @param int $size The collection size + * @param TValue $value The value to fill the collection + * + * @return static The result collection + * + * @noinspection PhpMissingReturnTypeInspection + */ + public static function fill (int $size, $value); + /** + * Create a collection filled with the same element, using a list of keys + * + * @param IImmutableCollection $keys The list of keys + * @param TValue $value The value to fill the collection + * + * @return static The result collection + * + * @noinspection PhpMissingReturnTypeInspection + */ + public static function fillWithKeys (IImmutableCollection $keys, $value); + /** * Merge the current collection with one or multiple collections * diff --git a/src/Collections/ImmutableCollection.php b/src/Collections/ImmutableCollection.php index 29f9d8a..d881f32 100644 --- a/src/Collections/ImmutableCollection.php +++ b/src/Collections/ImmutableCollection.php @@ -375,6 +375,28 @@ class ImmutableCollection implements IImmutableCollection { return new static (explode($separator, $value)); } + /** + * @inheritDoc + */ + public static function fill (int $size, $value) { + $keys = new ImmutableCollection(); + for ($curr = 0; $curr < $size; $curr++) { + $keys->_add($curr); + } + + return static::fillWithKeys($keys, $value); + } + /** + * @inheritDoc + */ + public static function fillWithKeys (IImmutableCollection $keys, $value) { + $collection = new static(); + foreach ($keys as $key) { + $collection->_set($key, $value); + } + return $collection; + } + /** * @inheritDoc */ diff --git a/tests/test.php b/tests/test.php index 6d404ab..a48e0d4 100644 --- a/tests/test.php +++ b/tests/test.php @@ -1,5 +1,6 @@ add(28); -echo 'Size : ' . $collection->count() . PHP_EOL; \ No newline at end of file +echo 'Size : ' . $collection->count() . PHP_EOL; + +echo 'Fill :' . PHP_EOL; +foreach (ImmutableCollection::fill(5, -1) as $key => $value) { + echo "\t#" . $key . ' = ' . $value . PHP_EOL; +} \ No newline at end of file