miroshnikov / idles
A PHP functional utility library, port of Lodash/Ramda with lazy (idle) evaluation
Installs: 176
Dependents: 1
Suggesters: 0
Security: 0
Stars: 11
Watchers: 3
Forks: 1
Open Issues: 0
pkg:composer/miroshnikov/idles
Requires
- php: >=8.4
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.92
- pestphp/pest: ^4.2
- phpstan/phpstan: ^2.1
- squizlabs/php_codesniffer: ^4.0
README
IDLES - a PHP functional library
A PHP functional utility library, port of Javascript Lodash/Fp and Ramda libraries to PHP.
All functions are side-effect free and automatically curried, data is immutable.
The iterable collection parameter is usually supplied last to make currying convenient.
Lazy / delayed evaluation is supported in functional pipelines.
Go to https://idlephp.tech for more details, documentation and examples.
Requirements
PHP 8.4 or higher
Installation
composer require miroshnikov/idles
Roadmap
Note
Idles is currently under active development. Roadmap is to add all methods from Lodash and Ramda libraries and some functional tools.
Documentation
add
add($a, $b)
Calculates the sum of two numbers.
all
all($predicate, $collection)
Checks if $predicate returns truthy for all elements of $collection. Stop once it returns falsey.
allPass
allPass($predicates)
Returns a function that checks if its arguments pass all $predicates.
always
always($value)
Returns a function that always returns the given value.
any
any($predicate, $collection)
Checks if $predicate returns truthy for any element of $collection. Stops on first found.
anyPass
anyPass($predicates)
Returns a function that checks if its arguments pass any of the $predicates.
apply
apply($fn, $args)
Calls $fn(...$args)
applyTo
applyTo($value, $interceptor)
Returns the result of $interceptor($value).
ary
ary($n, $fn)
Creates a function that invokes $fn, with up to $n arguments, ignoring any additional arguments.
ascend
ascend($fn, $a, $b)
Makes an ascending comparator function out of a function that returns a value that can be compared with <=>.
attempt
attempt($fn, $args)
Calls $fn, returning either the result or the caught exception.
both
both($fn1, $fn2)
Resulting function returns $fn1(...$args) if it is falsy or $fn2(...$args) otherwise, short-circuited.
camelCase
camelCase($s)
Converts string to camel case.
capitalize
capitalize($string)
Converts the first character of string to upper case and the remaining to lower case.
collect
collect($collection)
Collects any iterable into array
compose
compose(...$fns)
Like pipe but invokes the functions from right to left.
concat
concat($iterable, $value)
Concatinates an iterable with an iterable/value.
concatAll
concatAll($values)
Concatinates an iterable with additional iterables/values
cond
cond($pairs)
Iterates over $pairs and invokes the corresponding function of the first predicate to return truthy.
count
count($predicate, $collection)
Counts the number of items in $collection matching the $predicate
countBy
countBy($iteratee, $collection)
Returns an array<result of $iteratee($value), number of times the $iteratee($value) was found in $collection>
curry
curry($fn)
\Idles\_ const may be used as a placeholder.
curryN
curryN($arity, $fn)
Curry with fixed arity. \Idles\_ const may be used as a placeholder.
curryRight
curryRight($f)
Like curry but arguments are prepended.
curryRightN
curryRightN($arity, $f)
Like curryN but arguments are prepended.
dec
dec($number)
Returns $number - 1
defaultTo
defaultTo($default, $value)
Returns the first argument if it is truthy, otherwise the second argument.
descend
descend($fn, $a, $b)
Makes an descending comparator function out of a function that returns a value that can be compared with <=>.
divide
divide($a, $b)
Returns $a / $b
drop
drop($n, $collection)
Skips the first $n elemens and returns the rest of iterable or string.
dropLast
dropLast($n, $collection)
Skips the last $n elements of iterable or string.
each
each($iteratee, $collection)
Iterates over elements of $collection. Iteratee may exit iteration early by returning false.
either
either($fn1, $fn2)
Resulting function returns $fn1(...$args) if it is truthy or $fn2(...$args) otherwise, short-circuited.
eq
eq($a, $b)
$a == $b
equals
equals($a, $b)
$a === $b
escapeRegExp
escapeRegExp($s)
Escapes regular expression.
evolve
evolve($transformations, $record)
Creates a new record by recursively calling transformation functions with $record properties.
F
F(...$args)
Always returns false
filter
filter($predicate, $collection)
Returns elements $predicate returns truthy for.
find
find($predicate, $collection)
Returns the first element $predicate returns truthy for.
findFrom
findFrom($predicate, $fromIndex, $collection)
Returns the first element $predicate returns truthy for starting from $fromIndex.
findIndex
findIndex($predicate, $collection)
Returns the index of the first element predicate returns truthy for or -1 if not found.
findIndexFrom
findIndexFrom($predicate, $fromIndex, $collection)
Returns the index of the first element $predicate returns truthy for starting from $fromIndex.
findLastIndex
findLastIndex($predicate, $collection)
Returns the index of the last element predicate returns truthy for, -1 if not found.
findLastIndexFrom
findLastIndexFrom($predicate, $fromIndex, $collection)
Returns the index of the last element $predicate returns truthy for starting from $fromIndex.
flatMap
flatMap($iteratee, $collection)
Maps and flattens.
flatMapDepth
flatMapDepth($iteratee, $depth, $collection)
Maps and flattens the mapped results up to $depth times.
flatten
flatten($collection)
Flattens iterable a single level deep.
flattenDepth
flattenDepth($depth, $collection)
Recursively flatten array up to $depth times.
flip
flip($fn)
Returns a new curried function with the first two arguments reversed.
flow
flow($funcs)
Left-to-right function composition. The first argument may have any arity; the remaining arguments must be unary.
fromPairs
fromPairs($collection)
Creates a new record from a list key-value pairs. The inverse of toPairs.
groupBy
groupBy($iteratee, $collection)
Creates an array composed of keys generated from running each value through $iteratee.
gt
gt($a, $b)
$a > $b
gte
gte($a, $b)
$a >= $b
has
has($key, $record)
Checks if $record has $key.
hasPath
hasPath($path, $record)
Checks if $path exists in $record.
head
head($collecton)
Gets the first element of $collecton.
identity
identity($value)
Returns the first argument it receives.
ifElse
ifElse($predicate, $onTrue, $onFalse)
Resulting function returns $onTrue(...$args) if $predicate(...$args) is truthy or $onFalse(...$args) otherwise.
inc
inc($number)
Returns $number + 1
includes
includes($value, $collection)
Checks if $value is in iterable/string.
includesFrom
includesFrom($value, $fromIndex, $collection)
Checks if $value is in iterable/string, starting from $fromIndex.
indexBy
indexBy($iteratee, $collection)
Creates a record composed of keys generated from the results of running each element of $collection through $iteratee.
indexOf
indexOf($item, $collection)
Returns the index of the first occurrence of the item in an iterable or string, else -1.
indexOfFrom
indexOfFrom($item, $fromIndex, $collection)
Returns the index of the first occurrence of the item in an iterable or string, starting from $fromIndex, else -1.
intersection
intersection($array1, $array2)
Returns unique values that are included in both arrays.
intersectionBy
intersectionBy($iteratee, $array1, $array2)
Like intersection but invokes $iteratee for each element before comparison.
intersectionWith
intersectionWith($comparator, $array1, $array2)
Like intersection but invokes $comparator to compare elements.
invert
invert($collection)
Replaces keys with values. Duplicate keys are overwritten.
iterate
iterate($fn, $value)
Returns a generator of $value, $f($value), $f($f($value)) etc.
join
join($separator, $collection)
Joins iterable elements separated by $separator.
just
just($value)
Returns an Optional with the specified non-null value
juxt
juxt($iteratees)
Applies a list of functions to a list of values.
keys
keys($record)
Returns an indexed iterable of keys in $record.
last
last($collecton)
Gets the last element of iterable.
lastIndexOf
lastIndexOf($item, $collection)
Returns the index of the last occurrence of $value in iterable or string, else -1.
length
length($value)
Returns size of a countable, number of parameters of a function, lenght of string or number of properties of an object.
lt
lt($a, $b)
$a < $b
lte
lte($a, $b)
$a <= $b
map
map($iteratee, $collection)
Run each element in $collection through $iteratee.
memoize
memoize($fn)
Creates a function that memoizes the result of $fn.
memoizeWith
memoizeWith($resolver, $fn)
Creates a function that memoizes the result of $fn. $resolver returns map cache key (args[0] by default).
merge
merge($left, $right)
Merges properties, numeric keys are replaced.
mergeAll
mergeAll($iterables)
Merges properties, numeric keys are replaced.
mergeDeep
mergeDeep($left, $right)
Merges properties recursively, numeric keys are replaced.
mergeWith
mergeWith($customizer, $left, $right)
Like merge but if a key exists in both records, $customizer is called to the values associated with the key.
modifyPath
modifyPath($path, $updater, $record)
Creates new record by applying an $updater function to the value at the given $path.
modulo
modulo($a, $b)
$a % $b
multiply
multiply($a, $b)
$a * $b
negate
negate($predicate)
Creates a function that negates the result of the $predicate function.
not
not($a)
returns !$a
nothing
nothing()
Returns an empty Optional.
now
now()
Returns the timestamp of the number of seconds
nth
nth($offset, $collection)
Returns the $offset element. If $offset is negative the element at index length + $offset is returned.
nthArg
nthArg($n)
Returns a function which returns its $nth argument.
objOf
objOf($key, $value)
Creates an array containing a single key => value pair.
omit
omit($keys, $collection)
The opposite of pick. Returns record without $keys.
omitBy
omitBy($predicate, $collection)
The opposite of pickBy. Returns properties of $record that $predicate returns falsey for.
once
once($fn)
$fn is only called once, the first value is returned in subsequent invocations.
Optional
interface Optional { /** * @return bool true if not empty */ public function isPresent(): bool; /** * @return bool true if empty */ public function isEmpty(): bool; /** * Returns value, throw exception if empty */ public function get(): mixed; /** * Returns the contained value if the optional is nonempty or `$default` */ public function orElse(mixed $default): mixed; /** * Returns the contained value, if present, otherwise throw an exception */ public function orElseThrow(\Exception $e = new \Exception('No value on None')): mixed; /** * If a value is present, apply the `$fn` to it, and if the result is non-null, return an Optional describing the result */ public function map(callable $fn): Optional; /** * Use instead of map if $f returns Optional */ public function flatMap(callable $fn): Optional; /** * If a value is present and matches the `$predicate`, return an Optional with the value, otherwise an empty Optional. */ public function filter(callable $predicate): Optional; }
Maybe/Option monad (container) which may or may not contain a non-null value.
orderBy
orderBy($iteratees, $orders, $collection)
Like sortBy but allows specifying the sort orders.
partial
partial($fn, $partials)
Creates a function that invokes $fn with $partials prepended to the arguments. \Idles\_ const may be used as a placeholder.
partialRight
partialRight($fn, $partials)
Like partial but $partials are appended.
partition
partition($predicate, $collection)
Split $collection into two groups, the first of which contains elements $predicate returns truthy for, the second of which contains elements $predicate returns falsey for.
path
path($path, $collection)
Retrieve the value at a given path.
pathOr
pathOr($default, $path, $collection)
Retrieve the value at a given path. If path is not found, the $default is returned.
paths
paths($paths, $collection)
Keys in, values out. Order is preserved.
pick
pick($keys, $collection)
Returns record containing only $keys.
pickBy
pickBy($predicate, $collection)
Returns record containing only keys $predicate returns truthy for.
pipe
pipe(...$fns)
Left-to-right function composition. The first argument may have any arity; the remaining arguments must be unary.
pluck
pluck($key, $collection)
Returns a new array by plucking the same named property off all records in the array supplied.
project
project($props, $collection)
Like SQL select statement.
prop
prop($key, $record)
Return the specified property.
propEq
propEq($key, $value, $record)
Returns $record[$key] == $value
propOr
propOr($default, $key, $record)
Return the $key property or $default.
rearg
rearg($indexes, $fn)
Returns a curried function that invokes $fn with arguments rearranged according to $indexes.
reduce
reduce($iteratee, $accumulator, $collection)
Reduces $collection to a value which is the accumulated result of running each element in collection through $iteratee.
remove
remove($start, $count, $iterable)
Removes items from $iterable starting at $start and containing $count elements.
resolve
resolve($resolvers, $record)
Adds new properties to $record using $resolvers.
round
round($precision, $number)
Rounds $number to specified $precision
setPath
setPath($path, $value, $record)
Return copy of $record with $path set with $value.
slice
slice($start, $end, $collection)
Returns a slice of iterable or string from $start up to, but not including $end.
sort
sort($comparator, $collection)
Sorts $collection using $comparator comparison ($a <=> $b) function.
sortBy
sortBy($iteratees, $collection)
Sorts $collection in ascending order according to $comparators.
sortWith
sortWith($comparators, $collection)
Sorts a $collection according to an array of comparison ($a <=> $b) functions.
split
split($separator, $s)
Splits string by $separator regular expression.
splitAt
splitAt($index, $arrayOrString)
Splits a given array or string at a given index.
splitEvery
splitEvery($length, $arrayOrString)
Splits an array or string into slices of the specified length.
splitWhen
splitWhen($predicate, $iterable)
Splits an array by predicate.
splitWhenever
splitWhenever($predicate, $iterable)
Splits an array into slices on every occurrence of a value.
startsWith
startsWith($target, $s)
If string starts with $target.
subtract
subtract($a, $b)
$a - $b
sum
sum($collection)
Sums elements in $collection
sumBy
sumBy($iteratee, $collection)
Sums elements, $iteratee is invoked for each element in $collection to generate the value to be summed.
T
T(...$args)
Always returns true
take
take($n, $collection)
Takes $n first elements from iterable.
takeLast
takeLast($n, $collection)
Returns a slice of iterable with $n elements taken from the end.
tap
tap($interceptor, $value)
Calls $interceptor($value) then returns the original $value.
times
times($iteratee, $n)
Calls the iteratee $n times, returning an array of the results of each invocation.
toLower
toLower($s)
Converts string to lower case.
toPairs
toPairs($record)
Converts a record into an array of [$key, $value].
toUpper
toUpper($s)
Converts string to upper case.
trim
trim($characters, $string)
Strip characters from the beginning and end of a string.
trimEnd
trimEnd($characters, $string)
Strip characters from the end of a string.
trimStart
trimStart($characters, $string)
Strip characters from the beginning of a string.
tryCatch
tryCatch($tryer, $catcher, $value)
Calls $tryer, if it throws, calls $catcher.
unapply
unapply($fn)
Returns fn (...$args) => $fn($args)
unary
unary($fn)
ary(1, $fn)
uniq
uniq($collection)
Removes duplicates using ===.
uniqBy
uniqBy($iteratee, $collection)
Like uniq but apply $iteratee fist.
uniqWith
uniqWith($predicate, $collection)
Like uniq but uses $predicate to compare elements.
unless
unless($predicate, $whenFalse, $value)
Returns $predicate($value) ? $value : $whenFalse($value).
useWith
useWith($fn, $transformers)
Applies each transformer function to each argument. Returns a new curried functions.
values
values($collection)
Returns an indexed iterable of values in $collection.
when
when($predicate, $whenTrue, $value)
Returns $predicate($value) ? $whenTrue($value) : $value.
where
where($spec, $record)
Checks if $record satisfies the spec by invoking the $spec properties with the corresponding properties of $record.
whereAny
whereAny($spec, $record)
Checks if $record satisfies the spec by invoking the $spec properties with the corresponding properties of $record. Returns true if at least one of the predicates returns true.
whereEq
whereEq($spec, $test)
Check if the $test satisfies the $spec.
without
without($values, $collection)
Returns $iterable without $values.
words
words($pattern, $s)
Splits string into an array of its words.
zip
zip($a, $b)
Creates a new iterable out of the two supplied by pairing up equally-positioned items from both iterables.
zipAll
zipAll($iterables)
Same as zip but for many iterables.
zipWith
zipWith($iteratee, $a, $b)
Like zip except that it accepts $iteratee to specify how grouped values should be combined.