diff --git a/README.md b/README.md index 17cbf88..485196b 100644 --- a/README.md +++ b/README.md @@ -269,6 +269,7 @@ will return: values walk where +with zip @@ -328,6 +329,7 @@ will return: * [set()](#set) : Overwrites or adds an element * [union()](#union) : Adds the elements without overwriting existing ones * [unshift()](#unshift) : Adds an element at the beginning +* [with()](#with) : Returns a copy and sets an element ### Aggregate @@ -5814,6 +5816,37 @@ Map::from( [ ``` +### with() + +Returns a copy of the map with the element at the given index replaced with the given value. + +```php +public function with( $key, $value ) : self +``` + +* @param **int|string** `$key` Array key to set or replace +* @param **mixed** `$value` New value for the given key +* @return **self<int|string,mixed>** New map of the values + +The original map stays untouched! This method is a shortcut for calling the +[copy()](#copy) and [set()](#set) methods. + +**Examples:** + +```php +$m = Map::from( ['a' => 1] ); + +$m->with( 2, 'b' ); +// ['a' => 1, 2 => 'b'] + +$m->with( 'a', 2 ); +// ['a' => 2] + +$m->all(); +// ['a' => 1] +``` + + ### zip() Merges the values of all arrays at the corresponding index. diff --git a/src/Map.php b/src/Map.php index 450a717..e97c4a8 100644 --- a/src/Map.php +++ b/src/Map.php @@ -5359,13 +5359,38 @@ public function where( string $key, string $op, $value ) : self } + /** + * Returns a copy of the map with the element at the given index replaced with the given value. + * + * Examples: + * $m = Map::from( ['a' => 1] ); + * $m->with( 2, 'b' ); + * $m->with( 'a', 2 ); + * + * Results: + * ['a' => 1, 2 => 'b'] + * ['a' => 2] + * + * The original map ($m) stays untouched! + * This method is a shortcut for calling the copy() and set() methods. + * + * @param int|string $key Array key to set or replace + * @param mixed $value New value for the given key + * @return self New map + */ + public function with( $key, $value ) : self + { + return $this->copy()->set( $key, $value ); + } + + /** * Merges the values of all arrays at the corresponding index. * * Examples: * $en = ['one', 'two', 'three']; * $es = ['uno', 'dos', 'tres']; - * $m = new Map( [1, 2, 3] )->zip( $en, $es ); + * $m = Map::from( [1, 2, 3] )->zip( $en, $es ); * * Results: * [ diff --git a/tests/MapTest.php b/tests/MapTest.php index 21685d2..cd2c71e 100644 --- a/tests/MapTest.php +++ b/tests/MapTest.php @@ -3527,6 +3527,17 @@ public function testWherePath() } + public function testWith() + { + $m = Map::from( ['a' => 1] ); + + $this->assertEquals( ['a' => 1, 2 => 'b'], $m->with( 2, 'b' )->toArray() ); + $this->assertEquals( ['a' => 1], $m->toArray() ); + $this->assertEquals( ['a' => 2], $m->with( 'a', 2 )->toArray() ); + $this->assertEquals( ['a' => 1], $m->toArray() ); + } + + public function testZip() { $m = new Map( [1, 2, 3] );