Add IImmutableCollection::fill and IImmutableCollection::fillWithKeys

master 3.4.0
Julien Rosset 2 years ago
parent 53f6062f97
commit 4da1264ad8

@ -161,6 +161,25 @@ interface IImmutableCollection extends IteratorAggregate, JsonSerializable, Coun
*/ */
public static function split (string $value, string $separator): static; 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<int, TValue> 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<TKey> $keys The list of keys
* @param TValue $value The value to fill the collection
*
* @return static<TKey, TValue> The result collection
*/
public static function fillWithKeys (IImmutableCollection $keys, $value): static;
/** /**
* Merge the current collection with one or multiple collections * Merge the current collection with one or multiple collections
* *

@ -365,6 +365,28 @@ class ImmutableCollection implements IImmutableCollection {
return new static (explode($separator, $value)); 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 * @inheritDoc
*/ */

@ -1,5 +1,6 @@
<?php <?php
use jrosset\Collections\ImmutableCollection;
use jrosset\Collections\InsensitiveCaseKeyCollection; use jrosset\Collections\InsensitiveCaseKeyCollection;
use jrosset\Collections\InsensitiveCaseKeyImmutableCollection; use jrosset\Collections\InsensitiveCaseKeyImmutableCollection;
@ -18,4 +19,9 @@ echo '-----' . PHP_EOL;
$collection = new InsensitiveCaseKeyCollection($readOnlyCollection); $collection = new InsensitiveCaseKeyCollection($readOnlyCollection);
$collection->add(28); $collection->add(28);
echo 'Size : ' . $collection->count() . PHP_EOL; echo 'Size : ' . $collection->count() . PHP_EOL;
echo 'Fill :' . PHP_EOL;
foreach (ImmutableCollection::fill(5, -1) as $key => $value) {
echo "\t#" . $key . ' = ' . $value . PHP_EOL;
}
Loading…
Cancel
Save