Skip to content

Utility Functions

A collection of general-purpose utility functions.

debounce

Creates a debounced function that delays invoking the provided function until after the specified wait time.

// Only executes the callback after 300ms have passed without it being called again
const debouncedSearch = debounce((query) => {
console.log(`Searching for: ${query}`);
// Perform search operation
}, 300);
// Call this as often as needed
searchInput.addEventListener('input', (e) => {
debouncedSearch(e.target.value);
});

memoize

Creates a function that memoizes the result of a function call.

// Compute fibonacci numbers (expensive operation)
const fibonacci = (n: number): number => {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
};
// Create a memoized version
const memoizedFib = memoize(fibonacci);
console.time('First call');
memoizedFib(40); // This will take some time
console.timeEnd('First call');
console.time('Second call');
memoizedFib(40); // This will be instant
console.timeEnd('Second call');

retry

Retries a function until it succeeds or reaches the maximum number of attempts.

// Function that might fail
const fetchData = async () => {
const random = Math.random();
if (random < 0.7) {
throw new Error('Failed to fetch data');
}
return { data: 'Success!' };
};
// Retry the function
retry(fetchData, {
maxAttempts: 5,
delay: 1000,
onRetry: (error, attempt) => {
console.log(`Attempt ${attempt} failed: ${error.message}. Retrying...`);
}
})
.then(result => console.log('Success:', result))
.catch(error => console.error('All retries failed:', error));

clone

Creates a shallow clone of a value.

const original = { name: 'John', age: 30, hobbies: ['reading', 'gaming'] };
const cloned = clone(original);
console.log(cloned); // { name: 'John', age: 30, hobbies: ['reading', 'gaming'] }
// It's a shallow clone
console.log(cloned === original); // false
console.log(cloned.hobbies === original.hobbies); // true
// Works with various data types
clone(new Date()); // Date object
clone(new Map()); // Map object
clone(new Set()); // Set object
clone(/abc/g); // RegExp object
clone(new Int32Array([1, 2, 3])); // TypedArray

cloneDeep

Creates a deep clone of a value.

const original = {
name: 'John',
address: {
city: 'New York',
country: 'USA'
},
hobbies: ['reading', 'gaming']
};
const cloned = cloneDeep(original);
console.log(cloned); // Deep copy of the original
// It's a deep clone
console.log(cloned === original); // false
console.log(cloned.address === original.address); // false
console.log(cloned.hobbies === original.hobbies); // false
// Works with nested structures
const complex = {
date: new Date(),
regex: /test/g,
map: new Map([['key', 'value']]),
set: new Set([1, 2, 3]),
array: [1, 2, { nested: true }],
typedArray: new Uint8Array([1, 2, 3])
};
const deepCloned = cloneDeep(complex);
// All properties are deeply cloned

get

Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.

const object = {
a: {
b: {
c: 3
}
},
x: [1, 2, { y: 4 }]
};
// Access nested properties with string path
get(object, 'a.b.c'); // => 3
// Access nested properties with array path
get(object, ['a', 'b', 'c']); // => 3
// Access array elements
get(object, 'x[2].y'); // => 4
get(object, ['x', 2, 'y']); // => 4
// With default value for undefined paths
get(object, 'a.b.d', 'default'); // => 'default'
get(object, 'a.x.e', 'not found'); // => 'not found'
// Works with various property names
get({ 'a-b': { c: 3 } }, ['a-b', 'c']); // => 3

set

Sets the value at path of object. If a portion of path doesn’t exist, it’s created. Arrays are created for missing index properties while objects are created for all other missing properties.

Note: This method mutates object.

const object = { a: [{ b: { c: 3 } }] };
// Set value with string path
set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c); // => 4
// Set value with array path
set(object, ['x', 0, 'y', 'z'], 5);
console.log(object.x[0].y.z); // => 5
// Creates arrays for numeric keys
set({}, 'a[0].b.c', 3);
// => { a: [{ b: { c: 3 } }] }
// Create objects for non-numeric keys
set({}, 'a.b.c', 3);
// => { a: { b: { c: 3 } } }
// Works with various property names
set({}, ['items', 0, 'name'], 'Item 1');
// => { items: [{ name: 'Item 1' }] }