diff --git a/README.md b/README.md index 74263ad..bebba47 100644 --- a/README.md +++ b/README.md @@ -132,7 +132,29 @@ Plain numeric arrays are handled best via the methods in A, while associative ar A::tail([1, 2, 3, 4, 5]) // -> [2, 3, 4, 5] ``` -- **filter** - +- **filter** - calls the given function on the elements of an array and returns every value where the function gave truthy value + + ```php + $numbers = [1, 2, 3, 4, 5, 6]; + + function isOdd($n){ + return $n % 2 === 0; + } + + A::filter('isOdd', $numbers); // [2, 4, 6] + ``` + +- **reject** - calls the given function on the elements of an array and removes every value where the function gave truthy value + + ```php + $numbers = [1, 2, 3, 4, 5, 6]; + + function isOdd($n){ + return $n % 2 === 0; + } + + A::reject('isOdd', $numbers); // [1, 3, 5] + ``` - **find** - calls the given function on the elements of an array and returns the value for the first match. if there's no match, it will return `null` diff --git a/src/A.php b/src/A.php index b7977bf..5a95826 100644 --- a/src/A.php +++ b/src/A.php @@ -260,7 +260,12 @@ public static function init(array $data): array { // A::filter(x => x % 2 == 0, [1, 2, 3, 4, 5]) -> [2, 4] public static function filter(callable $fn, array $data): array { - return A::values(array_filter($data, $fn)); + return self::values(array_filter($data, $fn)); + } + + public static function reject(callable $fn, array $data): array + { + return self::filter(fn($value) => !$fn($value), $data); } // A::find(x => x.a > 3, [['a' => 8], ['a' => 10]]) -> ['a' => 8] @@ -271,7 +276,7 @@ public static function find(callable $fn, array $data) // A::findLast(x => x.a > 3, [['a' => 8], ['a' => 10]]) -> ['a' => 10] public static function findLast(callable $fn, array $data) { - return self::find($fn, A::reverse($data)); + return self::find($fn, self::reverse($data)); } // A::findIndex(x => x.a === 10, [['a' => 8], ['a' => 10]]) -> 1 @@ -292,7 +297,7 @@ public static function findIndex(callable $fn, array $data): int { // A::findLastIndex(x => x.a > 3, [['a' => 8], ['a' => 10]]) -> 1 public static function findLastIndex(callable $fn, array $data): ?int { - return self::findIndex($fn, A::reverse($data)); + return self::findIndex($fn, self::reverse($data)); } // A::any(x => x.a === 10, [['a' => 8], ['a' => 10]]) -> true @@ -327,7 +332,7 @@ public static function pickRandom(array $data) // A::concat([1, 2], 3, [4, 5]) -> [1, 2, 3, 4, 5] public static function concat(...$args) { - return self::unnest(A::map(fn($arg) => self::ensureArray($arg),$args)); + return self::unnest(self::map(fn($arg) => self::ensureArray($arg),$args)); } // A::zipObj(['a', 'b'], [1, 2]) -> {a:1, b:2}