cloneWith
lang
This method is like clone except that it accepts customizer which is invoked to produce the cloned value.
Installation
Import
import { cloneWith } from '@tulx/utils';Source Code
Implementation
/**
* This method is like clone except that it accepts customizer which is invoked to produce the cloned value.
*
* @param value - The value to clone.
* @param customizer - The function to customize cloning.
* @returns Returns the cloned value.
*
* @example
* ```ts
* function customizer(value: unknown) {
* if (typeof value === 'string') {
* return value.toUpperCase();
* }
* }
* const cloned = cloneWith({ 'a': 'hello' }, customizer);
* // { 'a': 'HELLO' }
* ```
*/
export function cloneWith<T>(
value: T,
customizer?: (value: unknown) => unknown
): T {
if (customizer) {
const result = customizer(value);
if (result !== undefined) {
return result as T;
}
}
if (value === null || typeof value !== 'object') {
return value;
}
if (Array.isArray(value)) {
return [...value] as T;
}
return { ...value } as T;
}
Example
import { cloneWith } from '@tulx/utils';
function customizer(value: unknown) {
if (typeof value === 'string') {
return value.toUpperCase();
}
}
const cloned = cloneWith({ 'a': 'hello' }, customizer);
// { 'a': 'HELLO' }Related Functions
castArray
Casts value as an array if it's not one.
clone
Creates a shallow clone of value.
cloneDeep
This method is like clone except that it recursively clones value.
cloneDeepWith
This method is like cloneDeep except that it accepts customizer which is invoked to produce the cloned value.
conformsTo
Checks if object conforms to source by invoking the predicate properties of source with the corresponding property values of object.
eq
Performs a SameValueZero comparison between two values to determine if they are equivalent.