- Spec files
npm-lodash
Describes: pkg:npm/lodash@4.5.x
- Description
- Comprehensive JavaScript utility library with 300+ methods for arrays, objects, strings, functions, and more.
- Author
- tessl
- Last updated
function-methods.md docs/
1# Function Methods23Function composition, currying, throttling, debouncing, and other functional programming utilities. These methods enable advanced function manipulation and control flow patterns.45## Capabilities67### Function Control Flow89#### debounce10Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked.1112```javascript { .api }13/**14* Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked15* @param func - The function to debounce16* @param wait - The number of milliseconds to delay17* @param options - The options object18* @returns Returns the new debounced function19*/20function debounce(func, wait = 0, options);2122// Debounce options interface23interface DebounceOptions {24leading?: boolean; // Invoke on the leading edge of the timeout25maxWait?: number; // Maximum time func is allowed to be delayed before it's invoked26trailing?: boolean; // Invoke on the trailing edge of the timeout27}28```2930#### throttle31Creates a throttled function that only invokes func at most once per every wait milliseconds.3233```javascript { .api }34/**35* Creates a throttled function that only invokes func at most once per every wait milliseconds36* @param func - The function to throttle37* @param wait - The number of milliseconds to throttle invocations to38* @param options - The options object39* @returns Returns the new throttled function40*/41function throttle(func, wait = 0, options);4243// Throttle options interface44interface ThrottleOptions {45leading?: boolean; // Invoke on the leading edge of the timeout46trailing?: boolean; // Invoke on the trailing edge of the timeout47}48```4950### Function Invocation Control5152#### once53Creates a function that is restricted to invoking func once.5455```javascript { .api }56/**57* Creates a function that is restricted to invoking func once58* @param func - The function to restrict59* @returns Returns the new restricted function60*/61function once(func);62```6364#### after & before65Creates functions that invoke func only after/before being called n times.6667```javascript { .api }68/**69* Creates a function that invokes func once it's called n or more times70* @param n - The number of calls before func is invoked71* @param func - The function to restrict72* @returns Returns the new restricted function73*/74function after(n, func);7576/**77* Creates a function that invokes func while it's called less than n times78* @param n - The number of calls at which func is no longer invoked79* @param func - The function to restrict80* @returns Returns the new restricted function81*/82function before(n, func);83```8485### Function Scheduling8687#### defer88Defers invoking func until the current call stack has cleared.8990```javascript { .api }91/**92* Defers invoking func until the current call stack has cleared93* @param func - The function to defer94* @param args - The arguments to invoke func with95* @returns Returns the timer id96*/97function defer(func, ...args);98```99100#### delay101Invokes func after wait milliseconds.102103```javascript { .api }104/**105* Invokes func after wait milliseconds106* @param func - The function to delay107* @param wait - The number of milliseconds to delay invocation108* @param args - The arguments to invoke func with109* @returns Returns the timer id110*/111function delay(func, wait, ...args);112```113114### Function Binding115116#### bind117Creates a function that invokes func with the this binding of thisArg and partials prepended to the arguments it receives.118119```javascript { .api }120/**121* Creates a function that invokes func with the this binding of thisArg and partials prepended to the arguments it receives122* @param func - The function to bind123* @param thisArg - The this binding of func124* @param partials - The arguments to be partially applied125* @returns Returns the new bound function126*/127function bind(func, thisArg, ...partials);128```129130#### bindKey131Creates a function that invokes the method at object[key] with partials prepended to the arguments it receives.132133```javascript { .api }134/**135* Creates a function that invokes the method at object[key] with partials prepended to the arguments it receives136* @param object - The object to invoke the method on137* @param key - The key of the method138* @param partials - The arguments to be partially applied139* @returns Returns the new bound function140*/141function bindKey(object, key, ...partials);142```143144#### bindAll145Binds methods of an object to the object itself, overwriting the existing methods.146147```javascript { .api }148/**149* Binds methods of an object to the object itself, overwriting the existing methods150* @param object - The object to bind and assign the bound methods to151* @param methodNames - The object method names to bind152* @returns Returns object153*/154function bindAll(object, methodNames);155```156157### Partial Application158159#### partial160Creates a function that invokes func with partials prepended to the arguments it receives.161162```javascript { .api }163/**164* Creates a function that invokes func with partials prepended to the arguments it receives165* @param func - The function to partially apply arguments to166* @param partials - The arguments to be partially applied167* @returns Returns the new partially applied function168*/169function partial(func, ...partials);170```171172#### partialRight173Like partial except that partials are appended to the arguments it receives.174175```javascript { .api }176/**177* Like partial except that partials are appended to the arguments it receives178* @param func - The function to partially apply arguments to179* @param partials - The arguments to be partially applied180* @returns Returns the new partially applied function181*/182function partialRight(func, ...partials);183```184185### Currying186187#### curry188Creates a function that accepts arguments of func and either invokes func returning its result, if at least arity number of arguments have been provided, or returns a function that accepts the remaining func arguments.189190```javascript { .api }191/**192* Creates a function that accepts arguments of func and either invokes func returning its result, if at least arity number of arguments have been provided, or returns a function that accepts the remaining func arguments193* @param func - The function to curry194* @param arity - The arity of func195* @returns Returns the new curried function196*/197function curry(func, arity = func.length);198```199200#### curryRight201Like curry except that arguments are applied to func in the manner of partialRight instead of partial.202203```javascript { .api }204/**205* Like curry except that arguments are applied to func in the manner of partialRight instead of partial206* @param func - The function to curry207* @param arity - The arity of func208* @returns Returns the new curried function209*/210function curryRight(func, arity = func.length);211```212213### Function Transformation214215#### flip216Creates a function that invokes func with arguments reversed.217218```javascript { .api }219/**220* Creates a function that invokes func with arguments reversed221* @param func - The function to flip arguments for222* @returns Returns the new flipped function223*/224function flip(func);225```226227#### negate228Creates a function that negates the result of the predicate func.229230```javascript { .api }231/**232* Creates a function that negates the result of the predicate func233* @param predicate - The predicate to negate234* @returns Returns the new negated function235*/236function negate(predicate);237```238239### Argument Manipulation240241#### ary242Creates a function that invokes func, with up to n arguments, ignoring any additional arguments.243244```javascript { .api }245/**246* Creates a function that invokes func, with up to n arguments, ignoring any additional arguments247* @param func - The function to cap arguments for248* @param n - The arity cap249* @returns Returns the new capped function250*/251function ary(func, n = func.length);252```253254#### unary255Creates a function that accepts up to one argument, ignoring any additional arguments.256257```javascript { .api }258/**259* Creates a function that accepts up to one argument, ignoring any additional arguments260* @param func - The function to cap arguments for261* @returns Returns the new capped function262*/263function unary(func);264```265266#### rest267Creates a function that invokes func with the this binding of the created function and arguments from start and beyond provided as an array.268269```javascript { .api }270/**271* Creates a function that invokes func with the this binding of the created function and arguments from start and beyond provided as an array272* @param func - The function to apply a rest parameter to273* @param start - The start position of the rest parameter274* @returns Returns the new function275*/276function rest(func, start = func.length - 1);277```278279#### spread280Creates a function that invokes func with the this binding of the created function and an array of arguments much like Function#apply.281282```javascript { .api }283/**284* Creates a function that invokes func with the this binding of the created function and an array of arguments much like Function#apply285* @param func - The function to spread arguments over286* @param start - The start position of the spread287* @returns Returns the new function288*/289function spread(func, start = 0);290```291292#### rearg293Creates a function that invokes func with arguments arranged according to the specified indexes.294295```javascript { .api }296/**297* Creates a function that invokes func with arguments arranged according to the specified indexes298* @param func - The function to arrange arguments for299* @param indexes - The arranged argument indexes300* @returns Returns the new function301*/302function rearg(func, ...indexes);303```304305### Argument Transformation306307#### overArgs308Creates a function that invokes func with its arguments transformed.309310```javascript { .api }311/**312* Creates a function that invokes func with its arguments transformed313* @param func - The function to wrap314* @param transforms - The argument transforms315* @returns Returns the new function316*/317function overArgs(func, ...transforms);318```319320### Function Caching321322#### memoize323Creates a function that memoizes the result of func.324325```javascript { .api }326/**327* Creates a function that memoizes the result of func328* @param func - The function to have its output memoized329* @param resolver - The function to resolve the cache key330* @returns Returns the new memoized function331*/332function memoize(func, resolver);333334// Memoized function interface335interface MemoizedFunction {336(...args: any[]): any;337cache: Map<any, any>;338}339```340341### Function Wrapping342343#### wrap344Creates a function that provides value to wrapper as its first argument.345346```javascript { .api }347/**348* Creates a function that provides value to wrapper as its first argument349* @param value - The value to wrap350* @param wrapper - The wrapper function351* @returns Returns the new function352*/353function wrap(value, wrapper);354```355356## Usage Examples357358```javascript359import {360debounce, throttle, once, after, curry, partial,361memoize, delay, bind, flip, negate362} from "lodash";363364// Debouncing - delay execution until after events stop365const searchInput = document.getElementById('search');366const performSearch = debounce((query) => {367console.log('Searching for:', query);368// API call here369}, 300);370371searchInput.addEventListener('input', (e) => {372performSearch(e.target.value);373});374375// Throttling - limit execution frequency376const onScroll = throttle(() => {377console.log('Scroll position:', window.scrollY);378}, 100);379380window.addEventListener('scroll', onScroll);381382// Execute once383const initialize = once(() => {384console.log('App initialized');385// Setup code that should only run once386});387388initialize(); // 'App initialized'389initialize(); // (nothing happens)390391// Execute after n calls392const startApp = after(3, () => {393console.log('All resources loaded, starting app');394});395396// Called when each resource loads397startApp(); // (nothing happens)398startApp(); // (nothing happens)399startApp(); // 'All resources loaded, starting app'400401// Currying402const add = (a, b, c) => a + b + c;403const curriedAdd = curry(add);404405const add5 = curriedAdd(5);406const add5And3 = add5(3);407const result = add5And3(2); // 10408409// Or in one go410const result2 = curriedAdd(1)(2)(3); // 6411412// Partial application413const multiply = (a, b, c) => a * b * c;414const double = partial(multiply, 2);415const doubleAndTriple = partial(double, 3);416417console.log(doubleAndTriple(4)); // 2 * 3 * 4 = 24418419// Function memoization420const expensiveCalculation = memoize((n) => {421console.log(`Computing for ${n}`);422return n * n * n;423});424425expensiveCalculation(5); // 'Computing for 5', returns 125426expensiveCalculation(5); // returns 125 (cached, no log)427428// Custom resolver for memoization429const fetchUser = memoize(430async (id) => {431const response = await fetch(`/api/users/${id}`);432return response.json();433},434(id) => `user:${id}` // cache key resolver435);436437// Delayed execution438const sayHello = (name) => console.log(`Hello, ${name}!`);439delay(sayHello, 1000, 'World'); // Logs after 1 second440441// Function binding442const obj = {443name: 'MyObject',444greet(greeting) {445return `${greeting}, I'm ${this.name}`;446}447};448449const boundGreet = bind(obj.greet, obj);450const standaloneGreet = boundGreet;451console.log(standaloneGreet('Hello')); // 'Hello, I'm MyObject'452453// Argument flipping454const divide = (a, b) => a / b;455const flippedDivide = flip(divide);456457console.log(divide(10, 2)); // 5458console.log(flippedDivide(10, 2)); // 0.2 (2 / 10)459460// Negation461const isEven = (n) => n % 2 === 0;462const isOdd = negate(isEven);463464console.log(isEven(4)); // true465console.log(isOdd(4)); // false466467// Combining techniques468const createApiClient = () => {469const cache = new Map();470471const request = memoize(472throttle(async (url) => {473const response = await fetch(url);474return response.json();475}, 1000),476(url) => url477);478479return {480get: (endpoint) => request(`/api${endpoint}`)481};482};483484// Advanced currying example485const createLogger = curry((level, category, message) => {486console.log(`[${level.toUpperCase()}] ${category}: ${message}`);487});488489const errorLogger = createLogger('error');490const appErrorLogger = errorLogger('app');491const dbErrorLogger = errorLogger('database');492493appErrorLogger('User authentication failed');494dbErrorLogger('Connection timeout');495496// Function composition with partial application497const users = [498{ name: 'John', age: 30, active: true },499{ name: 'Jane', age: 25, active: false },500{ name: 'Bob', age: 35, active: true }501];502503const filterActive = partial(filter, _, 'active');504const mapNames = partial(map, _, 'name');505const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);506507const getActiveUserNames = compose(mapNames, filterActive);508console.log(getActiveUserNames(users)); // ['John', 'Bob']509```