
Enter a search term above to see results...
Enter a search term above to see results...
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.
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.
import { noop } from '@semantic-ui/utils';
// this reuses the same function which is a micro-optimizationfunction someFunction(callback = noop) { callback();}
// This creates a new empty function each timefunction lessEfficientFunction(callback = function() {}) { callback();}
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.
Name | Type | Description |
---|---|---|
x | any | The value to wrap |
A function that either calls the input function or returns the input value.
import { wrapFunction } from '@semantic-ui/utils';
const f1 = wrapFunction(() => 'Hello');console.log(f1()); // 'Hello'
const f2 = wrapFunction('World');console.log(f2()); // 'World'
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.
Name | Type | Description |
---|---|---|
fn | function | The function to memoize |
hashFunction | function | (Optional) A function to generate a cache key from the arguments |
A new function that caches results based on its arguments.
import { memoize, hashCode } from '@semantic-ui/utils';
// Using default hashingconst expensiveOperation = (a, b) => { console.log('Calculating...'); return a + b;};
const memoizedOperation = memoize(expensiveOperation);
console.log(memoizedOperation(2, 3)); // Logs: Calculating... 5console.log(memoizedOperation(2, 3)); // Logs: 5 (no recalculation)
// Using custom hashingconst 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... 5console.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
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.
Name | Type | Description |
---|---|---|
func | function | The function to debounce |
wait | number|object | The number of milliseconds to delay, or options object |
options | object | Optional 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 })
Name | Type | Default | Description |
---|---|---|---|
wait | number | 0 | Milliseconds to delay (when using overload syntax) |
rejectSkipped | boolean | false | Whether to reject skipped calls |
leading | boolean | false | Execute on first call |
trailing | boolean | true | Execute after wait period |
maxWait | number | undefined | Maximum time to wait before forcing execution |
abortController | AbortController | undefined | AbortController for cancellation |
A debounced function with cancel()
, flush()
, and pending()
methods.
import { debounce } from '@semantic-ui/utils';
// Basic usageconst 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 optionsconst 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 integrationconst controller = new AbortController();const abortableDebounce = debounce(apiCall, 500, { abortController: controller });controller.abort(); // Cancels pending execution
// MethodsdebouncedFunction.cancel(); // Cancel pending executiondebouncedFunction.flush(); // Execute immediately with latest argsdebouncedFunction.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.
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.
Name | Type | Description |
---|---|---|
func | function | The function to throttle |
wait | number|object | The number of milliseconds to throttle invocations to, or options object |
options | object | Optional 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 })
Name | Type | Default | Description |
---|---|---|---|
wait | number | 0 | Milliseconds to throttle invocations to (when using overload syntax) |
rejectSkipped | boolean | false | Whether to reject skipped calls |
leading | boolean | true | Execute immediately on first call |
trailing | boolean | true | Execute once more after wait period if calls occurred |
abortController | AbortController | undefined | AbortController for cancellation |
A throttled function with cancel()
, flush()
, and pending()
methods.
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 callsconst rateLimitedAPI = throttle(apiCall, 2000);rateLimitedAPI('/users'); // Executes immediately (leading)rateLimitedAPI('/posts'); // Queued for trailing executionrateLimitedAPI('/comments'); // Replaces previous trailing call
// AbortController integrationconst controller = new AbortController();const abortableThrottle = throttle(expensiveOperation, 1000, { abortController: controller });controller.abort(); // Cancels pending execution
// MethodsthrottledFunction.cancel(); // Cancel pending executionthrottledFunction.flush(); // Execute immediately with latest argsthrottledFunction.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.