|
| 1 | +# *KV combinators |
| 2 | + |
| 3 | +- #### Map |
| 4 | + |
| 5 | +Before v5 `Fp\Collections\Map` used `Fp\Collections\Entry` to represents kv pair. |
| 6 | +It was unfriendly for ide (lack autocompletion ability). |
| 7 | + |
| 8 | +Since v5 `Fp\Collections\Entry` has been removed. Instead, each method of `Fp\Collections\Map` has *KV version: |
| 9 | + |
| 10 | +```php |
| 11 | +<?php |
| 12 | + |
| 13 | +use Fp\Collections\HashMap; |
| 14 | + |
| 15 | +/** |
| 16 | + * @param HashMap<int, int> $hashMap |
| 17 | + * @return HashMap<int, int> |
| 18 | + */ |
| 19 | +function addOne(HashMap $hashMap): HashMap |
| 20 | +{ |
| 21 | + return $hashMap->map(fn(int $value) => $value + 2); |
| 22 | +} |
| 23 | + |
| 24 | +/** |
| 25 | + * @param HashMap<int, int> $hashMap |
| 26 | + * @return HashMap<int, int> |
| 27 | + */ |
| 28 | +function sumWithKeys(HashMap $hashMap): HashMap |
| 29 | +{ |
| 30 | + return $hashMap->mapKV(fn(int $key, int $value) => $key + $value); |
| 31 | +} |
| 32 | +``` |
| 33 | + |
| 34 | +This makes sense since the key and value are rarely needed at the same time. |
| 35 | + |
| 36 | +- #### Functions |
| 37 | + |
| 38 | +Regular functions has *KV combinators too: |
| 39 | + |
| 40 | +```php |
| 41 | +<?php |
| 42 | + |
| 43 | +use Fp\Collections\HashMap; |
| 44 | + |
| 45 | +use function Fp\Collection\map; |
| 46 | +use function Fp\Collection\mapKV; |
| 47 | + |
| 48 | +/** |
| 49 | + * @param array<int, int> $hashMap |
| 50 | + * @return array<int, int> |
| 51 | + */ |
| 52 | +function addOne(HashMap $hashMap): HashMap |
| 53 | +{ |
| 54 | + return map($hashMap, fn(int $value) => $value + 2); |
| 55 | +} |
| 56 | + |
| 57 | +/** |
| 58 | + * @param array<int, int> $hashMap |
| 59 | + * @return array<int, int> |
| 60 | + */ |
| 61 | +function sumWithKeys(array $hashMap): HashMap |
| 62 | +{ |
| 63 | + return mapKV($hashMap, fn(int $key, int $value) => $key + $value); |
| 64 | +} |
| 65 | +``` |
0 commit comments