diff --git a/src/Collections/IImmutableCollection.php b/src/Collections/IImmutableCollection.php index 7022274..7867f67 100644 --- a/src/Collections/IImmutableCollection.php +++ b/src/Collections/IImmutableCollection.php @@ -161,6 +161,25 @@ interface IImmutableCollection extends IteratorAggregate, JsonSerializable, Coun */ public static function split (string $value, string $separator): static; + /** + * 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 + */ + public static function fill (int $size, $value): static; + /** + * 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 + */ + public static function fillWithKeys (IImmutableCollection $keys, $value): static; + /** * Merge the current collection with one or multiple collections * diff --git a/src/Collections/ImmutableCollection.php b/src/Collections/ImmutableCollection.php index 4dc51b9..fc8bc1c 100644 --- a/src/Collections/ImmutableCollection.php +++ b/src/Collections/ImmutableCollection.php @@ -365,6 +365,28 @@ class ImmutableCollection implements IImmutableCollection { return new static (explode($separator, $value)); } + /** + * @inheritDoc + */ + public static function fill (int $size, $value): static { + $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): static { + $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