From 8a8203a086653dd1a1219d733340d15b933827e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lajos=20M=C3=A9sz=C3=A1ros?= Date: Tue, 20 Jul 2021 14:10:43 +0200 Subject: [PATCH] Added A::without() --- README.md | 25 +++++++++++++++++++++++++ src/A.php | 14 +++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a3d615e..f00443a 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,12 @@ A::isAssoc(["x" => 10, "y" => 20]); // true
A::sum + #### adds up the numbers in the given array and returns the sum + +```php +A::sum([1, 2, 3, 4, 5]); // 15 +``` +
@@ -556,6 +562,25 @@ A::concat([1, 2], 3, [4, 5]); // [1, 2, 3, 4, 5]
+
+ A::without + + #### removes items from the second array by values in the first array. if first value is not an array, then it is transformed into one + +```php +A::without([1, 3], [1, 2, 3, 4, 5]); // [2, 4, 5] +``` + +```php +A::without(['a' => 12], [1, 2, 3, 4, ['a' => 12]]); // [1, 2, 3, 4] +``` + +```php +A::without(['t'], ['t', 'f', 'f', 't', 'f']); // ['f', 'f', 'f'] +``` + +
+ ### String > Most string operations come with an optional 3rd parameter called $caseSensitivity, diff --git a/src/A.php b/src/A.php index 1d8db48..f7f3823 100644 --- a/src/A.php +++ b/src/A.php @@ -65,7 +65,7 @@ public static function keys(array $data): array return array_keys($data); } - // A::values([3, 6, 7]) -> [3, 6, 7] + // A::values([1 => 3, 3 => 6, 4 => 7]) -> [3, 6, 7] public static function values(array $data): array { return array_values($data); @@ -359,4 +359,16 @@ public static function zipObj(array $keys, array $values): object { $_keys = self::filter(fn($key) => array_key_exists($key, $keys) && array_key_exists($key, $values), $_keys); return self::reduce(fn($result, $key) => O::assoc($keys[$key], $values[$key], $result), new stdClass(), $_keys); } + + // A::without([1, 3], [1, 2, 3, 4, 5]) -> [2, 4, 5] + public static function without($excludedItems, array $values): array { + return self::values(self::reduce(function($values, $excludedItem) { + if (self::includes($excludedItem, $values)) { + $index = self::findIndex(fn($value) => $value === $excludedItem, $values); + unset($values[$index]); + } + + return $values; + }, $values, self::ensureArray($excludedItems))); + } }