Function Utilities API reference for function manipulation utility functions command API Reference
Categories

Function Utilities

The Function utilities provide helper functions for creating, wrapping, and optimizing functions in JavaScript. These utilities can help improve performance and simplify common function-related tasks.

Functions

noop

function noop()

A function that does nothing (no operation).

Performance Optimization The primary purpose of noop is to provide a reusable, empty function that avoids the performance memory and performance overhead of creating new empty functions. This is particularly beneficial when used as a default value for optional function arguments or callbacks.

Example

import { noop } from '@semantic-ui/utils';
// this reuses the same function which is a micro-optimization
function someFunction(callback = noop) {
callback();
}
// This creates a new empty function each time
function lessEfficientFunction(callback = function() {}) {
callback();
}

wrapFunction

function wrapFunction(x)

Ensures that the given value is a function. If it’s not, it returns a function that returns the value.

When to use Wrap function is helpful if you are unsure a function is defined but you want to call it. It can be simpler in some cases than type checking on a function.

Parameters

NameTypeDescription
xanyThe value to wrap

Returns

A function that either calls the input function or returns the input value.

Example

import { wrapFunction } from '@semantic-ui/utils';
const f1 = wrapFunction(() => 'Hello');
console.log(f1()); // 'Hello'
const f2 = wrapFunction('World');
console.log(f2()); // 'World'

memoize

function memoize(fn, hashFunction)

Creates a memoized version of a function, caching its results for repeated calls with the same arguments.

Custom Hashing This implementation allows for a custom hashing function, enabling more control over how arguments are compared for caching. The default hashing function uses JSON.stringify and a hash code function, which may not be suitable for all use cases, especially with complex objects or circular references.

Parameters

NameTypeDescription
fnfunctionThe function to memoize
hashFunctionfunction(Optional) A function to generate a cache key from the arguments

Returns

A new function that caches results based on its arguments.

Example

import { memoize, hashCode } from '@semantic-ui/utils';
// Using default hashing
const expensiveOperation = (a, b) => {
console.log('Calculating...');
return a + b;
};
const memoizedOperation = memoize(expensiveOperation);
console.log(memoizedOperation(2, 3)); // Logs: Calculating... 5
console.log(memoizedOperation(2, 3)); // Logs: 5 (no recalculation)
// Using custom hashing
const customHashOperation = (obj) => {
console.log('Processing object...');
return obj.a + obj.b;
};
const customHash = (args) => args[0].id; // Hash based on object id
const memoizedCustomOperation = memoize(customHashOperation, customHash);
console.log(memoizedCustomOperation({id: 1, a: 2, b: 3})); // Logs: Processing object... 5
console.log(memoizedCustomOperation({id: 1, a: 2, b: 3})); // Logs: 5 (no reprocessing)
console.log(memoizedCustomOperation({id: 2, a: 3, b: 4})); // Logs: Processing object... 7

debounce

function debounce(func, wait, options)
function debounce(func, options) // overload with options.wait

Creates a debounced version of a function that delays execution until after wait milliseconds have elapsed since the last call. Supports both sync and async functions with comprehensive promise handling and AbortController integration.

Parameters

NameTypeDescription
funcfunctionThe function to debounce
waitnumber|objectThe number of milliseconds to delay, or options object
optionsobjectOptional configuration object (when wait is number)

Overload Support You can pass options as the second parameter with wait specified inside: debounce(func, { wait: 300, leading: true })

Options
NameTypeDefaultDescription
waitnumber0Milliseconds to delay (when using overload syntax)
rejectSkippedbooleanfalseWhether to reject skipped calls
leadingbooleanfalseExecute on first call
trailingbooleantrueExecute after wait period
maxWaitnumberundefinedMaximum time to wait before forcing execution
abortControllerAbortControllerundefinedAbortController for cancellation

Returns

A debounced function with cancel(), flush(), and pending() methods.

Example

import { debounce } from '@semantic-ui/utils';
// Basic usage
const debouncedSave = debounce(saveData, 1000);
const results = await Promise.all([
debouncedSave('data1'),
debouncedSave('data2'),
debouncedSave('data3') // Only this executes, all promises resolve to same result
]);
// With options
const searchFunction = debounce(search, 300, {
leading: true, // Execute immediately on first call
maxWait: 1000 // Force execution after 1 second max
});
// Using overload syntax (options as second parameter)
const searchFunctionAlt = debounce(search, {
wait: 300,
leading: true,
maxWait: 1000
});
// AbortController integration
const controller = new AbortController();
const abortableDebounce = debounce(apiCall, 500, { abortController: controller });
controller.abort(); // Cancels pending execution
// Methods
debouncedFunction.cancel(); // Cancel pending execution
debouncedFunction.flush(); // Execute immediately with latest args
debouncedFunction.pending(); // Check if execution is scheduled

Promise Semantics All pending promises resolve with the result of the eventual execution. For async functions, the debounced function returns promises that resolve when the debounced execution completes.

throttle

function throttle(func, wait, options)
function throttle(func, options) // overload with options.wait

Creates a throttled version of a function that only invokes the function at most once per every wait milliseconds. Supports both sync and async functions with comprehensive promise handling and AbortController integration.

Parameters

NameTypeDescription
funcfunctionThe function to throttle
waitnumber|objectThe number of milliseconds to throttle invocations to, or options object
optionsobjectOptional configuration object (when wait is number)

Overload Support You can pass options as the second parameter with wait specified inside: throttle(func, { wait: 100, leading: false })

Options
NameTypeDefaultDescription
waitnumber0Milliseconds to throttle invocations to (when using overload syntax)
rejectSkippedbooleanfalseWhether to reject skipped calls
leadingbooleantrueExecute immediately on first call
trailingbooleantrueExecute once more after wait period if calls occurred
abortControllerAbortControllerundefinedAbortController for cancellation

Returns

A throttled function with cancel(), flush(), and pending() methods.

Example

import { throttle } from '@semantic-ui/utils';
// Basic usage (leading + trailing execution)
const throttledScroll = throttle(handleScroll, 100);
// Leading only (execute immediately, ignore subsequent calls)
const throttledClick = throttle(handleClick, 1000, {
leading: true,
trailing: false
});
// Trailing only (execute once after wait period)
const throttledResize = throttle(handleResize, 250, {
leading: false,
trailing: true
});
// Rate limiting API calls
const rateLimitedAPI = throttle(apiCall, 2000);
rateLimitedAPI('/users'); // Executes immediately (leading)
rateLimitedAPI('/posts'); // Queued for trailing execution
rateLimitedAPI('/comments'); // Replaces previous trailing call
// AbortController integration
const controller = new AbortController();
const abortableThrottle = throttle(expensiveOperation, 1000, { abortController: controller });
controller.abort(); // Cancels pending execution
// Methods
throttledFunction.cancel(); // Cancel pending execution
throttledFunction.flush(); // Execute immediately with latest args
throttledFunction.pending(); // Check if execution is scheduled

Use Cases Throttling is ideal for high-frequency events like scroll, resize, mousemove, and API rate limiting. Unlike debouncing which waits for calm periods, throttling ensures regular execution during continuous activity.

Previous
Errors
Next
Looping