iteratee
util
Creates a function that invokes the predicate at the path of a given object.
Installation
Import
import { iteratee } from '@tulx/utils';Source Code
Implementation
/**
* Creates a function that invokes the predicate at the path of a given object.
*
* @param func - The value to convert to a callback.
* @returns Returns the callback.
*
* @example
* ```ts
* const users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
* map(users, iteratee('user')); // ['barney', 'fred']
* ```
*/
export function iteratee<T>(
func: ((value: T) => unknown) | string | Record<string, unknown>
): (value: T) => unknown {
if (typeof func === 'function') {
return func;
}
if (typeof func === 'string') {
return (value: T) => (value as Record<string, unknown>)[func];
}
if (typeof func === 'object' && func !== null) {
return (value: T) => {
for (const key in func) {
if (Object.prototype.hasOwnProperty.call(func, key)) {
if ((value as Record<string, unknown>)[key] !== func[key]) {
return false;
}
}
}
return true;
};
}
return identity;
}
function identity<T>(value: T): T {
return value;
}
Example
import { iteratee } from '@tulx/utils';
const users = [
{ 'user': 'barney' },
{ 'user': 'fred' }
];
map(users, iteratee('user')); // ['barney', 'fred']Related Functions
attempt
Attempts to invoke func, returning either the result or the caught error object.
bindAll
Binds methods of an object to the object itself, overwriting the existing method.
cond
Creates a function that iterates over pairs and invokes the corresponding function of the first predicate to return truthy.
conforms
Creates a function that invokes the predicate properties of source with the corresponding property values of a given object.
constant
Creates a function that returns value.
defaultTo
Checks value to determine whether a default value should be returned in its place.