A comprehensive JavaScript utility library for working with native objects that extends Array, Date, Function, Number, Object, RegExp, and String with powerful methods.
—
Enhanced function utilities providing control, timing, and enhancement capabilities for JavaScript functions.
// Import Sugar namespace
import Sugar from "sugar";
// Methods available as Sugar.Function.methodName()CommonJS:
const Sugar = require("sugar");
// Methods available as Sugar.Function.methodName()
Sugar.Function.after(fn, 3);Control when and how many times functions execute.
Creates a function that executes only after being called n times.
/**
* Creates a function that executes only after being called n times
* @param instance - Function to control
* @param n - Number of calls required before execution
* @returns Function that executes after n calls
*/
function after(instance: Function, n: number): Function;Usage Example:
import Sugar from "sugar";
const fn = Sugar.Function.after(() => console.log('Called!'), 3);
fn(); // Nothing happens
fn(); // Nothing happens
fn(); // Logs 'Called!'
fn(); // Logs 'Called!' (continues to work)Creates a function that executes only on the first call, ignoring subsequent calls.
/**
* Creates a function that executes only once
* @param instance - Function to execute once
* @returns Function that executes only on first call
*/
function once(instance: Function): Function;Usage Example:
import Sugar from "sugar";
let counter = 0;
const increment = Sugar.Function.once(() => counter++);
increment(); // counter becomes 1
increment(); // counter stays 1
increment(); // counter stays 1Locks a function after n executions, preventing further calls.
/**
* Locks function after n executions
* @param instance - Function to lock
* @param n - Number of executions before locking (default: 1)
* @returns Function that locks after n calls
*/
function lock(instance: Function, n?: number): Function;Usage Example:
import Sugar from "sugar";
let calls = 0;
const fn = Sugar.Function.lock(() => calls++, 2);
fn(); // calls becomes 1
fn(); // calls becomes 2
fn(); // calls stays 2 (locked)Cancels a delayed or recurring function, preventing future executions.
/**
* Cancels delayed or recurring function execution
* @param instance - Function to cancel
* @returns The function instance
*/
function cancel(instance: Function): Function;Usage Example:
import Sugar from "sugar";
const fn = Sugar.Function.delay(() => console.log('Delayed'), 1000);
Sugar.Function.cancel(fn); // Prevents the delayed executionControl the timing and frequency of function execution.
Delays function execution by specified milliseconds.
/**
* Delays function execution
* @param instance - Function to delay
* @param ms - Milliseconds to delay (default: 1)
* @param args - Arguments to pass to function
* @returns The delayed function
*/
function delay(instance: Function, ms?: number, ...args: any[]): Function;Usage Example:
import Sugar from "sugar";
Sugar.Function.delay(() => console.log('Hello after 1 second'), 1000);
// With arguments
Sugar.Function.delay((name, age) => console.log(`${name} is ${age}`), 500, 'Alice', 25);Creates a debounced function that delays execution until after calls have stopped.
/**
* Creates debounced function that delays execution
* @param instance - Function to debounce
* @param ms - Milliseconds to wait (default: 1)
* @returns Debounced function
*/
function debounce(instance: Function, ms?: number): Function;Usage Example:
import Sugar from "sugar";
const search = Sugar.Function.debounce((query) => {
console.log('Searching for:', query);
}, 300);
// Only the last call within 300ms will execute
search('a');
search('ab');
search('abc'); // Only this will execute after 300msCreates a throttled function that executes at most once per specified interval.
/**
* Creates throttled function with limited execution frequency
* @param instance - Function to throttle
* @param ms - Milliseconds between executions (default: 1)
* @returns Throttled function
*/
function throttle(instance: Function, ms?: number): Function;Usage Example:
import Sugar from "sugar";
const handleScroll = Sugar.Function.throttle(() => {
console.log('Scroll event handled');
}, 100);
window.addEventListener('scroll', handleScroll);
// Function executes at most once every 100ms during scrollingExecutes a function repeatedly at specified intervals.
/**
* Executes function repeatedly at intervals
* @param instance - Function to execute repeatedly
* @param ms - Milliseconds between executions (default: 1)
* @param args - Arguments to pass to function
* @returns The recurring function (can be cancelled)
*/
function every(instance: Function, ms?: number, ...args: any[]): Function;Usage Example:
import Sugar from "sugar";
const timer = Sugar.Function.every(() => console.log('Tick'), 1000);
// Logs 'Tick' every second
// Cancel after 5 seconds
setTimeout(() => Sugar.Function.cancel(timer), 5000);Creates a lazy function with rate limiting and optional immediate execution.
/**
* Creates lazy function with rate limiting
* @param instance - Function to make lazy
* @param ms - Milliseconds for rate limiting (default: 1)
* @param immediate - Execute immediately on first call (default: false)
* @param limit - Maximum number of executions (optional)
* @returns Lazy function with rate limiting
*/
function lazy(instance: Function, ms?: number, immediate?: boolean, limit?: number): Function;Usage Example:
import Sugar from "sugar";
// Execute immediately, then limit to once per 2 seconds, max 3 times
const lazyFn = Sugar.Function.lazy(() => console.log('Lazy execution'), 2000, true, 3);
lazyFn(); // Executes immediately
lazyFn(); // Waits 2 seconds
lazyFn(); // Waits 2 seconds
lazyFn(); // Does nothing (limit reached)Enhance function capabilities with memoization and partial application.
Creates a memoized function that caches results based on arguments.
/**
* Creates memoized function with result caching
* @param instance - Function to memoize
* @param hashFn - Custom hash function for cache keys (optional)
* @param limit - Maximum cache size (optional)
* @returns Memoized function with caching
*/
function memoize(instance: Function, hashFn?: Function, limit?: number): Function;Usage Example:
import Sugar from "sugar";
const expensiveOperation = Sugar.Function.memoize((n) => {
console.log('Computing...', n);
return n * n * n;
});
console.log(expensiveOperation(5)); // Logs 'Computing... 5', returns 125
console.log(expensiveOperation(5)); // Returns 125 immediately (cached)
// Custom hash function for objects
const objectMemo = Sugar.Function.memoize(
(obj) => obj.value * 2,
(obj) => JSON.stringify(obj)
);
// Limit cache size to 10 entries
const limitedMemo = Sugar.Function.memoize((x) => x * x, null, 10);Creates a partially applied function with pre-filled arguments.
/**
* Creates partially applied function
* @param instance - Function to partially apply
* @param args - Arguments to pre-fill
* @returns Partially applied function
*/
function partial(instance: Function, ...args: any[]): Function;Usage Example:
import Sugar from "sugar";
const multiply = (a, b, c) => a * b * c;
const double = Sugar.Function.partial(multiply, 2);
const quadruple = Sugar.Function.partial(multiply, 2, 2);
console.log(double(3, 4)); // 2 * 3 * 4 = 24
console.log(quadruple(5)); // 2 * 2 * 5 = 20
// Useful for event handlers
const logWithPrefix = (prefix, message) => console.log(`${prefix}: ${message}`);
const errorLog = Sugar.Function.partial(logWithPrefix, 'ERROR');
const infoLog = Sugar.Function.partial(logWithPrefix, 'INFO');
errorLog('Something went wrong'); // Logs: ERROR: Something went wrong
infoLog('Operation completed'); // Logs: INFO: Operation completed