--- url: /reference/error/AbortError.md --- # AbortError An error class representing an aborted or canceled operation. ```typescript const error = new AbortError(message); ``` ## Usage ### `new AbortError(message?)` An error class used when an operation is aborted or canceled. It is thrown when operations like [debounce](../function/debounce.md) or [delay](../promise/delay.md) are canceled with an `AbortSignal`. ```typescript import { AbortError } from 'es-toolkit/error'; // Create an error with the default message. throw new AbortError(); // Error message: 'The operation was aborted' // Create an error with a custom message. throw new AbortError('File upload was canceled'); // Error message: 'File upload was canceled' ``` An example of using it with AbortSignal. ```typescript import { AbortError, delay } from 'es-toolkit'; async function fetchData(signal: AbortSignal) { try { await delay(1000, { signal }); return 'Data loaded'; } catch (error) { if (error instanceof AbortError) { console.log('Operation was canceled'); } throw error; } } const controller = new AbortController(); controller.abort(); // Cancel operation await fetchData(controller.signal); // Throws AbortError ``` #### Parameters * `message` (`string`, optional): The error message. Defaults to `'The operation was aborted'`. #### Returns (`AbortError`): Returns an error instance representing an aborted operation. It inherits from `Error` and the `name` property is `'AbortError'`. --- --- url: /intro.md --- # About es-toolkit es-toolkit is a modern JavaScript utility library that offers a collection of powerful functions for everyday use. Compared to alternatives like lodash, es-toolkit provides a [significantly smaller bundle size](./bundle-size.md) (up to 97% less) and [2-3 times faster runtime performance](./performance.md). This is achieved through a modern implementation that leverages the latest JavaScript features. es-toolkit comes with built-in TypeScript types and has been rigorously tested, ensuring 100% test coverage for maximum reliability. ## Features Here are some of the features es-toolkit offers: * **Array**: Utilities for array manipulation, such as [uniq](./reference/array/uniq.md) and [difference](./reference/array/difference.md). * **Function**: Tools for controlling function execution, including [debounce](./reference/function/debounce.md) and [throttle](./reference/function/throttle.md). * **Math**: Numerical utilities like [sum](./reference/math/sum.md) and [round](./reference/math/round.md). * **Object**: Tools for manipulating JavaScript objects, such as [pick](./reference/object/pick.md) and [omit](./reference/object/omit.md). * **Predicate**: Type guard functions like [isNotNil](./reference/predicate/isNotNil.md). * **Promise**: Asynchronous utilities like [delay](./reference/promise/delay.md). * **String**: Utilities for string manipulation, such as [snakeCase](./reference/string/snakeCase.md) ## Links Please refer to the following links for more information about this project. * [GitHub](https://github.com/toss/es-toolkit) --- --- url: /reference/compat/math/add.md --- # add (Lodash Compatibility) ::: warning Use the `+` operator This `add` function operates slowly due to complex type conversion and string handling. Use the faster and simpler `+` operator instead. ::: Adds two values. ```typescript const result = add(value, other); ``` ## Usage ### `add(value, other)` Use `add` when you want to add two values. It can handle not only numbers but also strings. ```typescript import { add } from 'es-toolkit/compat'; // Adding numbers add(2, 3); // Returns: 5 add(1.5, 2.5); // Returns: 4 // Handling NaN add(NaN, 5); // Returns: NaN add(10, NaN); // Returns: NaN ``` When strings are included, it operates as string concatenation. ```typescript import { add } from 'es-toolkit/compat'; add('2', 3); // Returns: '23' add(1, '5'); // Returns: '15' add('hello', 'world'); // Returns: 'helloworld' ``` `undefined` values are handled specially. ```typescript import { add } from 'es-toolkit/compat'; add(undefined, undefined); // Returns: 0 add(5, undefined); // Returns: 5 add(undefined, 3); // Returns: 3 ``` #### Parameters * `value` (`number`): The first value to add. * `other` (`number`): The second value to add. #### Returns (`number | string`): Returns the sum of two values. Returns a string if strings are included, otherwise returns a number. --- --- url: /reference/function/after.md --- # after Creates a new function that invokes the original function starting from the `n`-th call. ```typescript const afterFunc = after(n, func); ``` ## Usage ### `after(n, func)` Use `after` when you want to ignore the first few calls and execute the function starting from the `n`-th call. This is useful when you need to perform an action only after a specific number of occurrences in events or asynchronous operations. ```typescript import { after } from 'es-toolkit/function'; const afterFn = after(3, () => { console.log('executed'); }); // logs nothing afterFn(); // logs nothing afterFn(); // logs 'executed' afterFn(); // logs 'executed' afterFn(); ``` #### Parameters * `n` (`number`): The number of calls required before `func` is executed. * `func` (`F`): The function to be executed. #### Returns (`(...args: Parameters) => ReturnType | undefined`): A new function that tracks the number of calls and executes `func` starting from the `n`-th call. Returns `undefined` for calls before the `n`-th call. #### Throws Throws an error when `n` is not an integer or is negative. --- --- url: /reference/compat/function/after.md --- # after (Lodash Compatibility) ::: warning Use [`after`](../../function/after.md) from `es-toolkit` This `after` function operates slowly due to complex type validation and integer conversion handling. Instead, use the faster and more modern [after](../../function/after.md) from `es-toolkit`. ::: Creates a function that only executes after being called a specified number of times. ```typescript const restrictedFunction = after(n, func); ``` ## Usage ### `after(n, func)` Use `after` when you want to restrict a function to execute only after it has been called a certain number of times. It's useful for executing callbacks after multiple asynchronous operations are complete or activating a function after an initialization phase. ```typescript import { after } from 'es-toolkit/compat'; // Basic usage const logAfterThree = after(3, () => { console.log('Executed from the 3rd call!'); }); logAfterThree(); // Not executed logAfterThree(); // Not executed logAfterThree(); // Logs "Executed from the 3rd call!" logAfterThree(); // Logs "Executed from the 3rd call!" (continues to execute) ``` You can also use it to execute a specific callback after all asynchronous operations are complete. ```typescript import { after } from 'es-toolkit/compat'; const tasks = ['task1', 'task2', 'task3']; const allTasksComplete = after(tasks.length, () => { console.log('All tasks completed!'); }); // Called when each task completes tasks.forEach(task => { performAsyncTask(task, () => { console.log(`${task} complete`); allTasksComplete(); // Logs "All tasks completed!" on the 3rd call }); }); ``` When you pass 0 or a negative number, it executes immediately from the first call. ```typescript import { after } from 'es-toolkit/compat'; const immediate = after(0, () => console.log('Executed immediately')); immediate(); // "Executed immediately" const negative = after(-1, () => console.log('Executed immediately')); negative(); // "Executed immediately" ``` #### Parameters * `n` (`number`): The number of calls required before the function executes. * `func` (`TFunc`): The function to restrict. #### Returns (`TFunc`): Returns a new restricted function that executes the original function from the nth call onwards. --- --- url: /llms-txt.md --- # AI Integration es-toolkit is committed to helping AI agents make the most of our library. We're actively working on features that make it easier for AI-powered tools to understand, reference, and use es-toolkit effectively. ## llms.txt As part of this effort, es-toolkit provides [llms.txt](https://llmstxt.org/) files — a standard that helps AI assistants and large language models (LLMs) understand project documentation more effectively. ### `/llms.txt` A structured table of contents of es-toolkit's documentation, including links to individual pages. This is useful when an AI tool needs to look up specific functions or topics. * **URL**: ### `/llms-full.txt` The complete content of all documentation pages combined into a single file. This is useful when you want to provide the AI tool with comprehensive context about es-toolkit. * **URL**: ### Usage with AI Tools Many AI tools and LLM-powered applications support the llms.txt standard. You can use these endpoints to give AI assistants full context about es-toolkit's API and features. For example, you can provide the URL to an AI coding assistant so it can reference es-toolkit's documentation when helping you write code: ``` Use es-toolkit for utility functions. Documentation: https://es-toolkit.dev/llms-full.txt ``` --- --- url: /reference/function/ary.md --- # ary Creates a new function that limits the number of arguments a function can accept. ```typescript const limitedFunc = ary(func, n); ``` ## Usage ### `ary(func, n)` Use `ary` when you want to limit the number of arguments a function can accept. Additional arguments passed are ignored. This is especially useful in functional programming to prevent callback functions from receiving unexpected arguments. ```typescript import { ary } from 'es-toolkit/function'; function fn(a: number, b: number, c: number) { return Array.from(arguments); } // Limit to accept no arguments ary(fn, 0)(1, 2, 3); // Returns: [] // Limit to accept only 1 argument ary(fn, 1)(1, 2, 3); // Returns: [1] // Limit to accept only 2 arguments ary(fn, 2)(1, 2, 3); // Returns: [1, 2] ``` This is especially useful when used with array methods like `map`. ```typescript // parseInt accepts two arguments, but map passes three ['1', '2', '3'].map(parseInt); // Returns: [1, NaN, NaN] ['1', '2', '3'].map(parseInt); // Result: [1, NaN, NaN] // Because parseInt('2', 1), parseInt('3', 2) are executed. // Use ary to limit to only the first argument ['1', '2', '3'].map(ary(parseInt, 1)); // Result: [1, 2, 3] ✅ ``` #### Parameters * `func` (`F`): The function to limit the number of arguments. * `n` (`number`): The maximum number of arguments to accept. #### Returns (`(...args: any[]) => ReturnType`): A new function that accepts at most `n` arguments. --- --- url: /reference/compat/function/ary.md --- # ary (Lodash Compatibility) ::: warning Use [`ary`](../../function/ary.md) from `es-toolkit` This `ary` function operates slowly due to complex parameter validation. Instead, use the faster and more modern [ary](../../function/ary.md) from `es-toolkit`. ::: Creates a function that limits the number of arguments it can receive. ```typescript const cappedFunction = ary(func, n); ``` ## Usage ### `ary(func, n)` Use `ary` when you want to limit the number of arguments a function receives. It's useful for safely using functions that receive too many arguments or ignoring unnecessary arguments in callback functions. ```typescript import { ary } from 'es-toolkit/compat'; // Basic usage function greet(name, age, city) { return `Hello, ${name}! ${age} years old, from ${city}.`; } const limitedGreet = ary(greet, 2); console.log(limitedGreet('John', 30, 'Seoul', 'extraArg')); // "Hello, John! 30 years old, from undefined." // Arguments from the 3rd onwards are ignored ``` You can prevent unnecessary arguments from being passed to callback functions when using them with array methods. ```typescript import { ary } from 'es-toolkit/compat'; // parseInt accepts a second argument (radix), but map's callback passes 3 arguments const numbers = ['1', '2', '3', '4', '5']; // Incorrect usage - parseInt receives the index as radix console.log(numbers.map(parseInt)); // [1, NaN, NaN, NaN, NaN] // Use ary to pass only the first argument console.log(numbers.map(ary(parseInt, 1))); // [1, 2, 3, 4, 5] ``` You can limit functions to receive only the desired number of parameter arguments. ```typescript import { ary } from 'es-toolkit/compat'; function sum(...args) { return args.reduce((total, num) => total + num, 0); } const sum0 = ary(sum, 0); const sum1 = ary(sum, 1); const sum2 = ary(sum, 2); const sum3 = ary(sum, 3); console.log(sum0(1, 2, 3, 4, 5)); // 0 (no arguments) console.log(sum1(1, 2, 3, 4, 5)); // 1 (first argument only) console.log(sum2(1, 2, 3, 4, 5)); // 3 (first two arguments only) console.log(sum3(1, 2, 3, 4, 5)); // 6 (first three arguments only) ``` When passing a negative number or `NaN`, it's treated as 0 and all arguments are ignored. ```typescript import { ary } from 'es-toolkit/compat'; const func = (a, b, c) => [a, b, c]; console.log(ary(func, -1)(1, 2, 3)); // [] (negative treated as 0) console.log(ary(func, NaN)(1, 2, 3)); // [] (NaN treated as 0) ``` #### Parameters * `func` (`Function`): The function to cap arguments for. * `n` (`number`, optional): The maximum number of arguments to allow. If omitted, uses the function's `length` property. #### Returns (`Function`): Returns a new function that accepts at most `n` arguments. --- --- url: /reference/util/assert.md --- # assert Asserts that a given condition is true. If the condition is false, it throws an error. ```typescript assert(condition, message); ``` ::: info Relationship with `invariant` `assert` has exactly the same functionality as the `invariant` function. The only difference is the name. For more details, see the [`invariant`](./invariant.md) documentation. ::: ## Usage ### `assert(condition, message)` Use `assert` when a specific condition must be satisfied in your code. If the condition is false, it immediately throws an error and stops program execution. ```typescript import { assert } from 'es-toolkit/util'; // If the condition is true, nothing happens assert(true, 'This message will not appear'); // If the condition is false, it throws an error assert(false, 'This condition is false'); // Error: This condition is false // When checking that a value is not null or undefined const value = getValue(); assert(value !== null && value !== undefined, 'Value must not be null or undefined'); // Now you can be sure that value is neither null nor undefined // When checking if a number is positive const number = getNumber(); assert(number > 0, 'Number must be positive'); ``` You can also pass an error object directly. ```typescript import { assert } from 'es-toolkit/util'; // Passing an Error object assert(false, new Error('Custom error message')); // Using a custom error class class ValidationError extends Error { constructor(message: string) { super(message); this.name = 'ValidationError'; } } assert(false, new ValidationError('Validation failed')); ``` It's especially useful for verifying code assumptions during development or checking that function inputs are within expected ranges. #### Parameters * `condition` (`unknown`): The condition to evaluate. If it evaluates to a falsy value, an error is thrown. * `message` (`string | Error`): The error message or error object to throw when the condition is false. #### Returns (`void`): Returns nothing if the condition is true. #### Throws Throws the provided message or error object if the condition evaluates to false. --- --- url: /reference/compat/object/assign.md --- # assign (Lodash compatibility) ::: warning Use `Object.assign` instead This `assign` function operates slowly due to additional logic that checks whether values are equal. Use the faster and more modern `Object.assign` instead. ::: Assigns properties from source objects to a target object. ```typescript const result = assign(target, ...sources); ``` ## Usage ### `assign(target, ...sources)` Use `assign` when you want to copy properties from one or more source objects to a target object. If there are duplicate keys, values from later sources will overwrite earlier ones. ```typescript import { assign } from 'es-toolkit/compat'; // Basic usage const target = { a: 1, b: 2 }; const source = { b: 3, c: 4 }; const result = assign(target, source); // Result: { a: 1, b: 3, c: 4 } console.log(target === result); // true (target object is modified) // Merging multiple source objects const target2 = { a: 1 }; const source1 = { b: 2 }; const source2 = { c: 3 }; const source3 = { d: 4 }; assign(target2, source1, source2, source3); // Result: { a: 1, b: 2, c: 3, d: 4 } // Overwriting properties const target3 = { x: 1, y: 2 }; const source4 = { y: 3, z: 4 }; const source5 = { y: 5 }; assign(target3, source4, source5); // Result: { x: 1, y: 5, z: 4 } (y is overwritten with the last value) ``` This function only copies own properties of objects, not inherited properties. It also has an optimization that doesn't overwrite if values are the same. #### Parameters * `target` (`any`): The target object to which properties will be copied. * `...sources` (`any[]`): The source objects from which properties will be copied. #### Returns (`any`): Returns the modified target object. The target object itself is modified and returned. --- --- url: /reference/compat/object/assignIn.md --- # assignIn (Lodash compatibility) ::: warning Use `Object.assign` instead This `assignIn` function operates slowly due to additional processing for copying inherited properties and value comparison logic. Use the faster and more modern `Object.assign` instead. ::: Assigns all properties (including inherited properties) from source objects to a target object. ```typescript const result = assignIn(target, ...sources); ``` ## Usage ### `assignIn(target, ...sources)` Use `assignIn` when you want to copy both own and inherited properties from source objects to a target object. Unlike `assign`, it includes properties from the prototype chain. ```typescript import { assignIn } from 'es-toolkit/compat'; // Basic usage const target = { a: 1, b: 2 }; const source = { b: 3, c: 4 }; const result = assignIn(target, source); // Result: { a: 1, b: 3, c: 4 } console.log(target === result); // true (target object is modified) // Merging multiple source objects const target2 = { a: 1 }; const source1 = { b: 2 }; const source2 = { c: 3 }; assignIn(target2, source1, source2); // Result: { a: 1, b: 2, c: 3 } // Copying inherited properties too function Parent() {} Parent.prototype.inherited = 'inheritedValue'; const child = Object.create(Parent.prototype); child.own = 'ownValue'; const target3 = {}; assignIn(target3, child); // Result: { own: 'ownValue', inherited: 'inheritedValue' } // Also copies array index properties and length const arr = [1, 2, 3]; arr.customProp = 'custom'; const target4 = {}; assignIn(target4, arr); // Result: { '0': 1, '1': 2, '2': 3, customProp: 'custom' } ``` Unlike `assign`, this function copies inherited properties as well. It also has an optimization that doesn't overwrite if values are the same. #### Parameters * `target` (`any`): The target object to which properties will be copied. * `...sources` (`any[]`): The source objects from which properties will be copied. Both own and inherited properties are copied. #### Returns (`any`): Returns the modified target object. The target object itself is modified and returned. --- --- url: /reference/compat/object/assignInWith.md --- # assignInWith (Lodash compatibility) ::: warning Implementing custom logic is recommended This `assignInWith` function operates slowly and in a complex manner due to inherited property processing and customizer function calls. Instead, use `Object.assign` and implement custom logic directly. ::: Assigns all properties (including inherited properties) from source objects to a target object using a customizer function. ```typescript const result = assignInWith(target, ...sources, customizer); ``` ## Usage ### `assignInWith(target, ...sources, customizer)` Use `assignInWith` when you want to customize how properties are assigned while including inherited properties. The customizer function determines the final value for each property. ```typescript import { assignInWith } from 'es-toolkit/compat'; // Basic usage - assign only when undefined const target = { a: 1, b: undefined }; const source = { b: 2, c: 3 }; const result = assignInWith(target, source, (objValue, srcValue) => { return objValue === undefined ? srcValue : objValue; }); // Result: { a: 1, b: 2, c: 3 } // Customizer that merges array values const target2 = { numbers: [1, 2] }; const source2 = { numbers: [3, 4], name: 'test' }; assignInWith(target2, source2, (objValue, srcValue) => { if (Array.isArray(objValue) && Array.isArray(srcValue)) { return objValue.concat(srcValue); } return srcValue; }); // Result: { numbers: [1, 2, 3, 4], name: 'test' } // Processing inherited properties too function Parent() {} Parent.prototype.inherited = 'value'; const child = Object.create(Parent.prototype); child.own = 'ownValue'; const target3 = { existing: 'data' }; assignInWith(target3, child, (objValue, srcValue, key) => { if (objValue === undefined) { return `processed_${srcValue}`; } return objValue; }); // Result: { existing: 'data', own: 'processed_ownValue', inherited: 'processed_value' } ``` If the customizer function returns `undefined`, the default assignment behavior is used. Unlike `assignIn`, this function allows you to apply custom logic to each property. #### Parameters * `target` (`any`): The target object to which properties will be copied. * `...sources` (`any[]`): The source objects from which properties will be copied. Both own and inherited properties are copied. * `customizer` (`function`): A function that determines the value to assign. In the form `(objValue, srcValue, key, object, source) => any`. If it returns `undefined`, the default assignment behavior is used. #### Returns (`any`): Returns the modified target object. The target object itself is modified and returned. --- --- url: /reference/compat/object/assignWith.md --- # assignWith (Lodash compatibility) ::: warning Implementing custom logic is recommended This `assignWith` function is relatively slow due to complex customizer function processing. Instead, use `Object.assign` and implement custom logic directly. ::: Assigns properties from source objects to a target object using a customizer function. ```typescript const result = assignWith(target, source1, source2, customizer); ``` ## Usage ### `assignWith(object, ...sources, customizer)` Use `assignWith` when you want to customize how properties are assigned. The customizer function determines the final value for each property. ```typescript import { assignWith } from 'es-toolkit/compat'; // Basic usage - assign only when undefined const target = { a: 1, b: undefined }; const source = { b: 2, c: 3 }; const result = assignWith(target, source, (objValue, srcValue) => { return objValue === undefined ? srcValue : objValue; }); // Returns: { a: 1, b: 2, c: 3 } // Array merging const target2 = { users: ['alice'] }; const source2 = { users: ['bob', 'charlie'] }; const result2 = assignWith(target2, source2, (objValue, srcValue) => { if (Array.isArray(objValue)) { return objValue.concat(srcValue); } }); // Returns: { users: ['alice', 'bob', 'charlie'] } // Multiple sources with customizer const target3 = { a: 1 }; const result3 = assignWith(target3, { b: 2 }, { c: 3 }, (objValue, srcValue) => { return objValue === undefined ? srcValue : objValue; }); // Returns: { a: 1, b: 2, c: 3 } ``` #### Parameters * `object` (`any`): The target object to which properties will be assigned. * `...sources` (`any[]`): The source objects from which properties will be copied. * `customizer` (`function`): A function that determines the value to assign. In the form `(objValue, srcValue, key, object, source) => any`. #### Returns (`any`): Returns the target object with values determined by the customizer function. --- --- url: /reference/function/asyncNoop.md --- # asyncNoop A function that asynchronously does nothing. ```typescript const promise = asyncNoop(); ``` ::: info [`noop`](./noop.md) function If you need a function that synchronously does nothing, use the `noop` function which immediately returns `void`. ::: ## Usage ### `asyncNoop()` Use `asyncNoop` when you need to fill a placeholder or use as a default value where an asynchronous function is required. It returns a `Promise` that resolves to `undefined`. ```typescript import { asyncNoop } from 'es-toolkit/function'; // Example using as a default value interface Props { fetchData?: () => Promise; } function MyComponent({ fetchData = asyncNoop }: Props) { const handleFetchData = async () => { // fetchData is always a function, so it's safe to call await fetchData(); }; handleFetchData(); } // Example of direct invocation asyncNoop(); // Returns: Promise await asyncNoop(); // Returns: undefined ``` #### Returns (`Promise`): A `Promise` that resolves to `undefined`. --- --- url: /reference/array/at.md --- # at Gets the elements at specified indices from an array and returns a new array. ```typescript const result = at(arr, indices); ``` ## Reference ### `at(arr, indices)` Use `at` when you want to select elements at specific positions from an array. You can use negative indices to select elements from the end of the array. ```typescript import { at } from 'es-toolkit/array'; // Get elements at multiple indices from a number array. at([10, 20, 30, 40, 50], [1, 3, 4]); // Returns: [20, 40, 50] // Use negative indices to get elements from the end. at(['a', 'b', 'c', 'd'], [0, -1, -2]); // Returns: ['a', 'd', 'c'] ``` Non-integer indices are converted to integers. ```typescript import { at } from 'es-toolkit/array'; at([1, 2, 3, 4], [1.5, 2.9]); // [2, 3] ``` #### Parameters * `arr` (`T[]`): The array to get elements from. * `indices` (`number[]`): An array of indices of the elements to get. Negative values count from the end of the array. #### Returns (`T[]`): A new array containing the elements at the specified indices. --- --- url: /reference/compat/object/at.md --- # at (Lodash compatibility) ::: warning Use destructuring assignment instead This `at` function is relatively slow due to complex path processing and handling of various argument types. Instead, use destructuring assignment or direct property access. ::: Returns values at specified paths of an object as an array. ```typescript const result = at(object, ...paths); ``` ## Usage ### `at(object, ...paths)` Use `at` when you want to retrieve values from multiple paths in an object at once. It returns the values corresponding to each path as an array. ```typescript import { at } from 'es-toolkit/compat'; // Basic usage const object = { a: 1, b: 2, c: 3 }; const result = at(object, 'a', 'c'); // Returns: [1, 3] // Nested objects const nested = { a: { b: { c: 4, }, }, x: [1, 2, 3], }; const result2 = at(nested, 'a.b.c', 'x[1]'); // Returns: [4, 2] // Passing paths as an array const paths = ['a', 'c']; const result3 = at(object, paths); // Returns: [1, 3] // Non-existent paths const result4 = at(object, 'nonexistent', 'a'); // Returns: [undefined, 1] ``` `null` or `undefined` objects return an array of `undefined`. ```typescript import { at } from 'es-toolkit/compat'; at(null, 'a', 'b'); // [undefined, undefined] at(undefined, 'a', 'b'); // [undefined, undefined] ``` #### Parameters * `object` (`T | null | undefined`): The object from which to retrieve values. * `...paths` (`Array>`): The paths of values to retrieve. Can be passed as individual arguments or as arrays. #### Returns (`unknown[]`): Returns an array of values corresponding to the specified paths. --- --- url: /reference/util/attempt.md --- # attempt Executes a function and returns the result or error as a tuple. ```typescript const [error, result] = attempt(func); ``` ## Usage ### `attempt(func)` Use `attempt` when you want to safely execute a function. It allows you to handle errors without wrapping code in try-catch blocks. ```typescript import { attempt } from 'es-toolkit/util'; // Success case const [error, result] = attempt(() => 42); // error is null, result is 42 // Error case const [error, result] = attempt(() => { throw new Error('Something went wrong'); }); // error is an Error object, result is null // You can also specify types const [error, names] = attempt(() => ['Alice', 'Bob']); // names is inferred as string[] type ``` ::: warning Do not use with async functions This function is not suitable for async functions (functions that return a `Promise`). If you pass an async function, it will return `[null, Promise]`, but it won't catch the error even if the Promise is rejected later. For async functions, use the [`attemptAsync`](./attemptAsync.md) function instead. ```typescript // Incorrect usage const [error, promise] = attempt(async () => { const response = await fetch('https://api.example.com/data'); return response.json(); }); // Correct usage const [error, data] = await attemptAsync(async () => { const response = await fetch('https://api.example.com/data'); return response.json(); }); ``` ::: #### Parameters * `func` (`() => T`): The function to execute. #### Returns (`[null, T] | [E, null]`): Returns `[null, result]` tuple on success, or `[error, null]` tuple on error. --- --- url: /reference/compat/function/attempt.md --- # attempt (Lodash Compatibility) ::: warning Use `es-toolkit`'s [`attempt`](../../util/attempt.md) function or try-catch blocks instead This `attempt` function can be confusing because it returns both errors and return values without distinction. Instead, use the more direct and clear [`attempt`](../../util/attempt.md) function or try-catch blocks. ::: A function that executes a function and returns an error object if an error occurs. ```typescript const result = attempt(func, ...args); ``` ## Usage ### `attempt(func, ...args)` Use `attempt` when you want to safely execute a function. It's useful when executing a function that may throw errors, preventing the program from crashing and handling errors as return values. ```typescript import { attempt } from 'es-toolkit/compat'; // Basic usage - successful case const result = attempt((x, y) => x + y, 2, 3); console.log(result); // 5 // Error case const errorResult = attempt(() => { throw new Error('Something went wrong'); }); console.log(errorResult); // Error: Something went wrong ``` Here's the difference compared to using try-catch blocks. ```typescript // Using attempt import { attempt } from 'es-toolkit/compat'; const result = attempt(riskyFunction, arg1, arg2); if (result instanceof Error) { console.log('Error occurred:', result.message); } else { console.log('Result:', result); } // Using try-catch (more direct) try { const result = riskyFunction(arg1, arg2); console.log('Result:', result); } catch (error) { console.log('Error occurred:', error.message); } ``` #### Parameters * `func` (`Function`): The function to execute. * `args` (`...any[]`): The arguments to pass to the function. #### Returns (`ReturnType | Error`): Returns the return value if the function succeeds, or an Error object if an error occurs. --- --- url: /reference/util/attemptAsync.md --- # attemptAsync Executes an async function and returns the result or error as a tuple. ```typescript const [error, result] = await attemptAsync(func); ``` ## Usage ### `attemptAsync(func)` Use `attemptAsync` when you want to safely execute an async function. You can handle errors without wrapping async/await blocks in try-catch. ```typescript import { attemptAsync } from 'es-toolkit/util'; // When API request succeeds const [error, data] = await attemptAsync(async () => { const response = await fetch('https://api.example.com/data'); return response.json(); }); // error is null, data contains response data // When network error occurs const [error, data] = await attemptAsync(async () => { throw new Error('Network error'); }); // error is Error object, data is null // You can also specify types interface User { id: number; name: string; } const [error, users] = await attemptAsync(async () => { const response = await fetch('https://api.example.com/users'); return response.json(); }); // users is inferred as User[] type ``` It's especially useful when you need error handling in async operations like database queries or file reading. ```typescript // File reading example const [error, content] = await attemptAsync(async () => { const fs = await import('fs/promises'); return fs.readFile('config.json', 'utf8'); }); if (error) { console.log('Cannot read file:', error.message); } else { console.log('File content:', content); } ``` ::: info Use attempt for synchronous functions This function is suitable for handling async functions (functions that return `Promise`). If you want to handle synchronous functions, we recommend using the [`attempt`](./attempt.md) function instead. ::: #### Parameters * `func` (`() => Promise`): The async function to execute. #### Returns (`Promise<[null, T] | [E, null]>`): Returns a Promise that resolves to `[null, result]` on success, or `[error, null]` if an error occurs. --- --- url: /reference/function/before.md --- # before Creates a new function that limits the number of times a function can be called. ```typescript const limitedFunc = before(n, func); ``` ## Usage ### `before(n, func)` Use `before` when you want to limit a function to be executed only up to a specific number of times. The function will execute until the `n-1`-th call, and from the `n`-th call onwards, it will no longer execute. ```typescript import { before } from 'es-toolkit/function'; const beforeFn = before(3, () => { console.log('executed'); }); // Logs 'executed' beforeFn(); // Logs 'executed' beforeFn(); // Logs nothing beforeFn(); // Logs nothing beforeFn(); ``` This is useful for tasks that should only be executed once, such as initialization or setup. ```typescript let initialized = false; const initialize = before(2, () => { console.log('Initializing...'); initialized = true; }); // Logs 'Initializing...' and performs initialization initialize(); // Does nothing as it's already initialized initialize(); ``` #### Parameters * `n` (`number`): The maximum number of times the returned function can call `func`. If `n` is 0, `func` will not be called. If it's a positive integer, it will be called up to `n-1` times. * `func` (`F`): The function whose invocation count will be limited. #### Returns (`(...args: Parameters) => ReturnType | undefined`): A new function that tracks the number of calls and executes `func` only up to the `n-1`-th call. Returns `undefined` for calls from the `n`-th onwards. #### Throws Throws an error when `n` is not an integer or is negative. --- --- url: /reference/compat/function/before.md --- # before (Lodash Compatibility) ::: warning Use [`before`](../../function/before.md) from `es-toolkit` This `before` function operates slower due to complex type validation and integer conversion handling. Instead, use the faster and more modern [before](../../function/before.md) from `es-toolkit`. ::: Creates a function that executes the original function up to a specified number of times, then returns the last result for subsequent calls. ```typescript const limitedFunction = before(n, func); ``` ## Usage ### `before(n, func)` Use `before` when you want to restrict a function to execute only up to a certain number of times. This is useful for limiting function call counts or when you want to execute a function only during the initial setup phase. ```typescript import { before } from 'es-toolkit/compat'; // Basic usage let count = 0; const beforeThree = before(3, () => ++count); console.log(beforeThree()); // 1 (first call) console.log(beforeThree()); // 2 (second call) console.log(beforeThree()); // 2 (from third call onwards, returns last result) console.log(beforeThree()); // 2 (continues to return last result) ``` Alternative using closures: ```typescript // Using before const beforeThree = before(3, myFunction); // Using closures (simpler and faster) function createBefore(limit, callback) { let callCount = 0; let lastResult; return function (...args) { if (callCount < limit - 1) { lastResult = callback.apply(this, args); callCount++; } return lastResult; }; } const beforeThreeAlternative = createBefore(3, myFunction); ``` Using as an initialization function: ```typescript import { before } from 'es-toolkit/compat'; class Database { constructor() { this.isInitialized = false; // Initialization executes only once this.initialize = before(2, () => { console.log('Initializing database...'); this.setupConnection(); this.isInitialized = true; return 'Initialization complete'; }); } setupConnection() { // Actual connection setup logic } query(sql) { const initResult = this.initialize(); console.log(initResult); // First call: "Initialization complete", subsequent: same result // Query execution logic return `Query executed: ${sql}`; } } const db = new Database(); db.query('SELECT * FROM users'); // Initialization executed db.query('SELECT * FROM products'); // Initialization not executed ``` Limiting API calls: ```typescript import { before } from 'es-toolkit/compat'; // Allow API calls up to 5 times maximum const limitedApiCall = before(6, endpoint => { console.log(`API call: ${endpoint}`); return fetch(endpoint).then(res => res.json()); }); // First 5 calls execute actual API calls limitedApiCall('/api/data1'); // Actual call limitedApiCall('/api/data2'); // Actual call limitedApiCall('/api/data3'); // Actual call limitedApiCall('/api/data4'); // Actual call limitedApiCall('/api/data5'); // Actual call limitedApiCall('/api/data6'); // Returns last result (no API call) ``` Limiting event listeners: ```typescript import { before } from 'es-toolkit/compat'; // Process click events up to 3 times const limitedClickHandler = before(4, event => { console.log('Click processed:', event.target.id); return `Processed: ${Date.now()}`; }); document.getElementById('button').addEventListener('click', limitedClickHandler); // Only the first 3 clicks are processed, subsequent calls return the last result ``` Handling parameters and return values: ```typescript import { before } from 'es-toolkit/compat'; const limitedCalculator = before(3, (operation, a, b) => { const result = operation === 'add' ? a + b : a - b; console.log(`Calculation: ${a} ${operation} ${b} = ${result}`); return result; }); console.log(limitedCalculator('add', 5, 3)); // "Calculation: 5 add 3 = 8", returns: 8 console.log(limitedCalculator('subtract', 10, 4)); // "Calculation: 10 subtract 4 = 6", returns: 6 console.log(limitedCalculator('multiply', 7, 2)); // No calculation, returns: 6 (last result) ``` Passing 0 or 1 prevents the function from executing: ```typescript import { before } from 'es-toolkit/compat'; const neverCalled = before(0, () => { console.log('This function will not execute'); return 'result'; }); const onceOnly = before(1, () => { console.log('This function will also not execute'); return 'result'; }); console.log(neverCalled()); // undefined console.log(onceOnly()); // undefined ``` Resource cleanup optimization: ```typescript import { before } from 'es-toolkit/compat'; // Function references are automatically cleaned up to prevent memory leaks const limitedProcessor = before(2, data => { // Complex data processing return processComplexData(data); }); // After the 2nd call, the original function reference is removed (garbage collection) ``` #### Parameters * `n` (`number`): The maximum number of times to execute the function. It executes up to n-1 times, and from the nth call onwards, returns the last result. * `func` (`Function`): The function to restrict. #### Returns (`Function`): Returns a new function that executes the original function up to the specified number of times, and thereafter returns the last result. --- --- url: /reference/compat/function/bind.md --- # bind (Lodash Compatibility) ::: warning Use `Function.prototype.bind()` This `bind` function operates slowly due to complex placeholder handling, constructor function checking, and argument merging logic. If you don't need placeholders, the native `Function.prototype.bind()` is faster and simpler. Use the faster and standard `Function.prototype.bind()` instead. ::: Creates a function that fixes the `this` context and provides some arguments in advance. ```typescript const boundFunction = bind(func, thisObj, ...partialArgs); ``` ## Usage ### `bind(func, thisObj, ...partialArgs)` Use `bind` when you want to fix the `this` context of a function or provide some arguments in advance. It's especially useful when you want to use placeholders to provide arguments at specific positions later. ```typescript import { bind } from 'es-toolkit/compat'; // Basic usage function greet(greeting, punctuation) { return greeting + ' ' + this.user + punctuation; } const object = { user: 'John' }; const boundGreet = bind(greet, object, 'Hello'); console.log(boundGreet('!')); // "Hello John!" console.log(boundGreet('~')); // "Hello John~" ``` Comparison with native bind: ```typescript // Using bind import { bind } from 'es-toolkit/compat'; const boundFn1 = bind(func, thisObj, 'arg1'); // Using native bind (faster) const boundFn2 = func.bind(thisObj, 'arg1'); // Results are the same but native is faster ``` Using placeholder functionality: ```typescript import { bind } from 'es-toolkit/compat'; function calculate(operation, a, b, suffix) { return `${a} ${operation} ${b} = ${operation === '+' ? a + b : a - b}${suffix}`; } // Provide arguments at specific positions later using placeholders const calcWithSuffix = bind( calculate, null, bind.placeholder, // operation will be provided later bind.placeholder, // a will be provided later bind.placeholder, // b will be provided later ' points' // suffix is provided in advance ); console.log(calcWithSuffix('+', 5, 3)); // "5 + 3 = 8 points" console.log(calcWithSuffix('-', 10, 4)); // "10 - 4 = 6 points" ``` More practical placeholder example: ```typescript import { bind } from 'es-toolkit/compat'; function apiRequest(method, url, options, callback) { // API request logic console.log(`${method} ${url}`, options); callback(`${method} request complete`); } // Create a partially applied function for POST requests const postRequest = bind( apiRequest, null, 'POST', // method fixed bind.placeholder, // url will be provided later { 'Content-Type': 'application/json' }, // options fixed bind.placeholder // callback will be provided later ); postRequest('/api/users', result => { console.log(result); // "POST request complete" }); postRequest('/api/products', result => { console.log(result); // "POST request complete" }); ``` Method binding: ```typescript import { bind } from 'es-toolkit/compat'; class Logger { constructor(prefix) { this.prefix = prefix; } log(level, message) { console.log(`[${this.prefix}] ${level}: ${message}`); } } const logger = new Logger('MyApp'); // Bind method to use in a different context const logError = bind(logger.log, logger, 'ERROR'); const logInfo = bind(logger.log, logger, 'INFO'); // Now can be used independently setTimeout(() => logError('Server connection failed'), 1000); setTimeout(() => logInfo('Application started'), 2000); ``` Using in event handlers: ```typescript import { bind } from 'es-toolkit/compat'; class ButtonHandler { constructor(name) { this.name = name; this.clickCount = 0; } handleClick(event, customData) { this.clickCount++; console.log(`${this.name} button clicked #${this.clickCount}`); console.log('Custom data:', customData); console.log('Event type:', event.type); } } const handler = new ButtonHandler('Menu'); // Provide custom data in advance, pass event later const boundHandler = bind( handler.handleClick, handler, bind.placeholder, // event comes later 'Menu selected' // customData provided in advance ); // Connect to DOM event (event is automatically passed as first argument) document.getElementById('menu-btn')?.addEventListener('click', boundHandler); ``` Constructor functions are also supported: ```typescript import { bind } from 'es-toolkit/compat'; function Person(name, age, city) { this.name = name; this.age = age; this.city = city || 'Seoul'; } // Constructor for creating Seoul residents const SeoulPerson = bind(Person, null, bind.placeholder, bind.placeholder, 'Seoul'); const person1 = new SeoulPerson('John', 30); const person2 = new SeoulPerson('Jane', 25); console.log(person1); // Person { name: 'John', age: 30, city: 'Seoul' } console.log(person2); // Person { name: 'Jane', age: 25, city: 'Seoul' } ``` Using in functional programming: ```typescript import { bind } from 'es-toolkit/compat'; const numbers = [1, 2, 3, 4, 5]; // Fix parseInt radix to 10 const parseDecimal = bind(parseInt, null, bind.placeholder, 10); // Safe to use in map const parsed = ['1', '2', '3'].map(parseDecimal); console.log(parsed); // [1, 2, 3] // Problem when using regular parseInt const problematic = ['1', '2', '3'].map(parseInt); // [1, NaN, NaN] ``` #### Parameters * `func` (`Function`): The function to bind. * `thisObj` (`any`, optional): The `this` value to bind to the function. * `partialArgs` (`...any[]`): The arguments to provide in advance. You can use `bind.placeholder` to specify positions to be provided later. #### Returns (`Function`): Returns a new function with `this` fixed and some arguments applied in advance. --- --- url: /reference/compat/util/bindAll.md --- # bindAll (Lodash Compatibility) Binds methods of an object to the object itself. ```typescript const boundObject = bindAll(object, methodNames); ``` ## Usage ### `bindAll(object, ...methodNames)` Use `bindAll` when you want to fix the `this` value of specific methods to the object itself. This is useful for maintaining the `this` context when passing methods as event handlers or callbacks. ```typescript import { bindAll } from 'es-toolkit/compat'; const view = { label: 'docs', click: function () { console.log('clicked ' + this.label); }, }; // Bind method to object bindAll(view, 'click'); document.addEventListener('click', view.click); // => Logs 'clicked docs' when clicked ``` You can bind multiple methods at once. ```typescript import { bindAll } from 'es-toolkit/compat'; const obj = { name: 'example', greet() { return `Hello, ${this.name}!`; }, farewell() { return `Goodbye, ${this.name}!`; }, }; // Bind multiple methods with array bindAll(obj, ['greet', 'farewell']); const greet = obj.greet; greet(); // 'Hello, example!' (this is correctly bound) ``` It can handle numeric and special keys. ```typescript import { bindAll } from 'es-toolkit/compat'; const obj = { '-0': function () { return 'negative zero'; }, '0': function () { return 'zero'; }, }; bindAll(obj, -0); obj['-0'](); // 'negative zero' ``` #### Parameters * `object` (`Object`): The object to bind methods to. * `methodNames` (`...(string | string[] | number | IArguments)`): The method names to bind. Can be specified as individual strings, arrays, numbers, or Arguments objects. #### Returns (`Object`): Returns the original object with bound methods. --- --- url: /reference/compat/function/bindKey.md --- # bindKey (Lodash Compatibility) ::: warning Use arrow functions or the `bind` method This `bindKey` function operates in a complex and slow manner due to dynamic method binding and placeholder handling. Using JavaScript's native `bind` method or arrow functions is simpler and performs better. Instead, use the faster and more modern arrow functions or `Function.prototype.bind`. ::: Binds a method of an object, allowing it to reference methods that may be redefined later. ```typescript const bound = bindKey(object, key, ...partialArgs); ``` ## Usage ### `bindKey(object, key, ...partialArgs)` Use `bindKey` when you want to bind a method of an object while allowing the method to be changed later. Unlike regular `bind`, it references the latest method each time it's called. ```typescript import { bindKey } from 'es-toolkit/compat'; const object = { user: 'fred', greet: function (greeting, punctuation) { return greeting + ' ' + this.user + punctuation; }, }; // Bind the method. let bound = bindKey(object, 'greet', 'hi'); bound('!'); // Returns: 'hi fred!' // Redefine the method. object.greet = function (greeting, punctuation) { return greeting + 'ya ' + this.user + punctuation; }; // The bound function calls the new method. bound('!'); // Returns: 'hiya fred!' ``` You can use placeholders to reserve argument positions. ```typescript import { bindKey } from 'es-toolkit/compat'; const object = { user: 'fred', greet: function (greeting, punctuation) { return greeting + ' ' + this.user + punctuation; }, }; // Use a placeholder. const bound = bindKey(object, 'greet', bindKey.placeholder, '!'); bound('hi'); // Returns: 'hi fred!' ``` Partially applied arguments are passed first, followed by arguments provided at call time. ```typescript import { bindKey } from 'es-toolkit/compat'; const object = { add: function (a, b, c) { return a + b + c; }, }; // Set the first argument in advance. const bound = bindKey(object, 'add', 10); bound(20, 30); // Returns: 60 (10 + 20 + 30) ``` #### Parameters * `object` (`object`): The object to invoke the method on. * `key` (`string`): The key of the method to call. * `...partialArgs` (`any[]`, optional): The arguments to be partially applied to the method. You can use `bindKey.placeholder` to reserve argument positions. #### Returns (`(...args: any[]) => any`): Returns a new bound function. This function references the latest method of the object each time it's called. --- --- url: /bundle-size.md description: The minimal bundle footprint offered by es-toolkit --- # Bundle Footprint With its modern implementation, es-toolkit significantly reduces its bundle size, cutting it down by up to 97% compared to other libraries like lodash. This makes es-toolkit the most efficient in terms of bundle size, with some utility functions being as small as less than 100 bytes. ## Bundle Footprint Comparison ## Bundle Size Test Method Our bundle size is measured using [esbuild 0.23.0](https://esbuild.github.io), by analyzing the size of code like the following: ```tsx import { chunk } from 'es-toolkit'; // or import { chunk } from 'lodash-es'; console.log(chunk); ``` See our [bundle size benchmark code](https://github.com/toss/es-toolkit/tree/main/benchmarks/bundle-size) for details. --- --- url: /reference/string/camelCase.md --- # camelCase Converts a string to camel case. ```typescript const result = camelCase(str); ``` ## Usage ### `camelCase(str)` Use `camelCase` when you want to convert a string to camel case. Camel case is a naming convention where the first word is lowercase and the first letter of each subsequent word is capitalized. ```typescript import { camelCase } from 'es-toolkit/string'; // Convert various string formats to camel case camelCase('hello world'); // returns 'helloWorld' camelCase('some-hyphen-text'); // returns 'someHyphenText' camelCase('CONSTANT_CASE'); // returns 'constantCase' camelCase('PascalCase'); // returns 'pascalCase' camelCase('mixed SpAcE'); // returns 'mixedSpAcE' ``` It converts strings with special characters, spaces, hyphens, and other separators into a format suitable for JavaScript variable names or object property names. ```typescript import { camelCase } from 'es-toolkit/string'; // Convert keys from API responses const apiKey = 'user_first_name'; const jsKey = camelCase(apiKey); // 'userFirstName' // Convert HTML attributes to JavaScript properties const cssProperty = 'background-color'; const jsProperty = camelCase(cssProperty); // 'backgroundColor' ``` It also preserves Unicode characters. ```typescript import { camelCase } from 'es-toolkit/string'; camelCase('keep unicode 😅'); // returns 'keepUnicode😅' camelCase('한글-테스트'); // returns '한글테스트' ``` #### Parameters * `str` (`string`): The string to convert to camel case. #### Returns (`string`): Returns a new string converted to camel case. --- --- url: /reference/compat/string/camelCase.md --- # camelCase (Lodash compatibility) ::: warning Use `camelCase` from `es-toolkit` This `camelCase` function operates slower due to handling non-string input values and removing contracted apostrophes. Instead, use the faster and more modern [camelCase](../../string/camelCase.md) from `es-toolkit`. ::: Converts a string to camel case. ```typescript const result = camelCase(str); ``` ## Usage ### `camelCase(str)` Converts a string to camel case. Camel case is a naming convention where the first word starts with a lowercase letter and subsequent words begin with uppercase letters, all without spaces. ```typescript import { camelCase } from 'es-toolkit/compat'; camelCase('camelCase'); // 'camelCase' camelCase('some whitespace'); // 'someWhitespace' camelCase('hyphen-text'); // 'hyphenText' camelCase('HTTPRequest'); // 'httpRequest' ``` Non-string values are also converted to strings before processing. ```typescript import { camelCase } from 'es-toolkit/compat'; camelCase(123); // '123' camelCase(null); // '' camelCase(undefined); // '' ``` #### Parameters * `str` (`string | object`, optional): The value to convert to camel case. #### Returns (`string`): Returns the string converted to camel case. --- --- url: /reference/string/capitalize.md --- # capitalize Converts the first character of a string to uppercase and the remaining characters to lowercase. ```typescript const result = capitalize(str); ``` ## Usage ### `capitalize(str)` Use `capitalize` when you want to make only the first letter uppercase and convert the rest to lowercase. It's useful for normalizing names or titles. ```typescript import { capitalize } from 'es-toolkit/string'; // Basic usage capitalize('hello'); // returns 'Hello' capitalize('WORLD'); // returns 'World' capitalize('javaScript'); // returns 'Javascript' ``` It also handles empty strings and single character strings correctly. ```typescript import { capitalize } from 'es-toolkit/string'; capitalize(''); // returns '' capitalize('a'); // returns 'A' capitalize('A'); // returns 'A' ``` You can use it to normalize user input or create titles. ```typescript import { capitalize } from 'es-toolkit/string'; // Normalize user names const userName = 'john DOE'; const formattedName = userName.split(' ').map(capitalize).join(' '); // returns 'John Doe' // Create titles const title = capitalize('welcome to our website'); // returns 'Welcome to our website' ``` #### Parameters * `str` (`string`): The string to capitalize the first character. #### Returns (`string`): Returns a new string with the first character capitalized and the rest in lowercase. --- --- url: /reference/compat/string/capitalize.md --- # capitalize (Lodash compatibility) ::: warning Use `capitalize` from `es-toolkit` This `capitalize` function operates slower due to handling non-string input values. Instead, use the faster and more modern [capitalize](../../string/capitalize.md) from `es-toolkit`. ::: Converts the first character of a string to uppercase and the remaining characters to lowercase. ```typescript const result = capitalize(str); ``` ## Usage ### `capitalize(str)` Converts the first character of a string to uppercase and the remaining characters to lowercase. This is useful for making the first impression of a word better or formatting it as a title. ```typescript import { capitalize } from 'es-toolkit/compat'; capitalize('fred'); // 'Fred' capitalize('FRED'); // 'Fred' capitalize('fRED'); // 'Fred' ``` Empty strings and non-string values can also be handled. ```typescript import { capitalize } from 'es-toolkit/compat'; capitalize(''); // '' capitalize(123); // '123' capitalize(null); // '' capitalize(undefined); // '' ``` #### Parameters * `str` (`string`, optional): The string to capitalize. #### Returns (`string`): Returns the string with the first character capitalized and the remaining characters in lowercase. --- --- url: /reference/compat/array/castArray.md --- # castArray (Lodash Compatibility) ::: warning Use `Array.from()` or array literals (`[value]`) This `castArray` function behaves complexly due to no-argument handling and `undefined` processing. Instead, use the clearer and more modern `Array.from()` or conditional array creation (`Array.isArray(value) ? value : [value]`). ::: Converts a value to an array if it's not already an array. ```typescript const result = castArray(value); ``` ## Usage ### `castArray(value?)` Use `castArray` when you want to ensure any value becomes an array. If the value is already an array, it returns as is. Otherwise, it creates a new array containing that value. ```typescript import { castArray } from 'es-toolkit/compat'; // Convert a number to an array castArray(1); // Returns: [1] // Convert a string to an array castArray('hello'); // Returns: ['hello'] // Convert an object to an array castArray({ a: 1 }); // Returns: [{ a: 1 }] ``` Values that are already arrays are returned as is. ```typescript import { castArray } from 'es-toolkit/compat'; castArray([1, 2, 3]); // Returns: [1, 2, 3] castArray(['a', 'b']); // Returns: ['a', 'b'] ``` `null` and `undefined` are also converted to arrays. ```typescript import { castArray } from 'es-toolkit/compat'; castArray(null); // Returns: [null] castArray(undefined); // Returns: [undefined] ``` When called without arguments, returns an empty array. ```typescript import { castArray } from 'es-toolkit/compat'; castArray(); // Returns: [] ``` #### Parameters * `value` (`T | readonly T[]`, optional): The value to convert to an array. If no argument is provided, returns an empty array. #### Returns (`T[]`): Returns the array if the input is already an array, otherwise returns a new array containing the input value. --- --- url: /reference/compat/math/ceil.md --- # ceil (Lodash Compatibility) ::: warning Use `Math.ceil` This `ceil` function operates slowly due to decimal place calculations and internal function calls. Use the faster and more modern `Math.ceil` instead. ::: Rounds a number up to the specified decimal places. ```typescript const result = ceil(number, precision); ``` ## Usage ### `ceil(number, precision?)` Use `ceil` when you want to round a number up to a specific decimal place. ```typescript import { ceil } from 'es-toolkit/compat'; // Basic ceiling (to integer) ceil(4.006); // Returns: 5 ceil(4.1); // Returns: 5 // Ceiling to 2 decimal places ceil(6.004, 2); // Returns: 6.01 ceil(6.001, 2); // Returns: 6.01 // Ceiling with negative precision (units of 10) ceil(6040, -2); // Returns: 6100 ceil(1234, -2); // Returns: 1300 // Negative numbers are also rounded up ceil(-4.1); // Returns: -4 ceil(-6.004, 2); // Returns: -6.00 ``` #### Parameters * `number` (`number`): The number to round up. * `precision` (`number`, optional): The number of decimal places to round up to. Defaults to `0`. #### Returns (`number`): Returns the number rounded up to the specified decimal places. --- --- url: /reference/array/chunk.md --- # chunk Splits an array into smaller arrays of a specified size. ```typescript const chunked = chunk(arr, size); ``` ## Usage ### `chunk(arr, size)` Use `chunk` when you want to split a long array into multiple smaller arrays of the same size. If the array cannot be evenly divided, the last chunk will contain the remaining elements. ```typescript import { chunk } from 'es-toolkit/array'; // Split a number array into chunks of size 2. chunk([1, 2, 3, 4, 5], 2); // Returns: [[1, 2], [3, 4], [5]] // Split a string array into chunks of size 3. chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3); // Returns: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']] ``` Splitting an empty array returns an empty array. ```typescript import { chunk } from 'es-toolkit/array'; chunk([], 2); // [] ``` #### Parameters * `arr` (`T[]`): The array to split. * `size` (`number`): The size of each chunk. Must be a positive integer. #### Returns (`T[][]`): A 2D array split into chunks of size `size`. #### Throws Throws an error if `size` is not a positive integer. ## Try It ::: sandpack ```ts index.ts import { chunk } from 'es-toolkit/array'; console.log(chunk([1, 2, 3, 4, 5], 2)); ``` ::: ## Lodash Compatibility When you import `chunk` from `es-toolkit/compat`, it is compatible with lodash. * Returns an empty array if `size` is less than 1. * Even if you provide a number with decimals for `size`, it will be rounded down to an integer. ```typescript import { chunk } from 'es-toolkit/compat'; chunk([1, 2, 3], 0); // Returns [] ``` ## Performance Comparison | | [Bundle Size](../../bundle-size.md) | [Runtime Performance](../../performance.md) | | ----------------- | ----------------------------------- | ------------------------------------------- | | es-toolkit | 238 bytes (92.4% smaller) | 9,338,821 times (11% slower) | | es-toolkit/compat | 307 bytes (90.2% smaller) | 9,892,157 times (5% slower) | | lodash-es | 3,153 bytes | 10,523,270 times | --- --- url: /reference/compat/array/chunk.md --- # chunk (Lodash Compatibility) ::: warning Use [`chunk`](../../array/chunk.md) from `es-toolkit` This `chunk` function operates slower due to handling of `null`, `undefined`, and default `size` values. For better performance and a more modern implementation, use [chunk](../../array/chunk.md) from `es-toolkit` instead. ::: Divides an array into smaller arrays of a specified size. ```typescript const chunked = chunk(arr, size); ``` ## Usage ### `chunk(arr, size?)` Use `chunk` when you want to split a long array into multiple smaller arrays of the same size. If the array cannot be divided evenly, the last array will contain the remaining elements. ```typescript import { chunk } from 'es-toolkit/compat'; // Divide an array of numbers into chunks of size 2. chunk([1, 2, 3, 4], 2); // Returns: [[1, 2], [3, 4]] // Divide an array of strings into chunks of size 3. chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3); // Returns: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']] // When not evenly divisible chunk([1, 2, 3, 4, 5], 2); // Returns: [[1, 2], [3, 4], [5]] ``` `null` or `undefined` are treated as empty arrays. ```typescript import { chunk } from 'es-toolkit/compat'; chunk(null, 2); // Returns: [] chunk(undefined, 2); // Returns: [] ``` If size is 0 or negative, returns an empty array. ```typescript import { chunk } from 'es-toolkit/compat'; chunk([1, 2, 3], 0); // Returns: [] chunk([1, 2, 3], -1); // Returns: [] ``` #### Parameters * `arr` (`ArrayLike | null | undefined`): The array to divide. * `size` (`number`, optional): The size of each smaller array. Default is `1`. #### Returns (`T[][]`): Returns a two-dimensional array divided by size `size`. --- --- url: /reference/math/clamp.md --- # clamp Clamps a number within a specified range. ```typescript const clamped = clamp(value, maximum); const clamped = clamp(value, minimum, maximum); ``` ## Usage ### `clamp(value, maximum)` Use `clamp` when you want to restrict a number to be at most a given maximum value. If the value exceeds the maximum, it's clamped to the maximum; otherwise, it returns the original value. ```typescript import { clamp } from 'es-toolkit/math'; // Clamp to maximum value const result1 = clamp(10, 5); // result1 is 5 (10 is clamped to maximum 5) const result2 = clamp(3, 5); // result2 is 3 (less than 5, so unchanged) ``` #### Parameters * `value` (`number`): The number to clamp. * `maximum` (`number`): The maximum value. #### Returns (`number`): Returns the number clamped to be at most the maximum value. ### `clamp(value, minimum, maximum)` Use `clamp` when you want to restrict a number within a given minimum and maximum range. If the value falls outside the range, it's clamped to the nearest boundary. ```typescript import { clamp } from 'es-toolkit/math'; // Clamp within minimum and maximum range const result1 = clamp(10, 5, 15); // result1 is 10 (within range 5-15) const result2 = clamp(2, 5, 15); // result2 is 5 (clamped to minimum 5) const result3 = clamp(20, 5, 15); // result3 is 15 (clamped to maximum 15) ``` #### Parameters * `value` (`number`): The number to clamp. * `minimum` (`number`): The minimum value. * `maximum` (`number`): The maximum value. #### Returns (`number`): Returns the number clamped within the specified range. --- --- url: /reference/compat/math/clamp.md --- # clamp (Lodash Compatibility) ::: warning Use `es-toolkit`'s [clamp](../../math/clamp.md) This `clamp` function operates slowly due to NaN validation and handling. Use the faster and more modern `es-toolkit`'s [clamp](../../math/clamp.md) instead. ::: Clamps a number within the specified range. ```typescript const clamped = clamp(number, lower, upper); ``` ## Usage ### `clamp(number, lower, upper)` Use `clamp` when you want to restrict a number between a specified minimum and maximum value. ```typescript import { clamp } from 'es-toolkit/compat'; // Basic usage clamp(3, 2, 4); // Returns: 3 (within range) clamp(0, 5, 10); // Returns: 5 (clamped to minimum) clamp(15, 5, 10); // Returns: 10 (clamped to maximum) // Handles negative numbers clamp(-5, -10, -1); // Returns: -5 clamp(-15, -10, -1); // Returns: -10 (clamped to minimum) ``` ### `clamp(number, upper)` When only one argument is provided, it's used as the maximum value. ```typescript import { clamp } from 'es-toolkit/compat'; // Specifying only maximum clamp(5, 3); // Returns: 3 (clamped to maximum) clamp(2, 3); // Returns: 2 (within range) clamp(1, 5); // Returns: 1 ``` NaN values are treated as 0. ```typescript import { clamp } from 'es-toolkit/compat'; clamp(5, NaN, 10); // Returns: 5 (NaN is treated as 0, so range is 0-10) clamp(5, 2, NaN); // Returns: 2 (NaN is treated as 0, so range is 0-2) ``` #### Parameters * `number` (`number`): The number to clamp. * `lower` (`number`): The minimum value. If only the second parameter is provided, it becomes the maximum value. * `upper` (`number`, optional): The maximum value. #### Returns (`number`): Returns the number clamped within the specified range. --- --- url: /reference/object/clone.md --- # clone Creates a shallow copy of the given value. ```typescript const cloned = clone(obj); ``` ## Usage ### `clone(obj)` Use `clone` when you want to create a shallow copy of objects, arrays, Dates, RegExps, and other values. A shallow copy means only the top-level properties are copied, and nested objects or arrays share references with the original. ```typescript import { clone } from 'es-toolkit/object'; // Primitive values are returned as-is const num = 29; const clonedNum = clone(num); console.log(clonedNum); // 29 console.log(clonedNum === num); // true // Shallow copy of an array const arr = [1, 2, 3]; const clonedArr = clone(arr); console.log(clonedArr); // [1, 2, 3] console.log(clonedArr === arr); // false // Shallow copy of an object const obj = { a: 1, b: 'es-toolkit', c: [1, 2, 3] }; const clonedObj = clone(obj); console.log(clonedObj); // { a: 1, b: 'es-toolkit', c: [1, 2, 3] } console.log(clonedObj === obj); // false console.log(clonedObj.c === obj.c); // true (nested array shares reference due to shallow copy) ``` It supports various JavaScript types like `Date`, `RegExp`, `Map`, and `Set`. ```typescript // Date object const date = new Date(); const clonedDate = clone(date); console.log(clonedDate !== date); // true console.log(clonedDate.getTime() === date.getTime()); // true // RegExp object const regex = /abc/gi; const clonedRegex = clone(regex); console.log(clonedRegex !== regex); // true console.log(clonedRegex.source === regex.source); // true // Map and Set const map = new Map([['key', 'value']]); const clonedMap = clone(map); console.log(clonedMap !== map); // true console.log(clonedMap.get('key')); // 'value' ``` #### Parameters * `obj` (`T`): The value to clone. It can be any type, such as objects, arrays, or primitive values. #### Returns (`T`): A shallow copy of the given value. --- --- url: /reference/compat/object/clone.md --- # clone (Lodash compatibility) ::: warning Use `clone` from `es-toolkit` instead This `clone` function is relatively slow due to complex logic that handles special object types. Use the faster and more modern [clone](../../object/clone.md) from `es-toolkit` instead. ::: Creates a shallow copy of an object. ```typescript const cloned = clone(value); ``` ## Usage ### `clone(value)` Use `clone` when you want to create a shallow copy of a value. It can copy various types of objects and primitive values. ```typescript import { clone } from 'es-toolkit/compat'; // Copying primitive values const num = 42; const clonedNum = clone(num); // Returns: 42 (same value) // Copying arrays const arr = [1, 2, 3]; const clonedArr = clone(arr); // Returns: [1, 2, 3] (new array instance) // Copying objects const obj = { a: 1, b: 'hello' }; const clonedObj = clone(obj); // Returns: { a: 1, b: 'hello' } (new object instance) // Copying Date objects const date = new Date('2023-01-01'); const clonedDate = clone(date); // Returns: new Date('2023-01-01') (new Date instance) // Copying regular expressions const regex = /hello/gi; regex.lastIndex = 3; const clonedRegex = clone(regex); // Returns: /hello/gi with lastIndex = 3 // Copying Map const map = new Map([ ['a', 1], ['b', 2], ]); const clonedMap = clone(map); // Returns: new Map([['a', 1], ['b', 2]]) // Copying Set const set = new Set([1, 2, 3]); const clonedSet = clone(set); // Returns: new Set([1, 2, 3]) ``` Nested objects are only shallowly copied. ```typescript import { clone } from 'es-toolkit/compat'; const nested = { a: 1, b: { c: 2, }, }; const clonedNested = clone(nested); console.log(clonedNested !== nested); // true (different objects) console.log(clonedNested.b === nested.b); // true (nested objects have same reference) ``` #### Parameters * `value` (`T`): The value to clone. #### Returns (`T`): Returns the cloned value. --- --- url: /reference/object/cloneDeep.md --- # cloneDeep Creates a deep copy of the given value. ```typescript const deepCloned = cloneDeep(obj); ``` ## Usage ### `cloneDeep(obj)` Use `cloneDeep` when you want to completely copy an object or array, including all nested structures. A deep copy creates new copies of all nested objects and arrays, making the original and the copy completely independent. ```typescript import { cloneDeep } from 'es-toolkit/object'; // Primitive values are returned as-is const num = 29; const clonedNum = cloneDeep(num); console.log(clonedNum); // 29 console.log(clonedNum === num); // true // Deep copy of nested objects const obj = { a: { b: { c: 'deep' } }, d: [1, 2, { e: 'nested' }] }; const clonedObj = cloneDeep(obj); console.log(clonedObj); // { a: { b: { c: 'deep' } }, d: [1, 2, { e: 'nested' }] } console.log(clonedObj === obj); // false console.log(clonedObj.a === obj.a); // false (nested objects are also copied) console.log(clonedObj.d === obj.d); // false (nested arrays are also copied) console.log(clonedObj.d[2] === obj.d[2]); // false (objects within arrays are also copied) // Modifying the original doesn't affect the copy const original = { a: { count: 1 } }; const copied = cloneDeep(original); original.a.count = 2; console.log(copied.a.count); // 1 (unchanged) ``` It supports various JavaScript types like `Map` and `Set`, and handles circular references safely. ```typescript // Deep copy of Map and Set const map = new Map([['key', { nested: 'value' }]]); const clonedMap = cloneDeep(map); console.log(clonedMap !== map); // true console.log(clonedMap.get('key') !== map.get('key')); // true (nested object is also copied) // Handles circular references safely const circular: any = { name: 'test' }; circular.self = circular; const clonedCircular = cloneDeep(circular); console.log(clonedCircular !== circular); // true console.log(clonedCircular.self === clonedCircular); // true (circular reference is maintained) ``` For read-only properties defined by getters, the return value of the getter is stored as a regular property in the copied object. ```typescript const source = { get computedValue() { return 42; }, normalValue: 'hello', }; const cloned = cloneDeep(source); console.log(cloned); // { computedValue: 42, normalValue: 'hello' } ``` #### Parameters * `obj` (`T`): The value to deeply copy. It can be any type, such as objects, arrays, or primitive values. #### Returns (`T`): A deep copy of the given value. --- --- url: /reference/compat/object/cloneDeep.md --- # cloneDeep (Lodash compatibility) ::: warning Use `cloneDeep` from `es-toolkit` instead This `cloneDeep` function is relatively slow due to complex logic that handles special object types. Use the faster and more modern [cloneDeep](../../object/cloneDeep.md) from `es-toolkit` instead. ::: Creates a deep copy of an object. ```typescript const cloned = cloneDeep(value); ``` ## Usage ### `cloneDeep(value)` Use `cloneDeep` when you want to create a deep copy of a value. It copies nested objects and arrays completely as new instances. ```typescript import { cloneDeep } from 'es-toolkit/compat'; // Copying primitive values const num = 42; const clonedNum = cloneDeep(num); // Returns: 42 (same value) // Deep copying arrays const arr = [1, [2, 3], { a: 4 }]; const clonedArr = cloneDeep(arr); clonedArr[1][0] = 99; console.log(arr[1][0]); // 2 (original is not changed) console.log(clonedArr[1][0]); // 99 // Deep copying objects const obj = { a: 1, b: { c: 2, d: { e: 3, }, }, }; const clonedObj = cloneDeep(obj); clonedObj.b.d.e = 99; console.log(obj.b.d.e); // 3 (original is not changed) console.log(clonedObj.b.d.e); // 99 // Deep copying Date objects const date = new Date('2023-01-01'); const clonedDate = cloneDeep(date); // Returns: new Date('2023-01-01') (new Date instance) // Complex nested structures const complex = { arr: [1, { nested: true }], map: new Map([['key', { value: 1 }]]), set: new Set([{ item: 1 }]), date: new Date(), }; const clonedComplex = cloneDeep(complex); // All nested objects are copied as completely new instances ``` Circular references are also handled correctly. ```typescript import { cloneDeep } from 'es-toolkit/compat'; const obj = { a: 1 }; obj.self = obj; // circular reference const cloned = cloneDeep(obj); console.log(cloned !== obj); // true console.log(cloned.self === cloned); // true (circular reference preserved) ``` #### Parameters * `value` (`T`): The value to deep clone. #### Returns (`T`): Returns the deeply cloned value. --- --- url: /reference/object/cloneDeepWith.md --- # cloneDeepWith Deeply clones the given value with a custom cloning function. ```typescript const customCloned = cloneDeepWith(obj, cloneValue); ``` ## Usage ### `cloneDeepWith(obj, cloneValue)` Use `cloneDeepWith` when you want to deeply copy an object or array with custom logic for specific values. If the custom function `cloneValue` returns a value, that value is used; if it returns `undefined`, the default deep copying method is used. ```typescript import { cloneDeepWith } from 'es-toolkit/object'; // Double numbers during cloning const obj = { a: 1, b: { c: 2, d: 'text' } }; const clonedObj = cloneDeepWith(obj, value => { if (typeof value === 'number') { return value * 2; } // Return undefined to use default cloning }); console.log(clonedObj); // { a: 2, b: { c: 4, d: 'text' } } // Add 1 to all array elements during cloning const arr = [1, [2, 3], { num: 4 }]; const clonedArr = cloneDeepWith(arr, value => { if (typeof value === 'number') { return value + 1; } }); console.log(clonedArr); // [2, [3, 4], { num: 5 }] ``` The custom function receives the current value, key, original object, and internal stack information as parameters. ```typescript const data = { user: { name: 'Alice', age: 30 }, settings: { theme: 'dark', lang: 'en' }, }; const result = cloneDeepWith(data, (value, key, obj, stack) => { // Clone 'user' object with special handling if (key === 'user' && typeof value === 'object') { return { ...value, cloned: true }; } // Add prefix to strings if (typeof value === 'string') { return `cloned_${value}`; } }); console.log(result); // { // user: { name: 'cloned_Alice', age: 30, cloned: true }, // settings: { theme: 'cloned_dark', lang: 'cloned_en' } // } ``` Using a custom function allows you to freely configure how objects are cloned. For example, you can copy `Date` objects to be one year in the future. ```typescript const data = { created: new Date('2023-01-01'), updated: new Date('2023-12-31'), name: 'Document', }; const cloned = cloneDeepWith(data, value => { // Set Date objects to one year in the future if (value instanceof Date) { const newDate = new Date(value); newDate.setFullYear(newDate.getFullYear() + 1); return newDate; } }); console.log(cloned.created.getFullYear()); // 2024 console.log(cloned.updated.getFullYear()); // 2024 ``` #### Parameters * `obj` (`T`): The value to deeply copy. * `cloneValue` (`(value: any, key: PropertyKey | undefined, obj: T, stack: Map) => any`): A custom cloning function. Return the value to clone, or return `undefined` to use the default method. * `value`: The current value being cloned. * `key`: The property name of the current value. * `obj`: The original object to clone. * `stack`: An internal stack to handle circular references. #### Returns (`T`): A deep copy processed through the custom function. --- --- url: /reference/compat/object/cloneDeepWith.md --- # cloneDeepWith (Lodash compatibility) ::: warning Implementing custom logic is recommended This `cloneDeepWith` function is relatively slow due to complex customizer function and deep copy processing. Instead, use `cloneDeep` and implement custom logic directly. ::: Creates a deep copy of an object using a customizer function. ```typescript const cloned = cloneDeepWith(value, customizer); ``` ## Usage ### `cloneDeepWith(value, customizer?)` Use `cloneDeepWith` when you want to customize how deep copying works. The customizer function controls how specific values are copied. ```typescript import { cloneDeepWith } from 'es-toolkit/compat'; // Basic usage (without customizer) const obj = { a: 1, b: { c: 2, }, }; const cloned = cloneDeepWith(obj); // Returns: { a: 1, b: { c: 2 } } (completely new instances) // Special handling for Date objects const obj2 = { name: 'test', createdAt: new Date('2023-01-01'), nested: { updatedAt: new Date('2023-12-31'), }, }; const cloned2 = cloneDeepWith(obj2, value => { if (value instanceof Date) { // Convert Date to timestamp number return value.getTime(); } // Returning undefined uses default deep copy behavior }); // Returns: { // name: 'test', // createdAt: 1672531200000, // nested: { updatedAt: 1703980800000 } // } // Transforming array elements const arr = [1, [2, 3], { a: 4, b: [5, 6] }]; const clonedArr = cloneDeepWith(arr, value => { if (typeof value === 'number') { return value * 10; } }); // Returns: [10, [20, 30], { a: 40, b: [50, 60] }] // Handling functions const objWithFunc = { data: { count: 1 }, increment: function () { this.data.count++; }, }; const clonedWithFunc = cloneDeepWith(objWithFunc, value => { if (typeof value === 'function') { // Convert function to string return value.toString(); } }); // Returns: { // data: { count: 1 }, // increment: "function() { this.data.count++; }" // } ``` Combining circular references and customizer: ```typescript import { cloneDeepWith } from 'es-toolkit/compat'; const obj = { a: 1, b: { c: 2 } }; obj.b.self = obj; // circular reference const cloned = cloneDeepWith(obj, value => { if (typeof value === 'number') { return value + 100; } }); console.log(cloned.a); // 101 console.log(cloned.b.c); // 102 console.log(cloned.b.self === cloned); // true (circular reference preserved) ``` #### Parameters * `value` (`T`): The value to deep clone. * `customizer` (`function`, optional): A function that determines how to copy. In the form `(value: any, key?: string, object?: any, stack?: Map) => any`. #### Returns (`T`): Returns the deep copy processed by the customizer. --- --- url: /reference/compat/object/cloneWith.md --- # cloneWith (Lodash compatibility) ::: warning Implementing custom logic is recommended This `cloneWith` function is relatively slow due to complex customizer function processing. Instead, use `clone` and implement custom logic directly. ::: Creates a shallow copy of an object using a customizer function. ```typescript const cloned = cloneWith(value, customizer); ``` ## Usage ### `cloneWith(value, customizer?)` Use `cloneWith` when you want to customize how copying works. The customizer function controls how specific values are copied. ```typescript import { cloneWith } from 'es-toolkit/compat'; // Basic usage (without customizer) const obj = { a: 1, b: 'hello' }; const cloned = cloneWith(obj); // Returns: { a: 1, b: 'hello' } (new object instance) // Transforming number values const obj2 = { a: 1, b: 2, c: 'text' }; const cloned2 = cloneWith(obj2, value => { const obj = {}; for (const key in value) { const val = value[key]; if (typeof val === 'number') { obj[key] = val * 2; } else { obj[key] = val; } } return obj; }); // Returns: { a: 2, b: 4, c: 'text' } // Transforming array elements const arr = [1, 2, 3]; const clonedArr = cloneWith(arr, value => { return value.map(x => x + 10); }); // Returns: [11, 12, 13] // Handling specific types const complex = { date: new Date('2023-01-01'), number: 42, text: 'hello', }; const clonedComplex = cloneWith(complex, value => { const obj = {}; for (const key in value) { const val = value[key]; if (val instanceof Date) { obj[key] = val.toISOString(); } else if (typeof val === 'string') { obj[key] = val.toUpperCase(); } else { obj[key] = val; } } return obj; }); // Returns: { date: '2023-01-01T00:00:00.000Z', number: 42, text: 'HELLO' } ``` If the customizer returns `undefined`, the default copy behavior is used. ```typescript import { cloneWith } from 'es-toolkit/compat'; const obj = { a: 1, b: { c: 2 } }; const cloned = cloneWith(obj, value => { // Return undefined for all values = use default copy return undefined; }); // Returns: { a: 1, b: { c: 2 } } (same result as clone) ``` #### Parameters * `value` (`T`): The value to clone. * `customizer` (`function`, optional): A function that determines how to copy. In the form `(value: any) => any`. #### Returns (`T`): Returns the shallow copy processed by the customizer. --- --- url: /reference/array/compact.md --- # compact Returns a new array with falsy values removed. ```typescript const compacted = compact(arr); ``` ## Usage ### `compact(arr)` Use `compact` when you want to remove falsy values (`false`, `null`, `0`, `-0`, `0n`, `''`, `undefined`, `NaN`) from an array. A new array containing only truthy values is returned. ```typescript import { compact } from 'es-toolkit/array'; // Remove various falsy values. compact([0, -0, 0n, 1, false, 2, '', 3, null, undefined, 4, NaN, 5]); // Returns: [1, 2, 3, 4, 5] // Remove empty strings from a string array. compact(['hello', '', 'world', '', '!']); // Returns: ['hello', 'world', '!'] ``` The type system automatically excludes falsy types. ```typescript import { compact } from 'es-toolkit/array'; const mixed: (string | number | false | null)[] = ['text', 0, false, null, 5]; const result = compact(mixed); // result's type is (string | number)[] ``` #### Parameters * `arr` (`T[]`): The array to remove falsy values from. #### Returns (`Array>`): A new array with falsy values removed. --- --- url: /reference/compat/array/compact.md --- # compact (Lodash compatible) ::: warning Use [`compact`](../../array/compact.md) from `es-toolkit` instead This `compact` function operates slowly due to handling `null` or `undefined`, `size` default value processing, and more. Use the faster and more modern [compact](../../array/compact.md) from `es-toolkit` instead. ::: Removes falsy values from an array. ```typescript const compacted = compact(arr); ``` ## Usage ### `compact(arr)` Use `compact` when you want to remove falsy values like `false`, `null`, `0`, `""`, `undefined`, `NaN` from an array. ```typescript import { compact } from 'es-toolkit/compat'; // Remove falsy values compact([0, 1, false, 2, '', 3]); // Returns: [1, 2, 3] compact(['a', null, 'b', undefined, 'c', NaN]); // Returns: ['a', 'b', 'c'] // BigInt 0 is also removed compact([0n, 1n, false, 2n]); // Returns: [1n, 2n] // Works with empty arrays compact([]); // Returns: [] // When all values are falsy compact([false, null, 0, '', undefined, NaN]); // Returns: [] ``` Truthy values are preserved. ```typescript import { compact } from 'es-toolkit/compat'; compact([1, 'hello', true, {}, []]); // Returns: [1, 'hello', true, {}, []] // Non-zero numbers compact([0, -1, 2, -3]); // Returns: [-1, 2, -3] ``` `null` or `undefined` arrays are treated as empty arrays. ```typescript import { compact } from 'es-toolkit/compat'; compact(null); // Returns: [] compact(undefined); // Returns: [] ``` #### Parameters * `arr` (`ArrayLike | null | undefined`): The array to compact. #### Returns (`T[]`): Returns a new array with falsy values removed. --- --- url: /compatibility.md --- # Compatibility with Lodash ::: tip ✅ Starting with version 1.39.3, we ensure 100% compatibility with Lodash `es-toolkit/compat` functions exactly like all Lodash functions while being lighter and faster. * It ensures identical behavior with Lodash's actual test code. * It has been adopted by popular open-source projects including Storybook, Recharts, and CKEditor, and is recommended by Nuxt. For detailed documentation of all available compat functions, check out our [Compat Reference](/reference/compat/array/castArray). ::: ```tsx // es-toolkit/compat aims to provide 100% feature parity with lodash import { chunk } from 'es-toolkit/compat'; chunk([1, 2, 3, 4], 0); // Returns [], which is identical to lodash ``` For maximum compatibility with `lodash`, use `es-toolkit/compat`, a compatibility layer that bridges the gap between the two libraries. This module is designed to provide an identical API to `lodash`, making it easier to switch between the two libraries. `es-toolkit/compat` has been thoroughly tested with real test cases from `lodash`. It's important to note that `es-toolkit/compat` may have a slight performance impact and a larger bundle size compared to the original `es-toolkit`. This module is designed to facilitate a smooth transition and should be replaced with the original `es-toolkit` for optimal performance once the migration is complete. ## Design Principles ::: info Design principles are subject to change. ::: Our compatibility layer aims to achieve feature parity with 100% accuracy for: * Features that are written as a test case in lodash. * Features that can be inferred from types of `@types/lodash` or `@types/lodash-es`. * Feature differences identified while migrating code from lodash to es-toolkit (please report these to our [issues page](https://github.com/toss/es-toolkit/issues)). However, the following are out of scope for `es-toolkit/compat`: * Implicit type conversions, such as converting an empty string to zero or false. * Functions that have specialized implementations for specific types of arrays, like [sortedUniq](https://lodash.com/docs/4.17.15#sortedUniq). * Handling cases where internal object prototypes, like `Array.prototype`, have been modified. * Managing cases with JavaScript realms. * Method chaining support through "Seq" methods. ## Implementation Status ::: info The following emojis indicate the status of each feature: * ✅: Completed (The function is fully implemented and has passed all tests with lodash test code.) * 📝: In Review (The function is implemented but hasn't been tested with lodash test code yet.) * ❌: Not Implemented (The function hasn't been implemented.) Even if a feature is marked "in review," it might already be under review to ensure it matches lodash perfectly, and it could already offer the same functionality. ::: --- --- url: /reference/compat/array/concat.md --- # concat (Lodash compatible) ::: warning Use spread operator or [`Array#concat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) instead This `concat` function operates inefficiently due to the complex way Lodash handles array concatenation. Use the more intuitive and modern spread operator `[...arr1, ...arr2]` or `arr1.concat(arr2)` instead. ::: Concatenates multiple arrays and values into a single array. ```typescript const result = concat(...values); ``` ## Usage ### `concat(...values)` Use `concat` when you want to concatenate multiple values and arrays in order to create a new array. Arrays are flattened, and individual values are added as is. ```typescript import { concat } from 'es-toolkit/compat'; // Concatenate individual values concat(1, 2, 3); // Returns: [1, 2, 3] // Concatenate arrays concat([1, 2], [3, 4]); // Returns: [1, 2, 3, 4] // Concatenate values and arrays together concat(1, [2, 3], 4); // Returns: [1, 2, 3, 4] ``` Nested arrays are flattened only one level deep. ```typescript import { concat } from 'es-toolkit/compat'; // Nested arrays are flattened only one level concat([1, [2, 3]], 4); // Returns: [1, [2, 3], 4] // More deeply nested arrays concat([1, [2, [3, 4]]], 5); // Returns: [1, [2, [3, 4]], 5] ``` Handles empty arrays and empty values. ```typescript import { concat } from 'es-toolkit/compat'; // With empty arrays concat([], [1, 2], [], [3]); // Returns: [1, 2, 3] // When no values are provided concat(); // Returns: [] ``` #### Parameters * `values` (`...(T | readonly T[])`): Values and arrays to concatenate. Each array is flattened one level. #### Returns (`T[]`): Returns a new array with all values and array elements concatenated in order. --- --- url: /reference/compat/util/cond.md --- # cond (Lodash Compatibility) ::: warning Use if-else or switch statements instead This `cond` function performs slowly due to complex iteratee processing, array transformations, and function validation. Use faster and clearer if-else or switch statements instead. ::: Creates a function that iterates through condition-function pairs, checking conditions in order and executing the first matching function. ```typescript const conditionFunction = cond(pairs); ``` ## Usage ### `cond(pairs)` Use `cond` when you want to check multiple conditions in order and execute the function corresponding to the first true condition. This is useful for expressing complex conditional logic in a functional style. ```typescript import { cond } from 'es-toolkit/compat'; // Basic usage const getValue = cond([ [x => x > 10, x => 'big'], [x => x > 5, x => 'medium'], [x => x > 0, x => 'small'], [() => true, () => 'zero or negative'], ]); console.log(getValue(15)); // "big" console.log(getValue(8)); // "medium" console.log(getValue(3)); // "small" console.log(getValue(-1)); // "zero or negative" ``` You can also use it for object pattern matching. ```typescript import { cond } from 'es-toolkit/compat'; const processUser = cond([ [user => user.role === 'admin', user => `Admin: ${user.name}`], [user => user.role === 'user', user => `User: ${user.name}`], [user => user.role === 'guest', user => `Guest: ${user.name}`], [() => true, () => 'Unknown role'], ]); console.log(processUser({ name: 'John', role: 'admin' })); // "Admin: John" console.log(processUser({ name: 'Jane', role: 'user' })); // "User: Jane" ``` Only the first true condition is executed. If all conditions are false, it returns `undefined`. ```typescript import { cond } from 'es-toolkit/compat'; const checkValue = cond([ [x => x > 10, x => 'greater than 10'], [x => x < 5, x => 'less than 5'], ]); console.log(checkValue(15)); // "greater than 10" console.log(checkValue(3)); // "less than 5" console.log(checkValue(7)); // undefined (no matching condition) ``` #### Parameters * `pairs` (`Array<[predicate, func]>`): An array of pairs consisting of condition functions and functions to execute. #### Returns (`(...args: any[]) => unknown`): Returns a new function that checks conditions and executes the first matching function. --- --- url: /reference/compat/predicate/conforms.md --- # conforms (Lodash Compatibility) Creates a function that checks if an object satisfies all the conditions defined in the given predicate object. ```typescript const checker = conforms(predicates); ``` ## Usage ### `conforms(source)` Use `conforms` when you need to check multiple properties against their respective conditions at once. This function generates a validation function that's useful for testing multiple objects later. ```typescript import { conforms } from 'es-toolkit/compat'; // Define condition functions const isPositive = n => n > 0; const isEven = n => n % 2 === 0; const isString = s => typeof s === 'string'; // Create a validator with multiple conditions const validator = conforms({ a: isPositive, b: isEven, c: isString, }); // Validate objects validator({ a: 2, b: 4, c: 'hello' }); // true (all conditions met) validator({ a: -1, b: 4, c: 'hello' }); // false (a is not positive) validator({ a: 2, b: 3, c: 'hello' }); // false (b is not even) validator({ a: 2, b: 4, c: 123 }); // false (c is not a string) // Use in array filtering const users = [ { age: 25, score: 80, name: 'Alice' }, { age: 17, score: 95, name: 'Bob' }, { age: 30, score: 75, name: 'Charlie' }, ]; const adultHighScorer = conforms({ age: n => n >= 18, score: n => n >= 80, }); const filteredUsers = users.filter(adultHighScorer); // [{ age: 25, score: 80, name: 'Alice' }] ``` #### Parameters * `source` (`Record boolean>`): An object containing predicate functions for each property. #### Returns (`(object: Record) => boolean`): Returns a function that checks if a given object satisfies all the conditions. --- --- url: /reference/compat/predicate/conformsTo.md --- # conformsTo (Lodash Compatibility) Checks if an object satisfies all given condition functions. ```typescript const result = conformsTo(target, source); ``` ## Usage ### `conformsTo(target, source)` Use `conformsTo` when you need to check if an object's properties satisfy all specified conditions. It applies each condition function to the corresponding property to check the results. ```typescript import { conformsTo } from 'es-toolkit/compat'; // Basic usage const object = { a: 1, b: 2 }; const conditions = { a: n => n > 0, b: n => n > 1, }; conformsTo(object, conditions); // true (all conditions satisfied) // Various conditions const user = { name: 'Alice', age: 25, active: true }; const userValidation = { name: s => typeof s === 'string' && s.length > 0, age: n => typeof n === 'number' && n >= 18, active: b => typeof b === 'boolean', }; conformsTo(user, userValidation); // true // When conditions are not satisfied const invalidUser = { name: '', age: 15, active: 'yes' }; conformsTo(invalidUser, userValidation); // false // Partial condition checking const partialConditions = { age: n => n >= 21, }; conformsTo(user, partialConditions); // true (only checks age) // When property is missing const incompleteObject = { a: 1 }; // no b property const strictConditions = { a: n => n > 0, b: n => n > 0, }; conformsTo(incompleteObject, strictConditions); // false (b property is missing) ``` #### Parameters * `target` (`Record`): The object to inspect. * `source` (`Record boolean>`): An object with condition functions for each property. #### Returns (`boolean`): Returns `true` if the object satisfies all conditions, otherwise `false`. --- --- url: /reference/compat/util/constant.md --- # constant (Lodash Compatibility) ::: warning Use arrow functions instead This `constant` function creates an unnecessary function wrapper for simple tasks, which creates unnecessary overhead. Instead, use a simpler and more intuitive arrow function. ::: Creates a function that always returns the given value. ```typescript const constantFunction = constant(value); ``` ## Usage ### `constant(value)` Use `constant` when you need a function that always returns a specific value. It's useful in functional programming when providing default values or as callback functions. ```typescript import { constant } from 'es-toolkit/compat'; // Basic usage const always42 = constant(42); console.log(always42()); // 42 const alwaysHello = constant('hello'); console.log(alwaysHello()); // "hello" ``` It's convenient when used with array map or other higher-order functions. ```typescript import { constant } from 'es-toolkit/compat'; // Fill all elements with 0 const numbers = [1, 2, 3, 4, 5]; const zeros = numbers.map(constant(0)); console.log(zeros); // [0, 0, 0, 0, 0] // Replace all elements with the same object const users = ['alice', 'bob', 'charlie']; const defaultUser = users.map(constant({ role: 'user', active: true })); console.log(defaultUser); // [{ role: 'user', active: true }, { role: 'user', active: true }, { role: 'user', active: true }] ``` Can also be used for providing conditional default values. ```typescript import { constant } from 'es-toolkit/compat'; function processData(data, fallback = constant('default value')) { return data || fallback(); } console.log(processData(null)); // "default value" console.log(processData('actual data')); // "actual data" ``` Maintains object references. ```typescript import { constant } from 'es-toolkit/compat'; const obj = { a: 1 }; const getObj = constant(obj); console.log(getObj() === obj); // true (same object reference) ``` #### Parameters * `value` (`T`, optional): The value the function should return. If not provided, returns `undefined`. #### Returns (`() => T | undefined`): Returns a new function that always returns the given value. --- --- url: /reference/string/constantCase.md --- # constantCase Converts a string to constant case. ```typescript const result = constantCase(str); ``` ## Usage ### `constantCase(str)` Use `constantCase` when you want to convert a string to constant case. Constant case is a naming convention where all characters are uppercase and words are separated by underscores (`_`). ```typescript import { constantCase } from 'es-toolkit/string'; // Convert various string formats to constant case constantCase('hello world'); // returns 'HELLO_WORLD' constantCase('camelCase'); // returns 'CAMEL_CASE' constantCase('some-kebab-case'); // returns 'SOME_KEBAB_CASE' constantCase('PascalCase'); // returns 'PASCAL_CASE' constantCase('snake_case'); // returns 'SNAKE_CASE' ``` It's a commonly used naming convention when defining constants in JavaScript or other programming languages. ```typescript import { constantCase } from 'es-toolkit/string'; // Generate environment variable names const configKey = 'api base url'; const envVar = constantCase(configKey); // 'API_BASE_URL' // Generate constant names const settingName = 'maximum retry count'; const constantName = constantCase(settingName); // 'MAXIMUM_RETRY_COUNT' ``` It also properly handles strings with spaces or special characters. ```typescript import { constantCase } from 'es-toolkit/string'; constantCase('HTTP Request'); // returns 'HTTP_REQUEST' constantCase('user-agent-string'); // returns 'USER_AGENT_STRING' constantCase(' multiple spaces '); // returns 'MULTIPLE_SPACES' ``` #### Parameters * `str` (`string`): The string to convert to constant case. #### Returns (`string`): Returns a new string converted to constant case. --- --- url: /reference/array/countBy.md --- # countBy Categorizes the elements of an array based on a transformation function result and returns an object with counts. ```typescript const counted = countBy(arr, mapper); ``` ## Usage ### `countBy(arr, mapper)` Use `countBy` when you want to categorize array elements by a specific criterion and count each group. It groups elements using the value returned by the transformation function as a key and calculates the number of elements in each group. ```typescript import { countBy } from 'es-toolkit/array'; // Count numbers by odd/even categorization. countBy([1, 2, 3, 4, 5], item => (item % 2 === 0 ? 'even' : 'odd')); // Returns: { odd: 3, even: 2 } ``` You can also count based on a specific property of an object array. ```typescript import { countBy } from 'es-toolkit/array'; const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 25 }, { name: 'David', age: 30 }, ]; countBy(users, user => user.age); // Returns: { '25': 2, '30': 2 } ``` #### Parameters * `arr` (`T[]`): The array to count elements from. * `mapper` (`(item: T, index: number, array: T[]) => K`): A function that returns the value to use as the categorization criterion, called with each item, its index, and the array. #### Returns (`Record`): An object representing how many elements exist for each categorization criterion. ## Examples ```typescript // Using index parameter const arr = ['a', 'b', 'c', 'd']; const result = countBy(arr, (item, index) => (index < 2 ? 'first' : 'rest')); // Returns: { first: 2, rest: 2 } // Using array parameter const numbers = [1, 2, 3, 4]; const result2 = countBy(numbers, (item, index, arr) => (item < arr.length / 2 ? 'small' : 'large')); // Returns: { small: 1, large: 3 } ``` --- --- url: /reference/map/countBy.md --- # countBy (for `Map`s) Counts the occurrences of items in a Map based on a transformation function. ```typescript const counts = countBy(map, mapper); ``` ::: info This function is available exclusively from `es-toolkit/map` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `countBy(map, mapper)` Use `countBy` when you want to count how many entries in a Map fall into different categories. Provide a function that generates a key from each value-key pair, and it returns a Map with the generated keys and their counts as values. The count is incremented for each entry for which the transformation produces the same key. ```typescript import { countBy } from 'es-toolkit/map'; const map = new Map([ ['a', 1], ['b', 2], ['c', 1], ]); const result = countBy(map, value => value); // Result: Map(2) { 1 => 2, 2 => 1 } ``` You can count entries based on various criteria. ```typescript import { countBy } from 'es-toolkit/map'; // Count by value property const users = new Map([ ['user1', { name: 'Alice', age: 25, department: 'Engineering' }], ['user2', { name: 'Bob', age: 30, department: 'Engineering' }], ['user3', { name: 'Charlie', age: 35, department: 'Sales' }], ]); const byDepartment = countBy(users, user => user.department); // Result: Map(2) { 'Engineering' => 2, 'Sales' => 1 } // Count by derived value const ages = new Map([ ['p1', 25], ['p2', 30], ['p3', 25], ['p4', 40], ]); const ageGroups = countBy(ages, age => (age < 30 ? 'young' : 'senior')); // Result: Map(2) { 'young' => 2, 'senior' => 2 } // Count using both value and key const items = new Map([ ['alice', 20], ['bob', 30], ['carol', 20], ]); const firstLetter = countBy(items, (value, key) => key[0]); // Result: Map(3) { 'a' => 1, 'b' => 1, 'c' => 1 } ``` #### Parameters * `map` (`Map`): The Map to count occurrences from. * `mapper` (`(value: V, key: K, object: Map) => K2`): The function to produce a key for counting. #### Returns (`Map`): A Map containing the mapped keys and their counts. --- --- url: /reference/set/countBy.md --- # countBy (for `Set`s) Counts the occurrences of items in a Set based on a transformation function. ```typescript const counts = countBy(set, mapper); ``` ::: info This function is available exclusively from `es-toolkit/set` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `countBy(set, mapper)` Use `countBy` when you want to count how many elements in a Set fall into different categories. Provide a function that generates a key from each value, and it returns a Map with the generated keys and their counts as values. The count is incremented for each element for which the transformation produces the same key. ```typescript import { countBy } from 'es-toolkit/set'; const set = new Set([1, 2, 3, 4, 5]); const result = countBy(set, value => (value % 2 === 0 ? 'even' : 'odd')); // Result: Map(2) { 'odd' => 3, 'even' => 2 } ``` You can count elements based on various criteria. ```typescript import { countBy } from 'es-toolkit/set'; // Count by string length const words = new Set(['apple', 'banana', 'cherry', 'date']); const byLength = countBy(words, word => word.length); // Result: Map(3) { 5 => 1, 6 => 2, 4 => 1 } // Count by property const users = new Set([ { name: 'Alice', role: 'admin' }, { name: 'Bob', role: 'user' }, { name: 'Charlie', role: 'user' }, { name: 'Diana', role: 'admin' }, ]); const byRole = countBy(users, user => user.role); // Result: Map(2) { 'admin' => 2, 'user' => 2 } // Count by derived category const ages = new Set([15, 25, 35, 45, 55]); const ageGroups = countBy(ages, age => { if (age < 18) return 'minor'; if (age < 65) return 'adult'; return 'senior'; }); // Result: Map(2) { 'minor' => 1, 'adult' => 4 } ``` #### Parameters * `set` (`Set`): The Set to count occurrences from. * `mapper` (`(value: T, value2: T, set: Set) => K`): The function to produce a key for counting. #### Returns (`Map`): A Map containing the mapped keys and their counts. --- --- url: /reference/compat/array/countBy.md --- # countBy (Lodash compatible) ::: warning Use `countBy` from `es-toolkit` instead This `countBy` function operates slowly due to complex transformation function processing and type conversion. Use the faster and more modern [countBy](../../array/countBy.md) from `es-toolkit` instead. ::: Counts the occurrences of elements in an array or object, grouped by a criterion. ```typescript const counts = countBy(collection, iteratee); ``` ## Usage ### `countBy(collection, iteratee?)` Use `countBy` when you want to group elements of an array or object by some criterion and count how many elements are in each group. The value returned by the iteratee function becomes the key, and the count of elements with that key becomes the value. ```typescript import { countBy } from 'es-toolkit/compat'; // Group numbers by floor value countBy([6.1, 4.2, 6.3], Math.floor); // Returns: { '4': 1, '6': 2 } // Group strings by length countBy(['one', 'two', 'three'], 'length'); // Returns: { '3': 2, '5': 1 } // Group users by age range const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 35 }, { name: 'Charlie', age: 25 }, ]; countBy(users, user => Math.floor(user.age / 10) * 10); // Returns: { '20': 2, '30': 1 } ``` Works with objects too. ```typescript import { countBy } from 'es-toolkit/compat'; // Classify object values by type const obj = { a: 1, b: 'string', c: 2, d: 'text' }; countBy(obj, value => typeof value); // Returns: { 'number': 2, 'string': 2 } ``` When used without an iteratee function, groups by the value itself. ```typescript import { countBy } from 'es-toolkit/compat'; // Group by value itself countBy([1, 2, 1, 3, 2, 1]); // Returns: { '1': 3, '2': 2, '3': 1 } // Group boolean values countBy([true, false, true, true]); // Returns: { 'true': 3, 'false': 1 } ``` `null` or `undefined` collections return an empty object. ```typescript import { countBy } from 'es-toolkit/compat'; countBy(null); // Returns: {} countBy(undefined); // Returns: {} ``` #### Parameters * `collection` (`ArrayLike | object | null | undefined`): The array or object to process. * `iteratee` (`ValueIteratee`, optional): The function that defines the grouping criterion for each element. Can be a function, property name, or partial object. #### Returns (`Record`): Returns an object with keys for each group and values representing the count of elements in that group. --- --- url: /reference/compat/object/create.md --- # create (Lodash compatibility) ::: warning Use `Object.create` instead This `create` function is relatively slow due to complex property processing logic. Use the faster and more modern `Object.create` instead. ::: Creates a new object that inherits from the given prototype. ```typescript const obj = create(prototype, properties); ``` ## Usage ### `create(prototype, properties?)` Use `create` when you want to create a new object based on a prototype. You can optionally add properties as well. ```typescript import { create } from 'es-toolkit/compat'; // Basic usage const person = { greet() { console.log(`Hello, my name is ${this.name}`); }, }; const john = create(person, { name: 'John' }); john.greet(); // "Hello, my name is John" // Checking method inheritance console.log('greet' in john); // true console.log(john.hasOwnProperty('greet')); // false (inherited property) console.log(john.hasOwnProperty('name')); // true (own property) // Complex prototype const animal = { type: 'animal', makeSound() { console.log('Some generic sound'); }, }; const dog = create(animal, { breed: 'Golden Retriever', name: 'Buddy', makeSound() { console.log('Woof!'); }, }); console.log(dog.type); // 'animal' (inherited) console.log(dog.breed); // 'Golden Retriever' (own property) dog.makeSound(); // 'Woof!' (overridden method) // null prototype const cleanObj = create(null, { data: 'value' }); console.log(cleanObj.toString); // ƒ toString() { [native code] } (null is equivalent to {}) // Inheriting empty object const empty = create({}); console.log(Object.getPrototypeOf(empty)); // {} (empty object) ``` Only enumerable string keys are copied for properties. ```typescript import { create } from 'es-toolkit/compat'; const proto = { inherited: true }; const props = { visible: 'yes', [Symbol('hidden')]: 'no', // Symbol keys are not copied }; // Add non-enumerable property Object.defineProperty(props, 'hidden', { value: 'secret', enumerable: false, }); const obj = create(proto, props); console.log(obj.visible); // 'yes' console.log(obj.hidden); // undefined (non-enumerable) console.log(obj[Symbol('hidden')]); // undefined (Symbol key) console.log(obj.inherited); // true (inherited) ``` #### Parameters * `prototype` (`T extends object`): The prototype object to inherit from. * `properties` (`U extends object`, optional): Properties to add to the new object. #### Returns (`T & U`): Returns a new object that inherits from the prototype and has the specified properties. --- --- url: /reference/function/curry.md --- # curry Curries a function so it can be called with one argument at a time. ```typescript const curriedFunc = curry(func); ``` ## Usage ### `curry(func)` Use `curry` when you want to partially apply a function. The curried function returns a new function until it receives all required arguments. Once all arguments are provided, the original function is executed. ```typescript import { curry } from 'es-toolkit/function'; function sum(a: number, b: number, c: number) { return a + b + c; } const curriedSum = curry(sum); // Provide value `10` for argument `a` const sum10 = curriedSum(10); // Provide value `15` for argument `b` const sum25 = sum10(15); // Provide value `5` for argument `c` // All arguments have been received, so now it returns the value const result = sum25(5); // Returns: 30 ``` This is useful for creating reusable functions. ```typescript function multiply(a: number, b: number) { return a * b; } const curriedMultiply = curry(multiply); const double = curriedMultiply(2); const triple = curriedMultiply(3); double(5); // Returns: 10 triple(5); // Returns: 15 ``` #### Parameters * `func` (`(...args: any[]) => any`): The function to curry. #### Returns (`(...args: any[]) => any`): A curried function that can be called with one argument at a time. --- --- url: /reference/compat/function/curry.md --- # curry (Lodash Compatibility) ::: warning Use `es-toolkit`'s `curry` or manual closures This `curry` function performs slowly due to complex placeholder handling, arity validation, and argument composition logic. If you don't need placeholders, use the faster `es-toolkit`'s [`curry`](../../function/curry.md) or simple closures instead. ::: Curries a function so it can accept arguments one at a time or multiple at once. ```typescript const curriedFunction = curry(func, arity); ``` ## Usage ### `curry(func, arity)` Use `curry` when you want to curry a function to make partial application easier. It's useful for providing arguments step by step or using placeholders to provide arguments at specific positions later. ```typescript import { curry } from 'es-toolkit/compat'; // Basic usage function add(a, b, c) { return a + b + c; } const curriedAdd = curry(add); // Can be called in various ways console.log(curriedAdd(1)(2)(3)); // 6 console.log(curriedAdd(1, 2)(3)); // 6 console.log(curriedAdd(1)(2, 3)); // 6 console.log(curriedAdd(1, 2, 3)); // 6 ``` Comparison with main library curry: ```typescript // compat version (flexible, but slower) import { curry } from 'es-toolkit/compat'; const curriedCompat = curry(add); curriedCompat(1, 2)(3); // supported curriedCompat(1)(curry.placeholder, 3)(2); // placeholder support // main library version (faster, but one at a time only) import { curry } from 'es-toolkit'; const curriedMain = curry(add); curriedMain(1)(2)(3); // supported curriedMain(1, 2)(3); // not supported ``` Using placeholder feature: ```typescript import { curry } from 'es-toolkit/compat'; function greet(greeting, name, punctuation) { return `${greeting}, ${name}${punctuation}`; } const curriedGreet = curry(greet); // Skip middle arguments with placeholder const greetWithExclamation = curriedGreet(curry.placeholder, curry.placeholder, '!'); console.log(greetWithExclamation('Hello', 'John')); // "Hello, John!" const sayHello = curriedGreet('Hello'); console.log(sayHello(curry.placeholder, '~')('Jane')); // "Hello, Jane~" ``` Using in functional programming: ```typescript import { curry } from 'es-toolkit/compat'; // Create mapping functions const map = curry((fn, array) => array.map(fn)); const filter = curry((predicate, array) => array.filter(predicate)); const numbers = [1, 2, 3, 4, 5]; // Create reusable functions const double = x => x * 2; const isEven = x => x % 2 === 0; const mapDouble = map(double); const filterEven = filter(isEven); console.log(mapDouble(numbers)); // [2, 4, 6, 8, 10] console.log(filterEven(numbers)); // [2, 4] // Function composition const processNumbers = nums => mapDouble(filterEven(nums)); console.log(processNumbers(numbers)); // [4, 8] ``` Configuring API client: ```typescript import { curry } from 'es-toolkit/compat'; function apiRequest(method, baseUrl, endpoint, options) { return fetch(`${baseUrl}${endpoint}`, { method, ...options, }); } const curriedApiRequest = curry(apiRequest); // Create specialized functions with default settings const apiGet = curriedApiRequest('GET', 'https://api.example.com'); const apiPost = curriedApiRequest('POST', 'https://api.example.com'); // Include authentication headers const authenticatedPost = apiPost(curry.placeholder, { headers: { Authorization: 'Bearer token123' }, }); // Usage apiGet('/users'); // GET https://api.example.com/users authenticatedPost('/users'); // POST with auth headers ``` Mathematical operation functions: ```typescript import { curry } from 'es-toolkit/compat'; const calculate = curry((operation, a, b) => { switch (operation) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; default: throw new Error('Unsupported operation'); } }); // Specialized operation functions const add = calculate('+'); const subtract = calculate('-'); const multiply = calculate('*'); console.log(add(5, 3)); // 8 console.log(subtract(10)(4)); // 6 console.log(multiply(3, 4)); // 12 // Fix second operand with placeholder const addFive = calculate('+', curry.placeholder, 5); console.log(addFive(10)); // 15 ``` Specifying arity: ```typescript import { curry } from 'es-toolkit/compat'; function variableArgsFunction(a, b, c, ...rest) { return [a, b, c, rest]; } // Limit arity to 3 const curriedFixed = curry(variableArgsFunction, 3); console.log(curriedFixed(1)(2)(3)); // [1, 2, 3, []] console.log(curriedFixed(1, 2)(3)); // [1, 2, 3, []] // Use without arity (default: function.length) const curriedDefault = curry(variableArgsFunction); // arity = 3 ``` Simple currying alternative: ```typescript // Using curry const curriedAdd = curry((a, b, c) => a + b + c); // Manual closure (faster) const manualCurry = a => b => c => a + b + c; // Both produce the same result console.log(curriedAdd(1)(2)(3)); // 6 console.log(manualCurry(1)(2)(3)); // 6 ``` Constructor functions are also supported: ```typescript import { curry } from 'es-toolkit/compat'; function Person(name, age, city) { this.name = name; this.age = age; this.city = city; } const CurriedPerson = curry(Person); const SeoulPerson = CurriedPerson(curry.placeholder, curry.placeholder, 'Seoul'); const person1 = new SeoulPerson('John', 30); const person2 = new SeoulPerson('Jane', 25); console.log(person1.city); // "Seoul" console.log(person2.city); // "Seoul" ``` #### Parameters * `func` (`Function`): The function to curry. * `arity` (`number`, optional): The arity (number of arguments) of the function. If omitted, `func.length` is used. #### Returns (`Function & { placeholder: symbol }`): Returns the curried function. The `placeholder` property allows you to control argument positions. --- --- url: /reference/function/curryRight.md --- # curryRight Curries a function from right to left so it can be called with one argument at a time. ```typescript const curriedFunc = curryRight(func); ``` ## Usage ### `curryRight(func)` Use `curryRight` when you want to partially apply a function from right to left. Unlike regular `curry`, it receives arguments starting from the last one. ```typescript import { curryRight } from 'es-toolkit/function'; function sum(a: number, b: number, c: number) { return a + b + c; } const curriedSum = curryRight(sum); // Provide value `10` for argument `c` const add10 = curriedSum(10); // Provide value `15` for argument `b` const add25 = add10(15); // Provide value `5` for argument `a` // All arguments have been received, so now it returns the value const result = add25(5); // Returns: 30 ``` This is useful when applying arguments from right to left feels more natural. ```typescript function greet(greeting: string, name: string) { return `${greeting}, ${name}!`; } const curriedGreet = curryRight(greet); const greetJohn = curriedGreet('John'); greetJohn('Hello'); // Returns: 'Hello, John!' greetJohn('Hi'); // Returns: 'Hi, John!' ``` #### Parameters * `func` (`(...args: any[]) => any`): The function to curry. #### Returns (`(...args: any[]) => any`): A curried function that can be called with one argument at a time from right to left. --- --- url: /reference/compat/function/curryRight.md --- # curryRight (Lodash Compatibility) ::: warning Use `es-toolkit`'s [`curryRight`](../../function/curryRight.md) or manual closures instead This `curryRight` function operates slowly due to complex placeholder handling, arity validation, and argument composition logic. If you don't need placeholders, use the faster `es-toolkit`'s [`curryRight`](../../function/curryRight.md) or simple closures instead. ::: Curries a function from right to left, creating a function that accepts arguments one at a time or several at a time, starting from the last argument. ```typescript const curriedFunction = curryRight(func, arity); ``` ## Usage ### `curryRight(func, arity)` Use `curryRight` when you want to curry a function from right to left and partially apply arguments starting from the last one. Unlike regular `curry`, it processes arguments starting from the last one first. ```typescript import { curryRight } from 'es-toolkit/compat'; // Basic usage function subtract(a, b, c) { return a - b - c; } const curriedSubtract = curryRight(subtract); // Currying from right (starting from last argument) console.log(curriedSubtract(1)(2)(5)); // 5 - 2 - 1 = 2 console.log(curriedSubtract(1, 2)(5)); // 5 - 2 - 1 = 2 console.log(curriedSubtract(1)(2, 5)); // 2 - 5 - 1 = -4 console.log(curriedSubtract(1, 2, 5)); // 1 - 2 - 5 = -6 ``` Difference between `curry` and `curryRight`: ```typescript import { curry, curryRight } from 'es-toolkit/compat'; function divide(a, b, c) { return a / b / c; } // Regular curry (from left) const leftCurried = curry(divide); console.log(leftCurried(12)(3)(2)); // ((12 / 3) / 2) = 2 // curryRight (from right) const rightCurried = curryRight(divide); console.log(rightCurried(2)(3)(12)); // ((12 / 3) / 2) = 2 // The last provided 12 becomes the first argument (a) ``` Comparison with main library: ```typescript // compat version (flexible, but slower) import { curryRight } from 'es-toolkit/compat'; const curriedCompat = curryRight(subtract); curriedCompat(1, 2)(3); // supported curriedCompat(1)(curryRight.placeholder, 3)(2); // placeholder supported // main library version (faster, but one at a time only) import { curryRight } from 'es-toolkit'; const curriedMain = curryRight(subtract); curriedMain(1)(2)(3); // supported curriedMain(1, 2)(3); // not supported ``` Using placeholder feature: ```typescript import { curryRight } from 'es-toolkit/compat'; function formatMessage(name, action, time) { return `${name} did ${action} at ${time}`; } const curriedFormat = curryRight(formatMessage); // Skip specific positions with placeholder const todayAction = curriedFormat('today'); const todayLoginAction = todayAction(curryRight.placeholder, 'login'); console.log(todayLoginAction('John')); // "John did login at today" // Fix time first const morningFormat = curriedFormat('9 AM'); console.log(morningFormat('comment', 'Jane')); // "Jane did comment at 9 AM" ``` Using in array processing: ```typescript import { curryRight } from 'es-toolkit/compat'; // Take a specific number of items from the end of an array function takeFromEnd(array, count, separator = ', ') { return array.slice(-count).join(separator); } const curriedTake = curryRight(takeFromEnd); // Create function that separates with comma const takeWithComma = curriedTake(', '); // Get last 3 items const takeLast3 = takeWithComma(3); const fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']; console.log(takeLast3(fruits)); // "orange, grape, kiwi" // Use different separator const takeWithDash = curriedTake(' - '); console.log(takeWithDash(2, fruits)); // "grape - kiwi" ``` Using in function composition: ```typescript import { curryRight } from 'es-toolkit/compat'; // Log output function function logWithPrefix(message, level, timestamp) { return `[${timestamp}] ${level}: ${message}`; } const curriedLog = curryRight(logWithPrefix); // Fix with current time const currentTimeLog = curriedLog(new Date().toISOString()); // Create loggers by level const errorLog = currentTimeLog('ERROR'); const infoLog = currentTimeLog('INFO'); const debugLog = currentTimeLog('DEBUG'); // Usage console.log(errorLog('Database connection failed')); console.log(infoLog('Server started')); console.log(debugLog('Processing user request')); ``` Functional programming pipeline: ```typescript import { curryRight } from 'es-toolkit/compat'; // Data transformation functions const mapWith = curryRight((array, fn) => array.map(fn)); const filterWith = curryRight((array, predicate) => array.filter(predicate)); const reduceWith = curryRight((array, reducer, initial) => array.reduce(reducer, initial)); const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Define transformation functions const double = x => x * 2; const isEven = x => x % 2 === 0; const sum = (acc, val) => acc + val; // Compose pipeline (right first) const processNumbers = nums => { return reduceWith(filterWith(mapWith(nums, double), isEven), sum, 0); }; console.log(processNumbers(numbers)); // Double all numbers, filter even ones, then sum ``` API request builder: ```typescript import { curryRight } from 'es-toolkit/compat'; function makeRequest(url, method, headers, body) { return fetch(url, { method, headers, body }); } const curriedRequest = curryRight(makeRequest); // Set body first const withJsonBody = curriedRequest(JSON.stringify({ data: 'test' })); // Add headers const withHeaders = withJsonBody({ 'Content-Type': 'application/json', Authorization: 'Bearer token123', }); // Set POST method const postRequest = withHeaders('POST'); // Final usage postRequest('/api/data') .then(response => response.json()) .then(data => console.log(data)); ``` Manual currying alternative: ```typescript // Using curryRight const curriedSubtract = curryRight((a, b, c) => a - b - c); // Manual closure (faster, from right) const manualCurryRight = c => b => a => a - b - c; // Both give same result console.log(curriedSubtract(1)(2)(5)); // 2 console.log(manualCurryRight(1)(2)(5)); // 2 ``` Specifying arity: ```typescript import { curryRight } from 'es-toolkit/compat'; function variableArgsFunction(a, b, c, ...rest) { return { a, b, c, rest }; } // Limit arity to 3 (ignore rest) const curriedFixed = curryRight(variableArgsFunction, 3); // Receive in order c, b, a from right console.log(curriedFixed(3)(2)(1)); // { a: 1, b: 2, c: 3, rest: [] } ``` #### Parameters * `func` (`Function`): The function to curry from right to left. * `arity` (`number`, optional): The arity (number of arguments) of the function. If omitted, `func.length` is used. #### Returns (`Function & { placeholder: symbol }`): Returns a function curried from right to left. The `placeholder` property can be used to control argument positions. --- --- url: /reference/function/debounce.md --- # debounce Creates a debounced function that delays the invocation of a function. ```typescript const debouncedFunc = debounce(func, debounceMs, options); ``` ## Usage ### `debounce(func, debounceMs, options)` Use `debounce` when you want to combine consecutive calls into one. The debounced function executes after the specified time has passed since the last call. This is useful for handling rapid events like search input or window resizing. ```typescript import { debounce } from 'es-toolkit/function'; const debouncedFunction = debounce(() => { console.log('executed'); }, 1000); // Logs 'executed' if not called again within 1 second debouncedFunction(); // Cancels the previous call debouncedFunction.cancel(); // Immediately executes the pending function debouncedFunction.flush(); ``` This can be useful for calling heavy APIs in response to user input, such as search. ```typescript const searchInput = document.getElementById('search'); const searchResults = debounce(async (query: string) => { const results = await fetchSearchResults(query); displayResults(results); }, 300); searchInput.addEventListener('input', e => { searchResults(e.target.value); }); ``` You can cancel debounced function calls using [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal). ```typescript const controller = new AbortController(); const debouncedWithSignalFunction = debounce( () => { console.log('Function executed'); }, 1000, { signal: controller.signal } ); // Logs 'executed' if not called again within 1 second debouncedWithSignalFunction(); // Cancels the debounce function call controller.abort(); ``` #### Parameters * `func` (`F`): The function to create a debounced function from. * `debounceMs`(`number`): The number of milliseconds to delay. * `options` (`DebounceOptions`, optional): An options object. * `signal` (`AbortSignal`, optional): An optional `AbortSignal` to cancel the debounced function. * `edges` (`Array<'leading' | 'trailing'>`, optional): An array indicating when to execute the original function. Defaults to `['trailing']`. * If `'leading'` is included, the original function is executed immediately on the first call to the debounced function. * If `'trailing'` is included, the original function is executed after `debounceMs` milliseconds have passed since the last call to the debounced function. * If both `'leading'` and `'trailing'` are included, the original function is called at both the start and end of the delay. However, the debounced function must be called at least twice within `debounceMs` milliseconds for this to happen, as a single call to the debounced function cannot trigger the original function twice. #### Returns (`DebouncedFunction`): A debounced function with the following methods: * `cancel()`: Cancels the scheduled invocation. * `flush()`: Immediately executes the pending function. * `schedule()`: Reschedules the function execution. --- --- url: /reference/compat/function/debounce.md --- # debounce (Lodash compatibility) ::: warning Use [`debounce`](../../function/debounce.md) from `es-toolkit` This `debounce` function has overhead due to complex `maxWait` handling and Lodash-compatible option structure. Instead, use the faster and more modern [`debounce`](../../function/debounce.md) from `es-toolkit`. ::: Creates a debounced function that delays invoking the provided function until after `wait` milliseconds have elapsed since the last time it was invoked. ```typescript const debouncedFunction = debounce(func, wait, options); ``` ## Usage ### `debounce(func, wait, options)` Use `debounce` when you want to delay function invocation. It's useful for preventing excessive calls in search inputs, scroll events, button clicks, etc. ```typescript import { debounce } from 'es-toolkit/compat'; // Basic usage const searchFunction = debounce(query => { console.log('Searching:', query); }, 300); // Only executes if not called again within 300ms searchFunction('React'); // Not executed searchFunction('Vue'); // Not executed searchFunction('Angular'); // Logs "Searching: Angular" after 300ms ``` Comparison with main library debounce: ```typescript // compat version (Lodash compatible, additional options like maxWait) import { debounce } from 'es-toolkit/compat'; const debouncedCompat = debounce(func, 300, { leading: true, trailing: false, maxWait: 1000 }); // Main library version (faster, simpler) import { debounce } from 'es-toolkit'; const debouncedMain = debounce(func, 300, { edges: ['leading'] // Uses edges instead of leading/trailing }); ``` Leading and trailing options: ```typescript import { debounce } from 'es-toolkit/compat'; const func = () => console.log('Executed'); // leading: true - Execute immediately on first call const leadingDebounce = debounce(func, 1000, { leading: true }); leadingDebounce(); // Immediately logs "Executed" leadingDebounce(); // Wait 1 second // No additional execution after 1 second // trailing: true (default) - Execute after delay following last call const trailingDebounce = debounce(func, 1000, { trailing: true }); trailingDebounce(); // Wait 1 second trailingDebounce(); // Wait 1 second (cancels previous timer) // Logs "Executed" after 1 second // Both true - Execute at start and end const bothDebounce = debounce(func, 1000, { leading: true, trailing: true, }); bothDebounce(); // Immediately logs "Executed" bothDebounce(); // Wait 1 second // Logs "Executed" after 1 second (trailing) ``` maxWait option: ```typescript import { debounce } from 'es-toolkit/compat'; // Guarantees execution at least every 2 seconds const debouncedWithMaxWait = debounce(() => console.log('Saved'), 500, { maxWait: 2000 }); // Even with rapid consecutive calls, executes every 2 seconds setInterval(() => { debouncedWithMaxWait(); }, 100); // Calls every 100ms but logs "Saved" every 2 seconds ``` Real-world search example: ```typescript import { debounce } from 'es-toolkit/compat'; class SearchComponent { constructor() { this.searchInput = document.getElementById('search'); // Debounce user input by 300ms this.debouncedSearch = debounce(this.performSearch.bind(this), 300, { leading: false, // Don't search immediately on input start trailing: true, // Search after input stops }); this.searchInput.addEventListener('input', e => { this.debouncedSearch(e.target.value); }); } performSearch(query) { if (query.length < 2) return; console.log('API call:', query); // fetch(`/api/search?q=${query}`)... } } ``` Scroll event optimization: ```typescript import { debounce } from 'es-toolkit/compat'; // Debounce scroll events by 100ms, but execute at least every 500ms const optimizedScrollHandler = debounce( () => { const scrollTop = window.pageYOffset; console.log('Scroll position:', scrollTop); // Header hide/show logic if (scrollTop > 100) { document.header.classList.add('hidden'); } else { document.header.classList.remove('hidden'); } }, 100, { maxWait: 500 } ); window.addEventListener('scroll', optimizedScrollHandler); ``` API call throttling: ```typescript import { debounce } from 'es-toolkit/compat'; class AutoSave { constructor() { // Debounce by 500ms, save at least every 5 seconds this.debouncedSave = debounce(this.saveToServer.bind(this), 500, { maxWait: 5000 }); } onTextChange(content) { this.pendingContent = content; this.debouncedSave(); } saveToServer() { if (!this.pendingContent) return; console.log('Saving to server:', this.pendingContent); // fetch('/api/save', { ... }) this.pendingContent = null; } } ``` cancel and flush methods: ```typescript import { debounce } from 'es-toolkit/compat'; const debouncedFunc = debounce(() => { console.log('Executed'); }, 1000); debouncedFunc(); // Waiting 1 second // Cancel pending execution debouncedFunc.cancel(); // Or execute immediately debouncedFunc(); // Start waiting 1 second debouncedFunc.flush(); // Immediately logs "Executed" and cancels timer ``` Preventing duplicate button clicks: ```typescript import { debounce } from 'es-toolkit/compat'; const handleSubmit = debounce( async formData => { console.log('Submitting form...'); try { const response = await fetch('/api/submit', { method: 'POST', body: formData, }); console.log('Submission complete'); } catch (error) { console.error('Submission failed:', error); } }, 1000, { leading: true, trailing: false } // Only handle first click ); document.getElementById('submit-btn').addEventListener('click', e => { const formData = new FormData(e.target.form); handleSubmit(formData); }); ``` Resize event handling: ```typescript import { debounce } from 'es-toolkit/compat'; const handleResize = debounce( () => { const width = window.innerWidth; const height = window.innerHeight; console.log('Window resized:', { width, height }); // Recalculate layout recalculateLayout(); }, 250, { leading: false, trailing: true } ); window.addEventListener('resize', handleResize); // Cleanup on page unload window.addEventListener('beforeunload', () => { handleResize.cancel(); }); ``` #### Parameters * `func` (`Function`): The function to debounce. * `wait` (`number`, optional): The number of milliseconds to delay. Defaults to `0`. * `options` (`DebounceSettings`, optional): An options object. * `leading` (`boolean`): If `true`, executes the function at the start of the delay. Defaults to `false`. * `trailing` (`boolean`): If `true`, executes the function at the end of the delay. Defaults to `true`. * `maxWait` (`number`): The maximum time the function execution can be delayed. Defaults to `Infinity`. #### Returns (`DebouncedFunc`): Returns the debounced function. It includes `cancel()` and `flush()` methods. --- --- url: /reference/string/deburr.md --- # deburr Converts special characters and diacritics to ASCII characters. ```typescript const result = deburr(str); ``` ## Usage ### `deburr(str)` Use `deburr` when you want to convert special characters or diacritics in a string to ASCII characters. It's useful for normalizing characters in URLs, filenames, or search functionality. ```typescript import { deburr } from 'es-toolkit/string'; // Basic usage deburr('café'); // returns 'cafe' deburr('résumé'); // returns 'resume' deburr('naïve'); // returns 'naive' deburr('Zürich'); // returns 'Zurich' ``` It can handle special characters from various languages. ```typescript import { deburr } from 'es-toolkit/string'; // German deburr('München'); // returns 'Munchen' deburr('Björk'); // returns 'Bjork' // French deburr('Crème brûlée'); // returns 'Creme brulee' deburr('naïveté'); // returns 'naivete' // Spanish deburr('niño'); // returns 'nino' deburr('mañana'); // returns 'manana' ``` You can use it for URL generation or filename cleaning. ```typescript import { deburr } from 'es-toolkit/string'; // Generate URL slug const title = 'Café의 특별한 메뉴'; const slug = deburr(title).toLowerCase().replace(/\s+/g, '-'); // returns 'cafe의-특별한-메뉴' // Clean filename const fileName = 'résumé-김철수.pdf'; const cleanName = deburr(fileName); // returns 'resume-김철수.pdf' ``` It makes string comparison easier in search functionality. ```typescript import { deburr } from 'es-toolkit/string'; function searchMatch(query: string, target: string): boolean { const normalizedQuery = deburr(query.toLowerCase()); const normalizedTarget = deburr(target.toLowerCase()); return normalizedTarget.includes(normalizedQuery); } searchMatch('cafe', 'Café Mocha'); // returns true searchMatch('resume', 'résumé.pdf'); // returns true ``` #### Parameters * `str` (`string`): The string containing special characters or diacritics. #### Returns (`string`): Returns a new string with special characters and diacritics converted to ASCII characters. --- --- url: /reference/compat/string/deburr.md --- # deburr (Lodash compatibility) ::: warning Use `deburr` from `es-toolkit` This `deburr` function operates slower due to handling non-string input values. Instead, use the faster and more modern [deburr](../../string/deburr.md) from `es-toolkit`. ::: Converts special characters and diacritical marks in a string to ASCII characters. ```typescript const result = deburr(str); ``` ## Usage ### `deburr(str)` Converts special characters and diacritical marks in a string to ASCII characters. This is useful for making multilingual text easier to search or sort. ```typescript import { deburr } from 'es-toolkit/compat'; deburr('Æthelred'); // 'Aethelred' deburr('München'); // 'Munchen' deburr('Crème brûlée'); // 'Creme brulee' ``` Non-string values are also converted to strings before processing. ```typescript import { deburr } from 'es-toolkit/compat'; deburr(123); // '123' deburr(null); // '' deburr(undefined); // '' ``` #### Parameters * `str` (`string`, optional): The string to remove special characters from. #### Returns (`string`): Returns the string with special characters and diacritical marks converted to ASCII characters. --- --- url: /reference/compat/object/defaults.md --- # defaults (Lodash Compatibility) ::: warning Use `Object.assign()` instead This `defaults` function operates slowly due to complex logic that handles `undefined` and properties inherited from `Object.prototype` specially. Use faster, more modern `Object.assign()` instead. ::: Fills in `undefined` properties in an object by setting default values. ```typescript const result = defaults(object, source); ``` ## Usage ### `defaults(object, ...sources)` Use `defaults` when you want to set default values for `undefined` properties or properties inherited from `Object.prototype` in an object. You can pass multiple default value objects, and they are applied in order from left to right. ```typescript import { defaults } from 'es-toolkit/compat'; // Fill undefined properties with default values defaults({ a: 1 }, { a: 2, b: 2 }, { c: 3 }); // Returns: { a: 1, b: 2, c: 3 } // Only undefined properties are filled with default values defaults({ a: undefined }, { a: 1 }); // Returns: { a: 1 } // null values are preserved defaults({ a: null }, { a: 1 }); // Returns: { a: null } ``` If a property already has a value, it won't be overwritten with the default value. ```typescript import { defaults } from 'es-toolkit/compat'; defaults({ a: 1, b: 2 }, { b: 3 }, { c: 3 }); // Returns: { a: 1, b: 2, c: 3 } ``` #### Parameters * `object` (`any`): The target object to set default values on. * `...sources` (`any[]`): The source objects that provide default values. #### Returns (`any`): Returns the object with default values set. The first argument `object` is modified. --- --- url: /reference/compat/object/defaultsDeep.md --- # defaultsDeep (Lodash Compatibility) ::: warning Use destructuring assignment and `Object.assign()` instead This `defaultsDeep` function operates slowly and complexly due to recursive merging of nested objects and circular reference handling. Use faster, more modern destructuring assignment and `Object.assign()` instead. ::: Recursively sets default values on nested objects. ```typescript const result = defaultsDeep(target, ...sources); ``` ## Usage ### `defaultsDeep(target, ...sources)` Use `defaultsDeep` when you want to recursively set default values for `undefined` properties in nested objects. Similar to `defaults`, but it also merges nested objects. ```typescript import { defaultsDeep } from 'es-toolkit/compat'; // Setting default values in nested objects defaultsDeep({ a: { b: 2 } }, { a: { b: 3, c: 3 }, d: 4 }); // Returns: { a: { b: 2, c: 3 }, d: 4 } // Only undefined properties are filled with default values defaultsDeep({ a: { b: undefined } }, { a: { b: 1 } }); // Returns: { a: { b: 1 } } // null values are preserved defaultsDeep({ a: null }, { a: { b: 1 } }); // Returns: { a: null } ``` You can pass multiple source objects to apply default values in stages. ```typescript import { defaultsDeep } from 'es-toolkit/compat'; defaultsDeep({ a: { b: 2 } }, { a: { c: 3 } }, { a: { d: 4 }, e: 5 }); // Returns: { a: { b: 2, c: 3, d: 4 }, e: 5 } ``` #### Parameters * `target` (`any`): The target object to set default values on. * `...sources` (`any[]`): The source objects that provide default values. #### Returns (`any`): Returns the object with default values recursively set. The first argument `target` is modified. --- --- url: /reference/compat/util/defaultTo.md --- # defaultTo (Lodash Compatibility) Returns the default value for values that are `null`, `undefined`, or `NaN`. ```typescript const result = defaultTo(value, defaultValue); ``` ## Usage ### `defaultTo(value, defaultValue)` Use `defaultTo` when you want to provide a default value when a value is `null`, `undefined`, or `NaN`. It's useful for handling invalid values from API responses or user input. ```typescript import { defaultTo } from 'es-toolkit/compat'; // Basic usage console.log(defaultTo(null, 'default')); // 'default' console.log(defaultTo(undefined, 'default')); // 'default' console.log(defaultTo(NaN, 0)); // 0 console.log(defaultTo('actual', 'default')); // 'actual' console.log(defaultTo(123, 0)); // 123 ``` Can be used for processing API responses. ```typescript import { defaultTo } from 'es-toolkit/compat'; function processUserData(response) { return { name: defaultTo(response.name, 'No name'), age: defaultTo(response.age, 0), score: defaultTo(response.score, 0), // Includes NaN handling }; } // When API returns incomplete data const userData = processUserData({ name: null, age: undefined, score: NaN, }); console.log(userData); // { name: 'No name', age: 0, score: 0 } ``` Can also be used with arrays or objects. ```typescript import { defaultTo } from 'es-toolkit/compat'; const users = defaultTo(response.users, []); const metadata = defaultTo(response.metadata, {}); // Only handles null/undefined/NaN, not empty arrays or objects console.log(defaultTo([], ['default'])); // [] (empty array but valid value) console.log(defaultTo({}, { default: true })); // {} (empty object but valid value) ``` #### Parameters * `value` (`T | null | undefined`): The value to check. * `defaultValue` (`D`): The default value to return when the value is `null`, `undefined`, or `NaN`. #### Returns (`T | D`): Returns the original value if valid, otherwise returns the default value. --- --- url: /reference/compat/function/defer.md --- # defer (Lodash Compatibility) ::: warning Use `setTimeout` instead This `defer` function is a simple wrapper that internally calls `setTimeout(func, 1, ...args)`. Use the more direct and modern `setTimeout` instead. ::: Defers the execution of a function to the next event loop. ```typescript const timerId = defer(func, ...args); ``` ## Usage ### `defer(func, ...args)` Use `defer` when you want to execute a function after the current call stack has ended. You can defer the function's execution to the next event loop while passing additional arguments to the function. ```typescript import { defer } from 'es-toolkit/compat'; // Defer console output defer(console.log, 'deferred message'); // Outputs 'deferred message' after the current call stack ends // Defer execution with function and arguments const greet = (name: string, greeting: string) => { console.log(`${greeting}, ${name}!`); }; defer(greet, 'John', 'Hello'); // Outputs 'Hello, John!' after the current call stack ends ``` Internally, it uses `setTimeout(func, 1, ...args)` to execute the function after 1 millisecond. ```typescript import { defer } from 'es-toolkit/compat'; // These two codes work identically defer(console.log, 'message'); setTimeout(console.log, 1, 'message'); ``` #### Parameters * `func` (`(...args: any[]) => any`): The function to defer execution. * `...args` (`any[]`): The arguments to pass to the function. #### Returns (`number`): Returns the timer ID returned from `setTimeout`. You can cancel execution with `clearTimeout`. --- --- url: /reference/promise/delay.md --- # delay Delays code execution for a specified amount of time. ```typescript await delay(ms, options?); ``` ## Usage ### `delay(ms, options?)` Use `delay` when you want to pause code execution for a specific amount of time. You can use it with async/await to make the next code execute after a certain time. If needed, you can also cancel the delay through an `AbortSignal`. ```typescript import { delay } from 'es-toolkit/promise'; async function example() { console.log('Start'); await delay(1000); // Delays execution for 1 second console.log('Executed after 1 second'); await delay(500); // Delays for an additional 0.5 seconds console.log('Executed after an additional 0.5 seconds'); } example(); ``` You can also cancel the delay using AbortSignal: ```typescript async function cancellableDelay() { const controller = new AbortController(); const { signal } = controller; // Cancel the delay after 50ms setTimeout(() => controller.abort(), 50); try { await delay(1000, { signal }); console.log('1 second has passed'); // This code won't execute } catch (error) { console.log('Delay was cancelled'); // AbortError is thrown } } ``` It's also useful for simulating asynchronous behavior in tests. ```typescript async function simulateNetworkRequest() { console.log('Starting network request...'); await delay(2000); // Simulates a 2-second network delay console.log('Response received!'); return { data: 'test' }; } ``` #### Parameters * `ms` (`number`): The amount of time to delay in milliseconds. * `options` (`DelayOptions`, optional): Delay options. * `signal` (`AbortSignal`, optional): An AbortSignal to cancel the delay. #### Returns (`Promise`): Returns a Promise that completes after the specified time. #### Errors Throws `AbortError` when the AbortSignal is activated. --- --- url: /reference/compat/function/delay.md --- # delay (Lodash Compatibility) ::: warning Use `setTimeout` This `delay` function is a simple wrapper around `setTimeout`, but has slight overhead due to additional type validation and number conversion. Use the faster and standard `setTimeout` directly instead. ::: Sets a timer to execute a function after a specified amount of time. ```typescript const timerId = delay(func, wait, ...args); ``` ## Usage ### `delay(func, wait, ...args)` Use `delay` when you want to defer function execution by a specific amount of time. It's useful for animation timing, delaying user feedback, or scheduling asynchronous operations. ```typescript import { delay } from 'es-toolkit/compat'; // Basic usage const timerId = delay(() => { console.log('Executed after 1 second'); }, 1000); // Using with arguments delay( (name, age) => { console.log(`Hello, ${name}, age ${age}!`); }, 2000, 'John Doe', 30 ); // After 2 seconds: Prints "Hello, John Doe, age 30!" ``` Comparison with `setTimeout`: ```typescript // Using delay import { delay } from 'es-toolkit/compat'; const timerId1 = delay(myFunction, 1000, 'arg1', 'arg2'); // Using setTimeout (faster, standard) const timerId2 = setTimeout(myFunction, 1000, 'arg1', 'arg2'); // Or with arrow function const timerId3 = setTimeout(() => myFunction('arg1', 'arg2'), 1000); ``` Animation sequence: ```typescript import { delay } from 'es-toolkit/compat'; class AnimationSequence { constructor(element) { this.element = element; } fadeInSequence() { // Start immediately this.element.style.opacity = '0'; this.element.style.display = 'block'; // Start fade-in after 100ms delay(() => { this.element.style.transition = 'opacity 500ms ease-in'; this.element.style.opacity = '1'; }, 100); // Scale animation after 1 second delay(() => { this.element.style.transform = 'scale(1.1)'; }, 1000); // Back to original size after 1.5 seconds delay(() => { this.element.style.transform = 'scale(1)'; }, 1500); } } ``` Canceling timers: ```typescript import { delay } from 'es-toolkit/compat'; class TimerManager { constructor() { this.timers = new Map(); } setDelayedTask(id, task, delayMs) { // Cancel existing timer if it exists this.cancelTask(id); const timerId = delay(task, delayMs); this.timers.set(id, timerId); return timerId; } cancelTask(id) { const timerId = this.timers.get(id); if (timerId) { clearTimeout(timerId); this.timers.delete(id); return true; } return false; } cancelAllTasks() { this.timers.forEach(timerId => clearTimeout(timerId)); this.timers.clear(); } } const timerManager = new TimerManager(); // Schedule tasks timerManager.setDelayedTask( 'save', () => { console.log('Auto-saved'); }, 5000 ); timerManager.setDelayedTask( 'cleanup', () => { console.log('Cleanup completed'); }, 10000 ); // Cancel a specific task if needed // timerManager.cancelTask('save'); // Clean up all timers when page unloads window.addEventListener('beforeunload', () => { timerManager.cancelAllTasks(); }); ``` #### Parameters * `func` (`Function`): The function to execute after the delay. * `wait` (`number`): The number of milliseconds to delay. * `args` (`...any[]`): The arguments to pass to the function when it executes. #### Returns (`number`): Returns the timer ID. Can be canceled with `clearTimeout()`. --- --- url: /reference/array/difference.md --- # difference Returns a new array excluding elements from the first array that are in the second array. ```typescript const result = difference(firstArr, secondArr); ``` ## Usage ### `difference(firstArr, secondArr)` Use `difference` when you want to find the difference between two arrays. A new array is returned containing elements that are only in the first array and not in the second array. ```typescript import { difference } from 'es-toolkit/array'; // Find the difference of number arrays. const array1 = [1, 2, 3, 4, 5]; const array2 = [2, 4]; difference(array1, array2); // Returns: [1, 3, 5] // 2 and 4 are excluded because they are in both arrays. // Find the difference of string arrays. const colors1 = ['red', 'blue', 'green']; const colors2 = ['blue', 'yellow']; difference(colors1, colors2); // Returns: ['red', 'green'] ``` The difference with an empty array is the same as the original array. ```typescript import { difference } from 'es-toolkit/array'; difference([1, 2, 3], []); // [1, 2, 3] difference([], [1, 2, 3]); // [] ``` #### Parameters * `firstArr` (`T[]`): The reference array to find the difference from. * `secondArr` (`T[]`): The array containing elements to exclude from the first array. #### Returns (`T[]`): A new array containing elements that are only in the first array and not in the second array. ## Performance Comparison | | [Bundle Size](../../bundle-size.md) | [Performance](../../performance.md) | | ---------- | ----------------------------------- | ----------------------------------- | | es-toolkit | 90 bytes (92.4% smaller) | 9,317,227 times (85% faster) | | lodash-es | 7,958 bytes | 5,030,861 times | --- --- url: /reference/compat/array/difference.md --- # difference (Lodash compatible) ::: warning Use `difference` from `es-toolkit` instead This `difference` function operates in a complex manner due to handling `null` or `undefined` and processing multiple array arguments. Use the faster and more modern [difference](../../array/difference.md) from `es-toolkit` instead. ::: Computes the difference between the first array and the other arrays, excluding values from the first array that are present in the other arrays. ```typescript const result = difference(arr, ...values); ``` ## Usage ### `difference(arr, ...values)` Use `difference` when you want to remove all values from the first array that are present in the other arrays. The order is preserved from the first array. ```typescript import { difference } from 'es-toolkit/compat'; // Basic usage const array1 = [1, 2, 3, 4, 5]; const array2 = [2, 4]; const array3 = [5, 6]; difference(array1, array2, array3); // Returns: [1, 3] // String arrays difference(['a', 'b', 'c'], ['b'], ['c', 'd']); // Returns: ['a'] // Handling duplicates difference([1, 2, 2, 3], [2]); // Returns: [1, 3] ``` Handles empty arrays or empty differences. ```typescript import { difference } from 'es-toolkit/compat'; // Difference with empty array difference([1, 2, 3], []); // Returns: [1, 2, 3] // When all values are excluded difference([1, 2, 3], [1, 2, 3]); // Returns: [] // When there are no overlapping values difference([1, 2], [3, 4]); // Returns: [1, 2] ``` `null` or `undefined` arrays are treated as empty arrays. ```typescript import { difference } from 'es-toolkit/compat'; difference(null, [1, 2]); // Returns: [] difference(undefined, [1, 2]); // Returns: [] difference([1, 2, 3], null, undefined); // Returns: [1, 2, 3] (null and undefined are ignored) ``` Supports array-like objects. ```typescript import { difference } from 'es-toolkit/compat'; // Array-like objects const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; const arrayLike2 = { 0: 2, 1: 4, length: 2 }; difference(arrayLike1, arrayLike2); // Returns: [1, 3] ``` #### Parameters * `arr` (`ArrayLike | null | undefined`): The base array to compute the difference from. * `values` (`...ArrayLike[]`): Arrays containing values to exclude. #### Returns (`T[]`): Returns a new array with values from the first array excluding values present in the other arrays. --- --- url: /reference/array/differenceBy.md --- # differenceBy Transforms elements of two arrays with a conversion function, computes their difference, and returns a new array. ```typescript const result = differenceBy(firstArr, secondArr, mapper); ``` ## Usage ### `differenceBy(firstArr, secondArr, mapper)` Use `differenceBy` when you want to compute the difference between two arrays based on a specific criterion. It compares each element after transforming it with the conversion function, and returns the elements that exist only in the first array. ```typescript import { differenceBy } from 'es-toolkit/array'; // Compute the difference based on the id in object arrays. const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]; const array2 = [{ id: 2 }, { id: 4 }]; differenceBy(array1, array2, item => item.id); // Returns: [{ id: 1 }, { id: 3 }] // Elements with id 2 exist in both arrays and are excluded. // You can compare arrays of different types. const objects = [{ id: 1 }, { id: 2 }, { id: 3 }]; const numbers = [2, 4]; differenceBy(objects, numbers, item => (typeof item === 'object' ? item.id : item)); // Returns: [{ id: 1 }, { id: 3 }] ``` You can also compute the difference based on string length. ```typescript import { differenceBy } from 'es-toolkit/array'; const words1 = ['apple', 'banana', 'cherry']; const words2 = ['grape', 'lemon']; differenceBy(words1, words2, word => word.length); // Returns: ['banana', 'cherry'] // 'apple' is excluded because it has the same length as 'grape' or 'lemon'. ``` #### Parameters * `firstArr` (`T[]`): The base array to compute the difference from. * `secondArr` (`U[]`): The array containing elements to exclude from the first array. * `mapper` (`(value: T | U) => unknown`): The function that maps elements of both arrays. Elements are compared based on the values returned by this function. #### Returns (`T[]`): A new array containing elements that exist only in the first array, based on the transformed values. --- --- url: /reference/compat/array/differenceBy.md --- # differenceBy (Lodash compatible) ::: warning Use `differenceBy` from `es-toolkit` instead This `differenceBy` function operates slowly due to complex argument processing and iteratee transformation. Use the faster and more modern [differenceBy](../../array/differenceBy.md) from `es-toolkit` instead. ::: Computes the difference between the first array and other arrays after applying an iteratee function to transform the values for comparison. ```typescript const result = differenceBy(array, ...values, iteratee); ``` ## Usage ### `differenceBy(array, ...values, iteratee)` Use `differenceBy` when you want to remove elements from the first array that have equivalent transformed values in the other arrays. This is useful for comparing arrays of objects by a specific property or transformed value. ```typescript import { differenceBy } from 'es-toolkit/compat'; // Compare using Math.floor differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // Returns: [1.2] (2.1 is excluded because Math.floor(2.1) === Math.floor(2.3)) // Compare by string length differenceBy(['one', 'two', 'three'], ['four', 'eight'], 'length'); // Returns: ['one', 'two'] (three is excluded because it has the same length as eight) // Compare objects by property const users1 = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, ]; const users2 = [{ id: 1, name: 'Different Alice' }]; differenceBy(users1, users2, 'id'); // Returns: [{ id: 2, name: 'Bob' }] (excludes object with id 1) ``` Can exclude from multiple arrays at once. ```typescript import { differenceBy } from 'es-toolkit/compat'; // Exclude from multiple arrays differenceBy([2.1, 1.2, 3.5], [2.3], [1.4], [3.2], Math.floor); // Returns: [] (all elements are excluded) // Compare strings by length from multiple arrays differenceBy(['a', 'bb', 'ccc'], ['x'], ['yy'], ['zzz'], 'length'); // Returns: [] (lengths 1, 2, 3 are all excluded) ``` Without an iteratee function, it behaves like regular `difference`. ```typescript import { differenceBy } from 'es-toolkit/compat'; // Without iteratee function differenceBy([1, 2, 3], [2, 4]); // Returns: [1, 3] ``` `null` or `undefined` arrays are treated as empty arrays. ```typescript import { differenceBy } from 'es-toolkit/compat'; differenceBy(null, [1, 2], Math.floor); // Returns: [] differenceBy(undefined, [1, 2], x => x); // Returns: [] ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The base array to compute the difference from. * `values` (`...ArrayLike[]`): Arrays containing values to exclude. * `iteratee` (`ValueIteratee`): The function that transforms each element for comparison. Can be a function, property name, or partial object. #### Returns (`T[]`): Returns a new array with elements excluded based on the transformed values. --- --- url: /reference/array/differenceWith.md --- # differenceWith Computes the difference of two arrays using a custom comparison function and returns a new array. ```typescript const result = differenceWith(firstArr, secondArr, areItemsEqual); ``` ## Usage ### `differenceWith(firstArr, secondArr, areItemsEqual)` Use `differenceWith` when you want to compute the difference between two arrays using a custom comparison function. It determines if two elements are equal through the comparison function, and returns elements that exist only in the first array. ```typescript import { differenceWith } from 'es-toolkit/array'; // Compute the difference based on id in object arrays. const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]; const array2 = [{ id: 2 }, { id: 4 }]; const areItemsEqual = (a, b) => a.id === b.id; differenceWith(array1, array2, areItemsEqual); // Returns: [{ id: 1 }, { id: 3 }] // Elements with id 2 are considered equal and excluded. // You can compare arrays of different types. const objects = [{ id: 1 }, { id: 2 }, { id: 3 }]; const numbers = [2, 4]; const areItemsEqual2 = (a, b) => a.id === b; differenceWith(objects, numbers, areItemsEqual2); // Returns: [{ id: 1 }, { id: 3 }] ``` You can compare elements with complex conditions. ```typescript import { differenceWith } from 'es-toolkit/array'; const users1 = [ { name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }, { name: 'Charlie', age: 35 }, ]; const users2 = [ { name: 'Alice', age: 31 }, // Same user even if age is different { name: 'David', age: 25 }, ]; const areUsersEqual = (a, b) => a.name === b.name; differenceWith(users1, users2, areUsersEqual); // Returns: [{ name: 'Bob', age: 25 }, { name: 'Charlie', age: 35 }] ``` #### Parameters * `firstArr` (`T[]`): The base array to compute the difference from. * `secondArr` (`U[]`): The array containing elements to exclude from the first array. * `areItemsEqual` (`(x: T, y: U) => boolean`): The function that determines if two elements are equal. #### Returns (`T[]`): A new array containing elements that are determined to exist only in the first array according to the comparison function. ## Lodash Compatibility When you import `differenceWith` from `es-toolkit/compat`, it's fully compatible with lodash. * `differenceWith` can accept multiple arrays to compare against the first array. * `differenceWith` can accept array-like objects as arguments. * `differenceWith` can omit the custom comparison function. When omitted, it uses the [SameValueZero](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-samevaluezero) algorithm by default. ```typescript import { differenceWith } from 'es-toolkit/compat'; // Example 1: Comparing with multiple arrays using a comparison function const array = [{ id: 1 }, { id: 2 }, { id: 3 }]; const values1 = [{ id: 2 }]; const values2 = [{ id: 3 }]; const comparator = (a, b) => a.id === b.id; const result = differenceWith(array, values1, values2, comparator); // The result is [{ id: 1 }]. This element remains in the first array based on the comparison criteria. // Example 2: Using array-like objects with a comparison function const array = { 0: { id: 1 }, 1: { id: 2 }, 2: { id: 3 }, length: 3 }; const values = { 0: { id: 2 }, 1: { id: 3 }, length: 2 }; const comparator = (a, b) => a.id === b.id; const result2 = differenceWith(array, values, comparator); // The result is [{ id: 1 }]. This element remains only in the first array-like object based on the comparison criteria. // Example 3: Omitting the custom comparison function const array = [1, 2, 3]; const values1 = [2]; const values2 = [3]; const result3 = differenceWith(array, values1, values2); // The result is [1]. This element exists uniquely across all arrays. ``` --- --- url: /reference/compat/array/differenceWith.md --- # differenceWith (Lodash compatible) ::: warning Use `differenceWith` from `es-toolkit` instead This `differenceWith` function operates slowly due to handling `null` or `undefined`, processing multiple arrays, and `ArrayLike` type processing. Use the faster and more modern [differenceWith](../../array/differenceWith.md) from `es-toolkit` instead. ::: Removes elements from the first array that are present in the other arrays using a comparator function. ```typescript const result = differenceWith(array, ...values, comparator); ``` ## Usage ### `differenceWith(array, ...values, comparator)` Use `differenceWith` when you want to compute the difference using a comparator function to compare elements. The last argument becomes the comparator function. ```typescript import { differenceWith } from 'es-toolkit/compat'; // Compare objects by id const objects = [{ id: 1 }, { id: 2 }, { id: 3 }]; const others = [{ id: 2 }]; const comparator = (a, b) => a.id === b.id; differenceWith(objects, others, comparator); // Returns: [{ id: 1 }, { id: 3 }] // Exclude from multiple arrays at once const array = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]; const values1 = [{ id: 2 }]; const values2 = [{ id: 3 }]; differenceWith(array, values1, values2, comparator); // Returns: [{ id: 1 }, { id: 4 }] ``` Without a comparator function, it behaves like regular `difference`. ```typescript import { differenceWith } from 'es-toolkit/compat'; // Without comparator, uses regular comparison differenceWith([1, 2, 3], [2], [3]); // Returns: [1] ``` Can use complex comparison logic. ```typescript import { differenceWith } from 'es-toolkit/compat'; const users = [ { name: 'alice', age: 25 }, { name: 'bob', age: 30 }, { name: 'charlie', age: 35 }, ]; const excludeUsers = [{ name: 'bob', age: 25 }]; // Different age // Compare only by name const compareByName = (a, b) => a.name === b.name; differenceWith(users, excludeUsers, compareByName); // Returns: [{ name: 'alice', age: 25 }, { name: 'charlie', age: 35 }] // bob is excluded (even though age is different, name matches) ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The base array to compute the difference from. * `...values` (`Array>` + `(a: T, b: T) => boolean`): Arrays containing elements to exclude, with the last argument being the comparator function. #### Returns (`T[]`): Returns a new array with elements from the first array excluding those found in the other arrays using the comparator function. --- --- url: /reference/compat/math/divide.md --- # divide (Lodash Compatibility) ::: warning Use the `/` operator This `divide` function operates slowly due to additional function calls. Use the faster and simpler `/` operator instead. ::: Divides two numbers. ```typescript const result = divide(value, other); ``` ## Usage ### `divide(value, other)` Use `divide` when you want to divide two numbers. ```typescript import { divide } from 'es-toolkit/compat'; // Basic division divide(6, 3); // Returns: 2 divide(10, 5); // Returns: 2 // Decimal division divide(7, 2); // Returns: 3.5 divide(1, 3); // Returns: 0.3333333333333333 // Division by zero divide(6, 0); // Returns: Infinity divide(-6, 0); // Returns: -Infinity // NaN handling divide(2, NaN); // Returns: NaN divide(NaN, 3); // Returns: NaN divide(NaN, NaN); // Returns: NaN ``` #### Parameters * `value` (`number`): The dividend (number being divided). * `other` (`number`): The divisor (number dividing by). #### Returns (`number`): Returns the result of dividing the first number by the second. If either value is NaN, returns NaN. --- --- url: /CLAUDE.md --- # Documentation Guide es-toolkit docs are written in 4 languages. All must be created together. ## File Locations | Language | Path | | -------- | ------------------------------------------- | | English | `docs/reference/{category}/{fn}.md` | | Korean | `docs/ko/reference/{category}/{fn}.md` | | Japanese | `docs/ja/reference/{category}/{fn}.md` | | Chinese | `docs/zh_hans/reference/{category}/{fn}.md` | ## Translation Table | English | Korean (해요체) | Japanese | zh\_hans | | ---------- | --------------- | ---------------- | ------- | | Signature | 인터페이스 | インターフェース | 签名 | | Parameters | 파라미터 | パラメータ | 参数 | | Returns | 반환 값 | 戻り値 | 返回値 | | Examples | 예시 | 例 | 示例 | | Usage | 사용법 | 使い方 | 用法 | | Throws | 에러 | エラー | 异常 | ## Korean Style Write in polite conversational tone (해요체): "반환해요", "나눠요", "던져요". ## Template Use existing docs as reference. See `docs/reference/array/chunk.md` for a complete example. ```markdown # functionName [One-line description.] ## Signature \`\`\`typescript function functionName(param: ParamType): ReturnType; \`\`\` ### Parameters - `param` (`ParamType`): Description. ### Returns (`ReturnType`): Description. ## Examples \`\`\`typescript import { functionName } from 'es-toolkit/category'; functionName(input); // Returns: output \`\`\` ``` --- --- url: /reference/array/drop.md --- # drop Returns a new array with the specified number of elements removed from the beginning. ```typescript const dropped = drop(arr, itemsCount); ``` ## Usage ### `drop(arr, itemsCount)` Use `drop` when you want to remove some elements from the beginning of an array. It removes the specified number of elements from the start and returns a new array with the remaining elements. ```typescript import { drop } from 'es-toolkit/array'; // Remove the first 2 elements from the array. drop([1, 2, 3, 4, 5], 2); // Returns: [3, 4, 5] // If the count is greater than the array length, it returns an empty array. drop([1, 2, 3], 5); // Returns: [] ``` If you pass a negative number or 0, it returns a new array with the same elements as the original. ```typescript import { drop } from 'es-toolkit/array'; drop([1, 2, 3], 0); // [1, 2, 3] drop([1, 2, 3], -2); // [1, 2, 3] ``` #### Parameters * `arr` (`T[]`): The array to remove elements from. * `itemsCount` (`number`): The number of elements to remove from the beginning of the array. #### Returns (`T[]`): A new array with the specified number of elements removed from the beginning. --- --- url: /reference/compat/array/drop.md --- # drop (Lodash Compatibility) ::: warning Use `drop` from `es-toolkit` This `drop` function operates in a complex manner due to handling of `null` or `undefined`, `toInteger` conversion, etc. Instead, use the faster and more modern [`drop`](../../array/drop.md) from `es-toolkit`. ::: Removes a specified number of elements from the beginning of an array. ```typescript const result = drop(array, n); ``` ## Usage ### `drop(array, n?)` Use `drop` when you want to remove several elements from the beginning of an array and get the rest. By default, it removes the first element. ```typescript import { drop } from 'es-toolkit/compat'; // Basic usage (removes first element) drop([1, 2, 3, 4, 5]); // Returns: [2, 3, 4, 5] // Remove first 2 elements drop([1, 2, 3, 4, 5], 2); // Returns: [3, 4, 5] // Remove first 3 elements drop(['a', 'b', 'c', 'd'], 3); // Returns: ['d'] ``` When specifying 0 or a negative number, it returns the original array as is. ```typescript import { drop } from 'es-toolkit/compat'; // Remove 0 elements drop([1, 2, 3], 0); // Returns: [1, 2, 3] // Specify negative number drop([1, 2, 3], -1); // Returns: [1, 2, 3] ``` When specifying a number larger than the array, it returns an empty array. ```typescript import { drop } from 'es-toolkit/compat'; // Specify number larger than array size drop([1, 2, 3], 5); // Returns: [] // Remove from empty array drop([], 1); // Returns: [] ``` `null` or `undefined` arrays are treated as empty arrays. ```typescript import { drop } from 'es-toolkit/compat'; drop(null, 1); // Returns: [] drop(undefined, 2); // Returns: [] ``` Array-like objects are also supported. ```typescript import { drop } from 'es-toolkit/compat'; // Array-like object const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; drop(arrayLike, 1); // Returns: ['b', 'c'] ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array from which elements will be removed. * `n` (`number`, optional): The number of elements to remove. Default is `1`. #### Returns (`T[]`): Returns a new array with the specified number of elements removed from the beginning. --- --- url: /reference/array/dropRight.md --- # dropRight Returns a new array with the specified number of elements removed from the end. ```typescript const dropped = dropRight(arr, itemsCount); ``` ## Usage ### `dropRight(arr, itemsCount)` Use `dropRight` when you want to remove some elements from the end of an array. It removes the specified number of elements from the end and returns a new array with the remaining elements. ```typescript import { dropRight } from 'es-toolkit/array'; // Remove the last 2 elements from the array. dropRight([1, 2, 3, 4, 5], 2); // Returns: [1, 2, 3] // If the count is greater than the array length, it returns an empty array. dropRight([1, 2, 3], 5); // Returns: [] ``` If you pass a negative number or 0, it returns a new array with the same elements as the original. ```typescript import { dropRight } from 'es-toolkit/array'; dropRight([1, 2, 3], 0); // [1, 2, 3] dropRight([1, 2, 3], -2); // [1, 2, 3] ``` #### Parameters * `arr` (`T[]`): The array to remove elements from. * `itemsCount` (`number`): The number of elements to remove from the end of the array. #### Returns (`T[]`): A new array with the specified number of elements removed from the end. --- --- url: /reference/compat/array/dropRight.md --- # dropRight (Lodash Compatibility) ::: warning Use `dropRight` from `es-toolkit` This `dropRight` function operates slowly due to handling `null` or `undefined`, `guard` parameter processing, `toInteger` conversion, etc. Instead, use the faster and more modern [`dropRight`](../../array/dropRight.md) from `es-toolkit`. ::: Returns a new array with a specified number of elements removed from the end. ```typescript const result = dropRight(array, itemsCount); ``` ## Usage ### `dropRight(array, itemsCount)` Use `dropRight` when you want to remove a certain number of elements from the end of an array and create a new array with the remaining elements. ```typescript import { dropRight } from 'es-toolkit/compat'; // Remove the last 2 elements from a number array. dropRight([1, 2, 3, 4, 5], 2); // Returns: [1, 2, 3] // Remove the last 1 element from a string array. dropRight(['a', 'b', 'c'], 1); // Returns: ['a', 'b'] // If the number to remove is not specified, the default value 1 is used. dropRight([1, 2, 3]); // Returns: [1, 2] ``` `null` or `undefined` are treated as empty arrays. ```typescript import { dropRight } from 'es-toolkit/compat'; dropRight(null, 2); // [] dropRight(undefined, 2); // [] ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to remove elements from. * `itemsCount` (`number`, optional): The number of elements to remove from the end of the array. Default is `1`. #### Returns (`T[]`): Returns a new array with `itemsCount` elements removed from the end. --- --- url: /reference/array/dropRightWhile.md --- # dropRightWhile Returns a new array with elements removed from the end while a condition is satisfied. ```typescript const result = dropRightWhile(arr, canContinueDropping); ``` ## Usage ### `dropRightWhile(arr, canContinueDropping)` Use `dropRightWhile` when you want to remove elements from the end of an array that meet a specific condition. Starting from the end of the array, it removes elements while the condition function returns `true`, and stops when it returns `false`. ```typescript import { dropRightWhile } from 'es-toolkit/array'; // Remove elements greater than 3 from the end. const numbers = [1, 2, 3, 4, 5]; dropRightWhile(numbers, x => x > 3); // Returns: [1, 2, 3] // 4 and 5 satisfy the condition and are removed, stopping at 3 where the condition becomes false. // Remove elements matching a specific condition from an object array. const users = [ { name: 'Alice', active: true }, { name: 'Bob', active: true }, { name: 'Charlie', active: false }, { name: 'David', active: false }, ]; dropRightWhile(users, user => !user.active); // Returns: [{ name: 'Alice', active: true }, { name: 'Bob', active: true }] ``` If the array is empty or no elements satisfy the condition, it returns a new array same as the original. ```typescript import { dropRightWhile } from 'es-toolkit/array'; dropRightWhile([1, 2, 3], x => x > 5); // [1, 2, 3] dropRightWhile([], x => true); // [] ``` #### Parameters * `arr` (`T[]`): The array to remove elements from. * `canContinueDropping` (`(item: T, index: number, arr: T[]) => boolean`): The condition function that determines whether to continue removing elements. It receives each element, its index, and the entire array, and returns true or false. #### Returns (`T[]`): A new array containing elements from the first element that doesn't satisfy the condition to the beginning of the array. --- --- url: /reference/compat/array/dropRightWhile.md --- # dropRightWhile (Lodash Compatibility) ::: warning Use `dropRightWhile` from `es-toolkit` This `dropRightWhile` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, support for various predicate function formats, etc. Instead, use the faster and more modern [`dropRightWhile`](../../array/dropRightWhile.md) from `es-toolkit`. ::: Removes elements from the end of an array based on a predicate function. ```typescript const result = dropRightWhile(array, predicate); ``` ## Usage ### `dropRightWhile(array, predicate)` Use `dropRightWhile` when you want to consecutively remove elements from the end of an array that satisfy a specific condition. Removal stops when the predicate function returns `false`. ```typescript import { dropRightWhile } from 'es-toolkit/compat'; // Using a function as a predicate. const users = [ { user: 'barney', active: true }, { user: 'fred', active: false }, { user: 'pebbles', active: false }, ]; dropRightWhile(users, user => !user.active); // Returns: [{ user: 'barney', active: true }] // Matching with an object pattern. dropRightWhile(users, { user: 'pebbles', active: false }); // Returns: [{ user: 'barney', active: true }, { user: 'fred', active: false }] // Specifying property and value in array format. dropRightWhile(users, ['active', false]); // Returns: [{ user: 'barney', active: true }] // Checking condition by property name. dropRightWhile(users, 'active'); // Returns: [{ user: 'barney', active: true }, { user: 'fred', active: false }, { user: 'pebbles', active: false }] ``` `null` or `undefined` are treated as empty arrays. ```typescript import { dropRightWhile } from 'es-toolkit/compat'; dropRightWhile(null, x => x > 0); // [] dropRightWhile(undefined, x => x > 0); // [] ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to remove elements from. * `predicate` (`ListIteratee`, optional): The predicate function to apply to each element. Can accept a function, object pattern, array pattern, or property name. #### Returns (`T[]`): Returns a new array starting from the first element that does not satisfy the condition. --- --- url: /reference/array/dropWhile.md --- # dropWhile Returns a new array with elements removed from the beginning while a condition is satisfied. ```typescript const result = dropWhile(arr, canContinueDropping); ``` ## Usage ### `dropWhile(arr, canContinueDropping)` Use `dropWhile` when you want to remove elements from the beginning of an array that meet a specific condition. Starting from the beginning of the array, it removes elements while the condition function returns `true`, and stops when it returns `false`. ```typescript import { dropWhile } from 'es-toolkit/array'; // Remove elements less than 3 from the beginning. const numbers = [1, 2, 3, 4, 2, 5]; dropWhile(numbers, x => x < 3); // Returns: [3, 4, 2, 5] // 1 and 2 satisfy the condition and are removed, stopping at 3 where the condition becomes false. // Remove elements matching a specific condition from an object array. const users = [ { name: 'Alice', active: false }, { name: 'Bob', active: false }, { name: 'Charlie', active: true }, { name: 'David', active: true }, ]; dropWhile(users, user => !user.active); // Returns: [{ name: 'Charlie', active: true }, { name: 'David', active: true }] ``` If the array is empty or no elements satisfy the condition, it returns a new array same as the original. ```typescript import { dropWhile } from 'es-toolkit/array'; dropWhile([1, 2, 3], x => x > 5); // [1, 2, 3] dropWhile([], x => true); // [] ``` #### Parameters * `arr` (`T[]`): The array to remove elements from. * `canContinueDropping` (`(item: T, index: number, arr: T[]) => boolean`): The condition function that determines whether to continue removing elements. It receives each element, its index, and the entire array, and returns true or false. #### Returns (`T[]`): A new array containing elements from the first element that doesn't satisfy the condition to the end of the array. --- --- url: /reference/compat/array/dropWhile.md --- # dropWhile (Lodash Compatibility) ::: warning Use `dropWhile` from `es-toolkit` This `dropWhile` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, support for various predicate function formats, etc. Instead, use the faster and more modern [`dropWhile`](../../array/dropWhile.md) from `es-toolkit`. ::: Removes elements from the beginning of an array based on a predicate function. ```typescript const result = dropWhile(array, predicate); ``` ## Usage ### `dropWhile(array, predicate)` Use `dropWhile` when you want to consecutively remove elements from the beginning of an array that satisfy a specific condition. Removal stops when the predicate function returns `false`. ```typescript import { dropWhile } from 'es-toolkit/compat'; // Using a function as a predicate. dropWhile([1, 2, 3, 4, 5], n => n < 3); // Returns: [3, 4, 5] // Matching with an object pattern. const users = [ { name: 'alice', active: false }, { name: 'bob', active: false }, { name: 'charlie', active: true }, ]; dropWhile(users, { active: false }); // Returns: [{ name: 'charlie', active: true }] // Specifying property and value in array format. dropWhile(users, ['active', false]); // Returns: [{ name: 'charlie', active: true }] // Checking condition by property name. const items = [{ visible: false }, { visible: false }, { visible: true }]; dropWhile(items, 'visible'); // Returns: [{ visible: false }, { visible: false }, { visible: true }] ``` `null` or `undefined` are treated as empty arrays. ```typescript import { dropWhile } from 'es-toolkit/compat'; dropWhile(null, x => x > 0); // [] dropWhile(undefined, x => x > 0); // [] ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to remove elements from. * `predicate` (`ListIteratee`, optional): The predicate function to apply to each element. Can accept a function, object pattern, array pattern, or property name. Default is `identity`. #### Returns (`T[]`): Returns a new array starting from the first element that does not satisfy the condition. --- --- url: /reference/compat/array/each.md --- # each (Lodash Compatibility) ::: warning Use `Array.prototype.forEach` This `each` function operates slowly due to complex type processing and support for various collection types. Instead, use the faster and more modern `Array.prototype.forEach`. ::: Performs an iteration operation on each element of an array or object. ```typescript const result = each(collection, iteratee); ``` ## Usage ### `each(collection, iteratee)` Iterates through each element of an array, object, or string and executes the given function. For arrays, it iterates in index order; for objects, it iterates through enumerable properties. ```typescript import { each } from 'es-toolkit/compat'; // Iterate array each([1, 2, 3], (value, index) => console.log(value, index)); // Logs: 1 0, 2 1, 3 2 // Iterate object each({ a: 1, b: 2 }, (value, key) => console.log(key, value)); // Logs: 'a' 1, 'b' 2 // Iterate string each('hello', (char, index) => console.log(char, index)); // Logs: 'h' 0, 'e' 1, 'l' 2, 'l' 3, 'o' 4 ``` If the function returns `false`, iteration stops. ```typescript import { each } from 'es-toolkit/compat'; each([1, 2, 3, 4], value => { console.log(value); return value !== 2; // Stop at 2 }); // Logs: 1, 2 ``` #### Parameters * `collection` (`ArrayLike | Record | string | null | undefined`): The collection to iterate over. * `iteratee` (`(item: any, index: any, collection: any) => unknown`, optional): The function to execute for each element. Default is the `identity` function. #### Returns (`ArrayLike | Record | string | null | undefined`): Returns the original collection. --- --- url: /reference/compat/array/eachRight.md --- # eachRight (Lodash Compatibility) ::: warning Use `forEachRight` from `es-toolkit` This `eachRight` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, support for various predicate function formats, etc. Instead, use the faster and more modern [`forEachRight`](../../array/forEachRight.md) from `es-toolkit`. ::: Performs an iteration operation from right to left on each element of an array or object. ```typescript const result = eachRight(collection, iteratee); ``` ## Usage ### `eachRight(collection, iteratee)` Iterates through each element of an array, object, or string from right to left and executes the given function. For arrays, it iterates in reverse order from the last index; for objects, it iterates through enumerable properties in reverse order. ```typescript import { eachRight } from 'es-toolkit/compat'; // Iterate array in reverse order eachRight([1, 2, 3], (value, index) => console.log(value, index)); // Logs: 3 2, 2 1, 1 0 // Iterate object in reverse order eachRight({ a: 1, b: 2 }, (value, key) => console.log(key, value)); // Logs: 'b' 2, 'a' 1 // Iterate string in reverse order eachRight('hello', (char, index) => console.log(char, index)); // Logs: 'o' 4, 'l' 3, 'l' 2, 'e' 1, 'h' 0 ``` If the function returns `false`, iteration stops. ```typescript import { eachRight } from 'es-toolkit/compat'; eachRight([1, 2, 3, 4], value => { console.log(value); return value !== 2; // Stop at 2 }); // Logs: 4, 3, 2 ``` #### Parameters * `collection` (`ArrayLike | Record | string | null | undefined`): The collection to iterate over. * `iteratee` (`(item: any, index: any, collection: any) => unknown`, optional): The function to execute for each element. Default is the `identity` function. #### Returns (`ArrayLike | Record | string | null | undefined`): Returns the original collection. --- --- url: /reference/compat/string/endsWith.md --- # endsWith (Lodash compatibility) ::: warning Use JavaScript's `String.prototype.endsWith` This `endsWith` function operates slower due to handling `null` or `undefined`. Instead, use the faster and more modern JavaScript's `String.prototype.endsWith`. ::: Checks if a string ends with a given target string. ```typescript const result = endsWith(str, target); ``` ## Usage ### `endsWith(str, target, position?)` Use `endsWith` when you want to check if a string ends with a specific string. You can also specify the position to search up to. ```typescript import { endsWith } from 'es-toolkit/compat'; // Check string ending endsWith('fooBar', 'Bar'); // Returns: true endsWith('fooBar', 'foo'); // Returns: false // Check up to a specific position endsWith('fooBar', 'foo', 3); // Returns: true (checks if first 3 characters 'foo' ends with 'foo') ``` `null` or `undefined` returns `false`. ```typescript import { endsWith } from 'es-toolkit/compat'; endsWith(null, 'test'); // Returns: false endsWith('test', null); // Returns: false ``` #### Parameters * `str` (`string`, optional): The string to search in. * `target` (`string`, optional): The string to search for at the end. * `position` (`number`, optional): The position to end the search. Defaults to the full length of the string. #### Returns (`boolean`): Returns `true` if the string ends with the target string, otherwise `false`. --- --- url: /reference/compat/util/eq.md --- # eq (Lodash Compatibility) Checks if two values are equivalent using SameValueZero comparison. ```typescript const isEqual = eq(value, other); ``` ## Usage ### `eq(value, other)` Use `eq` when you want to check if two values are equivalent. Unlike regular `===` comparison, it returns `true` when comparing `NaN` with `NaN`. ```typescript import { eq } from 'es-toolkit/compat'; // Basic usage console.log(eq(1, 1)); // true console.log(eq(0, -0)); // true (SameValueZero considers 0 and -0 equal) console.log(eq(NaN, NaN)); // true console.log(eq('a', 'a')); // true console.log(eq('a', 'b')); // false ``` Behaves differently from `Object.is()`. ```typescript // Using eq console.log(eq(NaN, NaN)); // true console.log(eq(0, -0)); // true // Using Object.is (faster) console.log(Object.is(NaN, NaN)); // true console.log(Object.is(0, -0)); // false (Object.is considers 0 and -0 different) // Using === console.log(NaN === NaN); // false console.log(0 === -0); // true ``` #### Parameters * `value` (`any`): The first value to compare. * `other` (`any`): The second value to compare. #### Returns (`boolean`): Returns `true` if the values are equivalent, `false` otherwise. --- --- url: /reference/string/escape.md --- # escape Converts characters with special meaning in HTML to safe entities. ```typescript const result = escape(str); ``` ## Usage ### `escape(str)` Use `escape` when you want to safely insert text into HTML. It converts special characters like `&`, `<`, `>`, `"`, and `'` to HTML entities to prevent XSS attacks and ensure HTML is displayed correctly. ```typescript import { escape } from 'es-toolkit/string'; // Handle basic HTML special characters escape('
Hello World
'); // returns '<div>Hello World</div>' escape('Tom & Jerry'); // returns 'Tom & Jerry' escape('"Hello"'); // returns '"Hello"' escape("'Hello'"); // returns ''Hello'' ``` It's essential for security when displaying user input in HTML. ```typescript import { escape } from 'es-toolkit/string'; // Handle user input const userInput = ''; const safeHtml = `
${escape(userInput)}
`; // returns '
<script>alert("XSS")</script>
' // Generate dynamic HTML const title = 'Article "How to & Why"'; const html = `

${escape(title)}

`; // returns '

Article "How to & Why"

' ``` You can use it in templates or comment systems. ```typescript import { escape } from 'es-toolkit/string'; // Comment system function renderComment(comment: string, author: string) { return `
${escape(author)}: ${escape(comment)}
`; } // Usage example const html = renderComment('I love & "programming"!', 'John Doe'); // returns '
John Doe: I love <coding> & "programming"!
' ``` It's also useful when putting JSON strings in HTML attributes. ```typescript import { escape } from 'es-toolkit/string'; const data = { message: 'Hello & "welcome"' }; const jsonString = JSON.stringify(data); const htmlAttribute = `
`; // returns '
' ``` #### Parameters * `str` (`string`): The string to convert for safe use in HTML. #### Returns (`string`): Returns a new string with characters converted to HTML entities. --- --- url: /reference/compat/string/escape.md --- # escape (Lodash compatibility) ::: warning Use `escape` from `es-toolkit` This `escape` function operates slower due to handling non-string input values. Instead, use the faster and more modern [escape](../../string/escape.md) from `es-toolkit`. ::: Converts HTML special characters in a string to HTML entities. ```typescript const result = escape(str); ``` ## Usage ### `escape(str)` Converts the characters `&`, `<`, `>`, `"`, `'` in a string to their corresponding HTML entities. This is useful for preventing XSS attacks when inserting text into HTML documents. ```typescript import { escape } from 'es-toolkit/compat'; escape('This is a
element.'); // 'This is a <div> element.' escape('This is a "quote"'); // 'This is a "quote"' escape("This is a 'quote'"); // 'This is a 'quote'' escape('This is a & symbol'); // 'This is a & symbol' ``` Non-string values are also converted to strings before processing. ```typescript import { escape } from 'es-toolkit/compat'; escape(123); // '123' escape(null); // '' escape(undefined); // '' ``` #### Parameters * `str` (`string`, optional): The string to escape HTML special characters. #### Returns (`string`): Returns the string with HTML special characters converted to entities. --- --- url: /reference/string/escapeRegExp.md --- # escapeRegExp Escapes characters with special meaning in regular expressions to literal characters. ```typescript const result = escapeRegExp(str); ``` ## Usage ### `escapeRegExp(str)` Use `escapeRegExp` when you want to safely use a string in a regular expression pattern. It escapes regex special characters like `^`, `$`, `\`, `.`, `*`, `+`, `?`, `(`, `)`, `[`, `]`, `{`, `}`, and `|` so they match literally. ```typescript import { escapeRegExp } from 'es-toolkit/string'; // Basic usage escapeRegExp('Hello.'); // returns 'Hello\\.' escapeRegExp('(test)'); // returns '\\(test\\)' escapeRegExp('user@domain.com'); // returns 'user@domain\\.com' escapeRegExp('[abc]'); // returns '\\[abc\\]' ``` It's essential when using user input as a regex pattern. ```typescript import { escapeRegExp } from 'es-toolkit/string'; // Use user search term as regex function searchInText(text: string, searchTerm: string): boolean { const escapedTerm = escapeRegExp(searchTerm); const regex = new RegExp(escapedTerm, 'i'); // case insensitive return regex.test(text); } searchInText('Visit https://example.com', 'https://example.com'); // returns true searchInText('Price: $19.99', '$19.99'); // returns true ``` You can also use it for string replacement. ```typescript import { escapeRegExp } from 'es-toolkit/string'; function replaceAll(text: string, search: string, replacement: string): string { const escapedSearch = escapeRegExp(search); const regex = new RegExp(escapedSearch, 'g'); return text.replace(regex, replacement); } const html = '
Hello
World'; const result = replaceAll(html, '
', '
'); // returns '
Hello
World' ``` It's useful for handling file paths or URLs. ```typescript import { escapeRegExp } from 'es-toolkit/string'; // Check file extension function hasExtension(filename: string, extension: string): boolean { const escapedExt = escapeRegExp(extension); const regex = new RegExp(`\\.${escapedExt}$`, 'i'); return regex.test(filename); } hasExtension('document.pdf', 'pdf'); // returns true hasExtension('image.jpg', 'pdf'); // returns false // URL matching function matchesUrl(text: string, url: string): boolean { const escapedUrl = escapeRegExp(url); const regex = new RegExp(escapedUrl); return regex.test(text); } const content = 'Visit our site at https://es-toolkit.dev/ for more info'; matchesUrl(content, 'https://es-toolkit.dev/'); // returns true ``` #### Parameters * `str` (`string`): The string to escape regex special characters. #### Returns (`string`): Returns a new string with regex special characters escaped. --- --- url: /reference/compat/string/escapeRegExp.md --- # escapeRegExp (Lodash compatibility) ::: warning Use `escapeRegExp` from `es-toolkit` This `escapeRegExp` function operates slower due to handling non-string input values. Instead, use the faster and more modern [escapeRegExp](../../string/escapeRegExp.md) from `es-toolkit`. ::: Escapes regular expression special characters in a string. ```typescript const result = escapeRegExp(str); ``` ## Usage ### `escapeRegExp(str)` Escapes regular expression special characters `^`, `$`, `\`, `.`, `*`, `+`, `?`, `(`, `)`, `[`, `]`, `{`, `}`, `|` in a string. This is useful when you want to treat a string literally when dynamically creating regular expressions. ```typescript import { escapeRegExp } from 'es-toolkit/compat'; escapeRegExp('[es-toolkit](https://es-toolkit.dev/)'); // '\\[es-toolkit\\]\\(https://es-toolkit\\.dev/\\)' escapeRegExp('$^{}.+*?()[]|\\'); // '\\$\\^\\{\\}\\.\\+\\*\\?\\(\\)\\[\\]\\|\\\\' ``` Non-string values are also converted to strings before processing. ```typescript import { escapeRegExp } from 'es-toolkit/compat'; escapeRegExp(123); // '123' escapeRegExp(null); // '' escapeRegExp(undefined); // '' ``` #### Parameters * `str` (`string`, optional): The string to escape regular expression special characters. #### Returns (`string`): Returns the string with regular expression special characters escaped. --- --- url: /reference/map/every.md --- # every (for `Map`s) Tests whether all entries in a Map satisfy the provided predicate function. ```typescript const allMatch = every(map, doesMatch); ``` ::: info This function is available exclusively from `es-toolkit/map` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `every(map, doesMatch)` Use `every` when you want to check if all entries in a Map meet a specific condition. Provide a predicate function that tests each entry, and it returns true if the predicate is satisfied for all entries, and false otherwise. ```typescript import { every } from 'es-toolkit/map'; const map = new Map([ ['a', 10], ['b', 20], ['c', 30], ]); const result = every(map, value => value > 5); // Result: true const result2 = every(map, value => value > 15); // Result: false ``` You can test various conditions. ```typescript import { every } from 'es-toolkit/map'; // Check if all values meet criteria const inventory = new Map([ ['apple', { quantity: 10, inStock: true }], ['banana', { quantity: 5, inStock: true }], ['orange', { quantity: 8, inStock: true }], ]); const allInStock = every(inventory, item => item.inStock); // Result: true // Check if all keys match pattern const settings = new Map([ ['api.timeout', 5000], ['api.retries', 3], ['api.host', 'localhost'], ]); const allApiSettings = every(settings, (value, key) => key.startsWith('api.')); // Result: true ``` #### Parameters * `map` (`Map`): The Map to test. * `doesMatch` (`(value: V, key: K, map: Map) => boolean`): A predicate function that tests each entry. #### Returns (`boolean`): true if all entries satisfy the predicate, false otherwise. --- --- url: /reference/set/every.md --- # every (for `Set`s) Tests whether all elements in a Set satisfy the provided predicate function. ```typescript const allMatch = every(set, doesMatch); ``` ::: info This function is available exclusively from `es-toolkit/set` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `every(set, doesMatch)` Use `every` when you want to check if all elements in a Set meet a specific condition. Provide a predicate function that tests each element, and it returns true if the predicate is satisfied for all elements, and false otherwise. ```typescript import { every } from 'es-toolkit/set'; const set = new Set([10, 20, 30]); const result = every(set, value => value > 5); // Result: true const result2 = every(set, value => value > 15); // Result: false ``` You can test various conditions. ```typescript import { every } from 'es-toolkit/set'; // Check if all values meet criteria const ages = new Set([25, 30, 35, 40]); const allAdults = every(ages, age => age >= 18); // Result: true const allSeniors = every(ages, age => age >= 65); // Result: false // Check object properties const users = new Set([ { name: 'Alice', active: true }, { name: 'Bob', active: true }, { name: 'Charlie', active: true }, ]); const allActive = every(users, user => user.active); // Result: true ``` #### Parameters * `set` (`Set`): The Set to test. * `doesMatch` (`(value: T, value2: T, set: Set) => boolean`): A predicate function that tests each element. #### Returns (`boolean`): true if all elements satisfy the predicate, false otherwise. --- --- url: /reference/compat/array/every.md --- # every (Lodash Compatibility) ::: warning Use `Array.prototype.every()` This `every` function operates slowly due to complex object processing, support for various condition formats, etc. Instead, use the faster and more modern `Array.prototype.every()`. ::: Checks if all values in an array or object meet the given condition. ```typescript const result = every(collection, predicate); ``` ## Usage ### `every(collection, predicate?)` Use `every` when you want to check if all elements in an array or object satisfy a specific condition. The condition can be specified in various formats such as a function, partial object, property-value pair, property name, etc. ```typescript import { every } from 'es-toolkit/compat'; // Using a test function const numbers = [2, 4, 6, 8]; every(numbers, x => x % 2 === 0); // Returns: true // Using a property name const users = [ { name: 'Alice', active: true }, { name: 'Bob', active: true }, ]; every(users, 'active'); // Returns: true // Using a partial object every(users, { active: true }); // Returns: true // Using a property-value pair every(users, ['active', true]); // Returns: true ``` It works the same way for objects. ```typescript import { every } from 'es-toolkit/compat'; const scores = { math: 90, english: 85, science: 92 }; every(scores, score => score >= 80); // Returns: true ``` `null` or `undefined` are treated as empty collections and return `true`. ```typescript import { every } from 'es-toolkit/compat'; every(null); // Returns: true every(undefined); // Returns: true ``` #### Parameters * `collection` (`ArrayLike | Record | null | undefined`): The array or object to check. * `predicate` (`((item: T, index: number, collection: any) => unknown) | Partial | [keyof T, unknown] | PropertyKey`, optional): The condition to check. Can use a function, partial object, property-value pair, or property name. Defaults to the `identity` function. #### Returns (`boolean`): Returns `true` if all elements satisfy the condition, otherwise `false`. --- --- url: /reference/compat/object/extend.md --- # extend (Lodash Compatibility) ::: warning Use `Object.assign()` instead This `extend` function performs slower due to complex logic that handles properties inherited from the prototype chain. Use the faster and more modern `Object.assign()` instead. ::: Copies own and inherited properties from source objects to a target object. ```typescript const result = extend(object, source); ``` ## Usage ### `extend(object, ...sources)` Use `extend` to copy properties from one object to another. Similar to `Object.assign()`, but also copies inherited properties. This function is an alias of `assignIn`. ```typescript import { extend } from 'es-toolkit/compat'; // Copy basic properties const target = { a: 1 }; extend(target, { b: 2 }, { c: 3 }); // Returns: { a: 1, b: 2, c: 3 } // Also copies inherited properties function Parent() { this.a = 1; } Parent.prototype.b = 2; const source = new Parent(); extend({}, source); // Returns: { a: 1, b: 2 } ``` When there are duplicate properties, later source objects overwrite earlier ones. ```typescript import { extend } from 'es-toolkit/compat'; extend({ a: 1, b: 2 }, { b: 3 }, { c: 4 }); // Returns: { a: 1, b: 3, c: 4 } ``` #### Parameters * `object` (`any`): The target object to receive properties. * `...sources` (`any[]`): The source objects that provide properties. #### Returns (`any`): Returns the object with copied properties. The first argument `object` is modified. --- --- url: /reference/compat/object/extendWith.md --- # extendWith (Lodash compatibility) ::: warning Use `Object.assign()` with a custom function instead This `extendWith` function is complex and slow due to handling inherited properties from the prototype chain and custom merge logic. Use the faster and more modern `Object.assign()` with a custom function instead. ::: Copies own and inherited properties of objects to another object with custom logic. ```typescript const result = extendWith(object, source, customizer); ``` ## Usage ### `extendWith(object, ...sources, customizer)` Use `extendWith` to merge object properties with custom logic. It's similar to `extend` but allows you to decide how each property should be merged. This function is an alias for `assignInWith`. ```typescript import { extendWith } from 'es-toolkit/compat'; // Copy properties with custom merge logic const target = { a: 1, b: 2 }; extendWith(target, { b: 3, c: 4 }, (objValue, srcValue) => { return objValue === undefined ? srcValue : objValue; }); // Returns: { a: 1, b: 2, c: 4 } // Custom merge that concatenates arrays const obj1 = { a: [1, 2] }; const obj2 = { a: [3, 4], b: [5, 6] }; extendWith(obj1, obj2, (objValue, srcValue) => { if (Array.isArray(objValue)) { return objValue.concat(srcValue); } }); // Returns: { a: [1, 2, 3, 4], b: [5, 6] } ``` You can use multiple source objects. ```typescript import { extendWith } from 'es-toolkit/compat'; extendWith({ a: 1 }, { b: 2 }, { c: 3 }, (objValue, srcValue) => srcValue * 2); // Returns: { a: 1, b: 4, c: 6 } ``` #### Parameters * `object` (`any`): The target object to receive properties. * `...sources` (`any[]`): The source objects that provide properties. * `customizer` (`function`): The function that determines the value to assign for each property. It receives `(objValue, srcValue, key, object, source)`. #### Returns (`any`): Returns the object with copied properties. The first argument `object` is modified. --- --- url: /reference/array/fill.md --- # fill Fills array elements with a specified value. Modifies the original array directly. ```typescript const filled = fill(arr, value, start, end); ``` ::: info If you don't want to modify the original array, use [`toFilled`](./toFilled.md). `toFilled` returns a new array instead of modifying the original. ::: ## Usage ### `fill(arr, value, start?, end?)` Use `fill` when you want to fill a specific range of an array with a specified value. It replaces elements from the start position to just before the end position with the provided value. If you don't specify start or end positions, it fills the entire array. ```typescript import { fill } from 'es-toolkit/array'; // Fill the entire array with 'a'. const array1 = [1, 2, 3]; fill(array1, 'a'); // Returns: ['a', 'a', 'a'] // Fill an empty array with 2. const array2 = Array(3); fill(array2, 2); // Returns: [2, 2, 2] // Fill from index 1 to just before 3 with '*'. const array3 = [4, 6, 8, 10]; fill(array3, '*', 1, 3); // Returns: [4, '*', '*', 10] ``` You can also use negative indices. Negative indices count from the end of the array. ```typescript import { fill } from 'es-toolkit/array'; const array = [1, 2, 3]; fill(array, '*', -2, -1); // Returns: [1, '*', 3] ``` #### Parameters * `arr` (`Array`): The array to fill. * `value` (`U`): The value to fill the array with. * `start` (`number`, optional): The start position. Default is `0`. * `end` (`number`, optional): The end position. Default is the array length. #### Returns (`Array`): Returns the original array filled with values. --- --- url: /reference/compat/array/fill.md --- # fill (Lodash Compatibility) ::: warning Use `fill` from `es-toolkit` This `fill` function operates with complex behavior due to handling `null` or `undefined`, support for array-like objects, etc. Instead, use the faster and more modern [`fill`](../../array/fill.md) from `es-toolkit`. ::: Fills the elements of an array with a specified value. ```typescript const result = fill(array, value, start, end); ``` ## Usage ### `fill(array, value, start?, end?)` Use `fill` when you want to fill a specific range or the entire array with the same value. It modifies the original array directly. ```typescript import { fill } from 'es-toolkit/compat'; // Fill entire array const arr1 = [1, 2, 3]; fill(arr1, 'a'); // Returns: ['a', 'a', 'a'] // Fill specific range const arr2 = [1, 2, 3, 4, 5]; fill(arr2, '*', 1, 4); // Returns: [1, '*', '*', '*', 5] // Use negative indices const arr3 = [1, 2, 3, 4, 5]; fill(arr3, 'x', -3, -1); // Returns: [1, 2, 'x', 'x', 5] ``` Array-like objects are also supported. ```typescript import { fill } from 'es-toolkit/compat'; const arrayLike = { 0: 1, 1: 2, 2: 3, length: 3 }; fill(arrayLike, 'a', 1, 2); // Returns: { 0: 1, 1: 'a', 2: 3, length: 3 } ``` `null` or `undefined` arrays are treated as empty arrays. ```typescript import { fill } from 'es-toolkit/compat'; fill(null, 'a'); // Returns: [] fill(undefined, 'a'); // Returns: [] ``` Strings are read-only, so they are returned as is. ```typescript import { fill } from 'es-toolkit/compat'; fill('abc', 'x'); // Returns: 'abc' (not modified) ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to fill. * `value` (`U`): The value to fill the array with. * `start` (`number`, optional): The start position. Defaults to `0`. * `end` (`number`, optional): The end position (not included). Defaults to `array.length`. #### Returns (`ArrayLike`): Returns the array filled with the value. --- --- url: /reference/map/filter.md --- # filter (for `Map`s) Filters a Map based on a predicate function. ```typescript const filtered = filter(map, callback); ``` ::: info This function is available exclusively from `es-toolkit/map` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `filter(map, callback)` Use `filter` when you want to create a new Map containing only the entries that satisfy a specific condition. Provide a predicate function that tests each entry, and it returns a new Map with only the entries for which the predicate returns true. ```typescript import { filter } from 'es-toolkit/map'; const map = new Map([ ['a', 1], ['b', 2], ['c', 3], ['d', 4], ]); const result = filter(map, value => value > 2); // Result: // Map(2) { // 'c' => 3, // 'd' => 4 // } ``` You can filter based on various criteria. ```typescript import { filter } from 'es-toolkit/map'; // Filter by value type const inventory = new Map([ ['apple', { quantity: 10, inStock: true }], ['banana', { quantity: 0, inStock: false }], ['orange', { quantity: 5, inStock: true }], ]); const inStockItems = filter(inventory, item => item.inStock); // Result: Map with 'apple' and 'orange' entries // Filter by key pattern const data = new Map([ ['user_1', 'Alice'], ['admin_1', 'Bob'], ['user_2', 'Charlie'], ]); const users = filter(data, (value, key) => key.startsWith('user_')); // Result: Map with 'user_1' and 'user_2' entries ``` #### Parameters * `map` (`Map`): The Map to filter. * `callback` (`(value: V, key: K, map: Map) => boolean`): A predicate function that tests each entry. #### Returns (`Map`): A new Map containing only the entries that satisfy the predicate. --- --- url: /reference/set/filter.md --- # filter (for `Set`s) Filters a Set based on a predicate function. ```typescript const filtered = filter(set, callback); ``` ::: info This function is available exclusively from `es-toolkit/set` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `filter(set, callback)` Use `filter` when you want to create a new Set containing only the elements that satisfy a specific condition. Provide a predicate function that tests each element, and it returns a new Set with only the elements for which the predicate returns true. ```typescript import { filter } from 'es-toolkit/set'; const set = new Set([1, 2, 3, 4, 5]); const result = filter(set, value => value > 2); // Result: Set(3) { 3, 4, 5 } ``` You can filter based on various criteria. ```typescript import { filter } from 'es-toolkit/set'; // Filter by value type const numbers = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); const evenNumbers = filter(numbers, num => num % 2 === 0); // Result: Set(5) { 2, 4, 6, 8, 10 } // Filter objects const products = new Set([ { name: 'Laptop', price: 1000, available: true }, { name: 'Mouse', price: 25, available: false }, { name: 'Keyboard', price: 75, available: true }, ]); const availableProducts = filter(products, product => product.available); // Result: Set with Laptop and Keyboard ``` #### Parameters * `set` (`Set`): The Set to filter. * `callback` (`(value: T, value2: T, set: Set) => boolean`): A predicate function that tests each element. #### Returns (`Set`): A new Set containing only the elements that satisfy the predicate. --- --- url: /reference/compat/array/filter.md --- # filter (Lodash Compatibility) ::: warning Use `Array.prototype.filter()` This `filter` function operates slowly due to complex object processing, support for various condition formats, etc. Instead, use the faster and more modern `Array.prototype.filter()`. ::: Creates a new array with elements that satisfy the given condition. ```typescript const result = filter(collection, predicate); ``` ## Usage ### `filter(collection, predicate)` Use `filter` when you want to filter out only elements that satisfy a specific condition from an array or object. The condition can be specified in various formats such as a function, partial object, property-value pair, property name, etc. ```typescript import { filter } from 'es-toolkit/compat'; // Using a test function const numbers = [1, 2, 3, 4, 5]; filter(numbers, x => x % 2 === 0); // Returns: [2, 4] // Using a property name const users = [ { name: 'Alice', active: true }, { name: 'Bob', active: false }, { name: 'Charlie', active: true }, ]; filter(users, 'active'); // Returns: [{ name: 'Alice', active: true }, { name: 'Charlie', active: true }] // Using a partial object filter(users, { active: true }); // Returns: [{ name: 'Alice', active: true }, { name: 'Charlie', active: true }] // Using a property-value pair filter(users, ['active', true]); // Returns: [{ name: 'Alice', active: true }, { name: 'Charlie', active: true }] ``` It works the same way for objects, returning an array of values that satisfy the condition. ```typescript import { filter } from 'es-toolkit/compat'; const scores = { math: 90, english: 75, science: 85 }; filter(scores, score => score >= 80); // Returns: [90, 85] ``` `null` or `undefined` are treated as empty arrays. ```typescript import { filter } from 'es-toolkit/compat'; filter(null, x => x > 0); // Returns: [] filter(undefined, x => x > 0); // Returns: [] ``` #### Parameters * `collection` (`ArrayLike | Record | null | undefined`): The array or object to filter. * `predicate` (`((item: T, index: number, collection: any) => unknown) | Partial | [keyof T, unknown] | PropertyKey`): The filtering condition. Can use a function, partial object, property-value pair, or property name. #### Returns (`T[]`): Returns a new array consisting of elements that satisfy the condition. --- --- url: /reference/array/filterAsync.md --- # filterAsync Filters an array using an async predicate function and returns a new array containing only the elements that satisfy the condition. ```typescript const filtered = await filterAsync(array, predicate); ``` ## Reference ### `filterAsync(array, predicate, options?)` Use `filterAsync` to filter an array with async operations like API calls or database queries. Unlike regular `filter`, it supports async predicate functions and allows you to limit concurrency with the `concurrency` option. ```typescript import { filterAsync } from 'es-toolkit/array'; // Filter for active users by checking their status via API. const users = [{ id: 1 }, { id: 2 }, { id: 3 }]; const activeUsers = await filterAsync(users, async user => { return await checkUserStatus(user.id); }); // Returns: Array containing only active users // Limit concurrency to reduce server load. const numbers = [1, 2, 3, 4, 5]; const evenNumbers = await filterAsync(numbers, async n => await isEvenAsync(n), { concurrency: 2 }); // Only 2 operations run concurrently at most. ``` The `concurrency` option helps limit external API calls or manage system resources efficiently. If not specified, all operations run concurrently. ```typescript import { filterAsync } from 'es-toolkit/array'; // Execute at most 3 API calls concurrently. const items = await filterAsync(largeArray, async item => await validateItem(item), { concurrency: 3 }); ``` #### Parameters * `array` (`readonly T[]`): The array to filter. * `predicate` (`(item: T, index: number, array: readonly T[]) => Promise`): An async function that tests each element. If it returns a truthy value, the element is included in the result. * `options` (`FilterAsyncOptions`, optional): Options to control concurrency. * `concurrency` (`number`, optional): Maximum number of concurrent operations. If not specified, all operations run concurrently. #### Returns (`Promise`): A promise that resolves to a new array containing only the elements for which the predicate function returned a truthy value. --- --- url: /reference/set/find.md --- # find (for `Set`s) Finds the first element in a Set for which the predicate function returns true. ```typescript const element = find(set, doesMatch); ``` ::: info This function is available exclusively from `es-toolkit/set` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `find(set, doesMatch)` Use `find` when you want to find the first element in a Set that matches a specific condition. Provide a predicate function that tests each element, and it returns the first matching element or undefined if none is found. ```typescript import { find } from 'es-toolkit/set'; const set = new Set([ { name: 'apple', quantity: 10 }, { name: 'banana', quantity: 5 }, { name: 'grape', quantity: 15 }, ]); const result = find(set, value => value.quantity > 10); // Result: { name: 'grape', quantity: 15 } ``` You can search based on various criteria. ```typescript import { find } from 'es-toolkit/set'; // Find by value property const users = new Set([ { id: 1, name: 'Alice', age: 25 }, { id: 2, name: 'Bob', age: 30 }, { id: 3, name: 'Charlie', age: 35 }, ]); const senior = find(users, user => user.age >= 35); // Result: { id: 3, name: 'Charlie', age: 35 } // Find by string pattern const emails = new Set(['user@example.com', 'admin@example.com', 'info@company.com']); const adminEmail = find(emails, email => email.startsWith('admin')); // Result: 'admin@example.com' ``` #### Parameters * `set` (`Set`): The Set to search. * `doesMatch` (`(value: T, value2: T, set: Set) => boolean`): A predicate function that tests each element. #### Returns (`T | undefined`): The first element that satisfies the predicate, or undefined if none found. --- --- url: /reference/compat/array/find.md --- # find (Lodash Compatibility) ::: warning Use `Array.prototype.find()` This `find` function operates slowly due to complex object processing, support for various condition formats, etc. Instead, use the faster and more modern `Array.prototype.find()`. ::: Finds the first element in an array or object that matches the condition. ```typescript const result = find(collection, predicate, fromIndex); ``` ## Usage ### `find(collection, predicate, fromIndex?)` Use `find` when you want to find the first element that satisfies a specific condition in an array or object. The condition can be specified in various formats such as a function, partial object, property-value pair, property name, etc. ```typescript import { find } from 'es-toolkit/compat'; // Using a test function const numbers = [1, 2, 3, 4, 5]; find(numbers, x => x > 3); // Returns: 4 // Using a property name const users = [ { name: 'Alice', active: false }, { name: 'Bob', active: true }, { name: 'Charlie', active: true }, ]; find(users, 'active'); // Returns: { name: 'Bob', active: true } // Using a partial object find(users, { active: true }); // Returns: { name: 'Bob', active: true } // Using a property-value pair find(users, ['name', 'Charlie']); // Returns: { name: 'Charlie', active: true } ``` You can specify a starting index. ```typescript import { find } from 'es-toolkit/compat'; const numbers = [1, 2, 3, 4, 5]; find(numbers, x => x > 2, 2); // Returns: 3 (starts searching from index 2) ``` It works the same way for objects. ```typescript import { find } from 'es-toolkit/compat'; const scores = { math: 90, english: 75, science: 85 }; find(scores, score => score >= 80); // Returns: 90 ``` `null` or `undefined` are treated as empty collections and return `undefined`. ```typescript import { find } from 'es-toolkit/compat'; find(null, x => x > 0); // Returns: undefined find(undefined, x => x > 0); // Returns: undefined ``` #### Parameters * `collection` (`ArrayLike | Record | null | undefined`): The array or object to search. * `predicate` (`((item: T, index: number, collection: any) => unknown) | Partial | [keyof T, unknown] | PropertyKey`): The search condition. Can use a function, partial object, property-value pair, or property name. * `fromIndex` (`number`, optional): The index to start searching from. Defaults to `0`. #### Returns (`T | undefined`): Returns the first element that satisfies the condition. If not found, returns `undefined`. --- --- url: /reference/compat/array/findIndex.md --- # findIndex (Lodash Compatibility) ::: warning Use `Array.prototype.findIndex` This `findIndex` function operates slowly due to additional features such as handling various condition formats and `fromIndex` processing. Use the faster and more modern `Array.prototype.findIndex` instead. ::: Finds the index of the first element in an array that matches a condition. ```typescript const index = findIndex(arr, doesMatch, fromIndex); ``` ## Usage ### `findIndex(arr, doesMatch, fromIndex)` Use `findIndex` when you want to find the position of the first element in an array that matches a specific condition. You can specify the condition in various ways. If no element matches the condition, it returns `-1`. When you specify a condition as a function, it executes the function for each element and returns the index of the first element that returns true. ```typescript import { findIndex } from 'es-toolkit/compat'; const users = [ { id: 1, name: 'Alice', active: false }, { id: 2, name: 'Bob', active: true }, { id: 3, name: 'Charlie', active: true }, ]; // Specify condition with a function findIndex(users, user => user.active); // Returns: 1 ``` When you specify a condition as a partial object, it returns the index of the first element that matches those properties. ```typescript import { findIndex } from 'es-toolkit/compat'; // Specify condition with a partial object findIndex(users, { name: 'Bob', active: true }); // Returns: 1 ``` When you specify a condition as an array of property name and value, it returns the index of the first element whose property matches that value. ```typescript import { findIndex } from 'es-toolkit/compat'; // Specify condition with a [property, value] array findIndex(users, ['active', true]); // Returns: 1 ``` When you specify only a property name, it returns the index of the first element where that property evaluates to true. ```typescript import { findIndex } from 'es-toolkit/compat'; // Specify condition with a property name findIndex(users, 'active'); // Returns: 1 ``` When you specify `fromIndex`, the search starts from that index. Negative values are calculated from the end of the array. ```typescript import { findIndex } from 'es-toolkit/compat'; // Start search from index 2 findIndex(users, user => user.active, 2); // Returns: 2 // Search from the second element from the end findIndex(users, user => user.active, -2); // Returns: 1 ``` `null` or `undefined` are treated as empty arrays. ```typescript import { findIndex } from 'es-toolkit/compat'; findIndex(null, user => user.active); // -1 findIndex(undefined, 'active'); // -1 ``` #### Parameters * `arr` (`ArrayLike | null | undefined`): The array to search. * `doesMatch` (`((item: T, index: number, arr: any) => unknown) | Partial | [keyof T, unknown] | PropertyKey`, optional): The matching condition. Can be a function, partial object, key-value pair, or property name. * `fromIndex` (`number`, optional): The index to start the search from. Default is `0`. #### Returns (`number`): Returns the index of the first element that matches the condition. Returns `-1` if no element matches. --- --- url: /reference/object/findKey.md --- # findKey Finds the key of the first element that satisfies the given condition. ```typescript const key = findKey(obj, predicate); ``` ## Usage ### `findKey(obj, predicate)` Use `findKey` when you want to find the key of the first element in an object that satisfies a specific condition. It returns the key for the first value where the condition function returns `true`. ```typescript import { findKey } from 'es-toolkit/object'; // Find the first user under 30 years old const users = { alice: { age: 25, active: true }, bob: { age: 30, active: false }, charlie: { age: 35, active: true }, }; const youngUserKey = findKey(users, user => user.age < 30); console.log(youngUserKey); // 'alice' // Find an inactive user const inactiveUserKey = findKey(users, user => !user.active); console.log(inactiveUserKey); // 'bob' // When no element satisfies the condition const seniorUserKey = findKey(users, user => user.age > 50); console.log(seniorUserKey); // undefined ``` The condition function receives the current value, key, and the entire object. ```typescript const data = { item1: { priority: 'high', status: 'pending' }, item2: { priority: 'low', status: 'done' }, item3: { priority: 'high', status: 'done' }, }; // Search considering both key name and value const result = findKey(data, (value, key, obj) => { return key.includes('2') && value.status === 'done'; }); console.log(result); // 'item2' ``` Can also be used with complex object structures. ```typescript const products = { laptop: { specs: { ram: 16, cpu: 'Intel i7' }, price: 1200, available: true, }, phone: { specs: { ram: 8, cpu: 'Snapdragon' }, price: 800, available: false, }, tablet: { specs: { ram: 12, cpu: 'Apple M1' }, price: 1000, available: true, }, }; const affordableKey = findKey(products, product => product.price < 1000 && product.available); console.log(affordableKey); // undefined (no product satisfies the condition) const highRamKey = findKey(products, product => product.specs.ram >= 12); console.log(highRamKey); // 'laptop' ``` #### Parameters * `obj` (`T extends Record`): The object to search. * `predicate` (`(value: T[keyof T], key: keyof T, obj: T) => boolean`): A condition function to execute for each element. Finds the key of the first element that returns `true`. #### Returns (`keyof T | undefined`): The key of the first element that satisfies the condition. Returns `undefined` if no element satisfies the condition. --- --- url: /reference/map/findKey.md --- # findKey (for `Map`s) Finds the first key in a Map for which the predicate function returns true. ```typescript const key = findKey(map, doesMatch); ``` ::: info This function is available exclusively from `es-toolkit/map` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `findKey(map, doesMatch)` Use `findKey` when you want to find the key of the first entry that matches a specific condition. Provide a predicate function that tests each entry, and it returns the key of the first matching entry or undefined if none is found. ```typescript import { findKey } from 'es-toolkit/map'; const map = new Map([ ['apple', { color: 'red', quantity: 10 }], ['banana', { color: 'yellow', quantity: 5 }], ['grape', { color: 'purple', quantity: 15 }], ]); const result = findKey(map, value => value.quantity > 10); // Result: 'grape' ``` You can search based on various criteria. ```typescript import { findKey } from 'es-toolkit/map'; // Find by value property const users = new Map([ ['user1', { name: 'Alice', age: 25 }], ['user2', { name: 'Bob', age: 30 }], ['user3', { name: 'Charlie', age: 35 }], ]); const seniorUser = findKey(users, user => user.age >= 35); // Result: 'user3' // Find by key pattern const settings = new Map([ ['api.timeout', 5000], ['api.retries', 3], ['db.host', 'localhost'], ]); const dbSetting = findKey(settings, (value, key) => key.startsWith('db.')); // Result: 'db.host' ``` #### Parameters * `map` (`Map`): The Map to search. * `doesMatch` (`(value: V, key: K, map: Map) => boolean`): A predicate function that tests each entry. #### Returns (`K | undefined`): The key of the first entry that satisfies the predicate, or undefined if none found. --- --- url: /reference/compat/object/findKey.md --- # findKey (Lodash compatibility) ::: warning Use `es-toolkit`'s `findKey` This `findKey` function operates in a complex manner due to various condition type handling and compatibility logic. Instead, use the faster and more modern [findKey](../../object/findKey.md) from `es-toolkit`. ::: Finds the key of the first element that matches the predicate. ```typescript const key = findKey(obj, predicate); ``` ## Usage ### `findKey(obj, predicate)` Use `findKey` to find the key of the first element in an object that matches the predicate. You can use various types of predicates such as functions, objects, arrays, and strings. ```typescript import { findKey } from 'es-toolkit/compat'; // Find key with a function predicate const users = { alice: { age: 25, active: true }, bob: { age: 30, active: false }, charlie: { age: 35, active: true }, }; findKey(users, user => user.age > 30); // Returns: 'charlie' // Find key with an object predicate findKey(users, { active: false }); // Returns: 'bob' // Find key with a property path findKey(users, 'active'); // Returns: 'alice' ``` If no element matches the predicate, it returns `undefined`. ```typescript import { findKey } from 'es-toolkit/compat'; findKey({ a: 1, b: 2 }, value => value > 5); // Returns: undefined ``` #### Parameters * `obj` (`T | null | undefined`): The object to search. * `predicate` (`ObjectIteratee`, optional): The predicate to apply to each element. Can be a function, object, array, or string. #### Returns (`string | undefined`): Returns the key of the first element that matches the predicate. Returns `undefined` if no match is found. --- --- url: /reference/compat/array/findLast.md --- # findLast (Lodash Compatibility) ::: warning Use `Array.prototype.findLast` This `findLast` function is complex and slow due to handling various types and special conditions. Use the faster and more modern `Array.prototype.findLast` instead. ::: Finds the last element in an array or object that satisfies a condition. ```typescript const lastEven = findLast(array, predicate); ``` ## Usage ### `findLast(collection, predicate?, fromIndex?)` Finds the last element in an array or object that satisfies the given condition. Searches in reverse order from the end of the array and returns the first element that satisfies the condition. ```typescript import { findLast } from 'es-toolkit/compat'; // Specify condition with a function const users = [ { user: 'barney', age: 36 }, { user: 'fred', age: 40 }, { user: 'pebbles', age: 18 }, ]; findLast(users, o => o.age < 40); // => { user: 'pebbles', age: 18 } // Specify condition with an object findLast(users, { age: 36 }); // => { user: 'barney', age: 36 } // Specify condition with a key-value pair findLast(users, ['age', 18]); // => { user: 'pebbles', age: 18 } // Specify condition with a property name (last element with truthy value) findLast(users, 'age'); // => { user: 'fred', age: 40 } ``` You can also specify a starting index for the search. ```typescript import { findLast } from 'es-toolkit/compat'; const numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1]; findLast(numbers, n => n > 3, 6); // Search in reverse from index 6 // => 4 ``` `null` or `undefined` returns empty results. ```typescript import { findLast } from 'es-toolkit/compat'; findLast(null, x => x > 0); // undefined findLast(undefined, x => x > 0); // undefined ``` #### Parameters * `collection` (`ArrayLike | Record | null | undefined`): The array or object to search. * `predicate` (`ListIterateeCustom`, optional): The condition to apply to each element. Can be a function, object, key-value pair, or property name. Default is the `identity` function. * `fromIndex` (`number`, optional): The index to start the search from. If negative, it's calculated from the end. Default is the last index of the array. #### Returns (`T | undefined`): Returns the last element that satisfies the condition. Returns `undefined` if no element satisfies the condition. --- --- url: /reference/compat/array/findLastIndex.md --- # findLastIndex (Lodash Compatibility) ::: warning Use `Array.prototype.findLastIndex` This `findLastIndex` function operates slowly due to additional features such as handling `null` or `undefined`, partial object matching, and property name matching. Use the faster and more modern `Array.prototype.findLastIndex` instead. ::: Finds the index of the last element in an array that satisfies a condition. ```typescript const lastIndex = findLastIndex(array, predicate, fromIndex); ``` ## Usage ### `findLastIndex(array, predicate, fromIndex)` Use `findLastIndex` when you want to find the index of the first element that matches a given condition starting from the end of the array. Returns `-1` if no element satisfies the condition. This function can specify the condition in various ways. When you pass a function, it executes the function for each element. When you pass a partial object, it checks if the element has those properties. When you pass an array-formatted key-value pair, it checks if a specific property matches the given value. When you pass a string, it checks if that property evaluates to a truthy value. ```typescript import { findLastIndex } from 'es-toolkit/compat'; const users = [ { user: 'barney', active: true }, { user: 'fred', active: false }, { user: 'pebbles', active: false }, ]; // Specify the condition using a function findLastIndex(users, o => o.user === 'pebbles'); // Returns: 2 // Find a matching element using a partial object findLastIndex(users, { user: 'barney', active: true }); // Returns: 0 // Find a matching element using a property-value pair findLastIndex(users, ['active', false]); // Returns: 2 // Find an element with a truthy value using a property name findLastIndex(users, 'active'); // Returns: 0 ``` You can also specify a starting position for the search. If `fromIndex` is negative, it's calculated from the end of the array. ```typescript import { findLastIndex } from 'es-toolkit/compat'; const numbers = [1, 2, 3, 4, 5]; // Search in reverse from index 3 findLastIndex(numbers, n => n < 4, 2); // Returns: 2 // If you use a negative index, it's calculated from the end findLastIndex(numbers, n => n > 2, -2); // Returns: 3 ``` `null` or `undefined` are treated as empty arrays. ```typescript import { findLastIndex } from 'es-toolkit/compat'; findLastIndex(null, n => n > 0); // -1 findLastIndex(undefined, n => n > 0); // -1 ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to search. * `predicate` (`((item: T, index: number, arr: any) => unknown) | Partial | [keyof T, unknown] | PropertyKey`, optional): The condition to test each element. Can be a function, partial object, property-value pair, or property name. Default is the identity function. * `fromIndex` (`number`, optional): The index to start the search from. If negative, it's calculated from the end of the array. Default is `array.length - 1`. #### Returns (`number`): Returns the index of the last element that satisfies the condition. Returns `-1` if no element satisfies the condition. --- --- url: /reference/compat/object/findLastKey.md --- # findLastKey (Lodash Compatibility) ::: warning Use `Array.findLast()` and `Object.keys()` instead This `findLastKey` function operates in a complex manner due to various condition type handling and compatibility logic. Instead, use the faster and more modern `Array.findLast()` and `Object.keys()`. ::: Finds the key of the last element matching a predicate, searching from the end. ```typescript const key = findLastKey(obj, predicate); ``` ## Usage ### `findLastKey(obj, predicate)` Use `findLastKey` to find the key of the last element matching a predicate in an object. Unlike `findKey`, it searches from the end. You can use various forms of predicates including functions, objects, arrays, and strings. ```typescript import { findLastKey } from 'es-toolkit/compat'; // Find key using a function predicate const users = { alice: { age: 25, active: true }, bob: { age: 30, active: false }, charlie: { age: 35, active: true }, }; findLastKey(users, user => user.active); // Returns: 'charlie' (first active: true found from the end) // Find key using an object predicate findLastKey(users, { active: true }); // Returns: 'charlie' // Find key using a property path findLastKey(users, 'active'); // Returns: 'charlie' // Find key using a property-value array findLastKey(users, ['active', false]); // Returns: 'bob' ``` If no element matches the predicate, it returns `undefined`. ```typescript import { findLastKey } from 'es-toolkit/compat'; findLastKey({ a: 1, b: 2 }, value => value > 5); // Returns: undefined ``` #### Parameters * `obj` (`T | null | undefined`): The object to search. * `predicate` (`ObjectIteratee`, optional): The predicate to apply to each element. Can be a function, object, array, or string. #### Returns (`string | undefined`): Returns the key of the last element matching the predicate. Returns `undefined` if none found. --- --- url: /reference/map/findValue.md --- # findValue (for `Map`s) Finds the first value in a Map for which the predicate function returns true. ```typescript const value = findValue(map, doesMatch); ``` ::: info This function is available exclusively from `es-toolkit/map` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `findValue(map, doesMatch)` Use `findValue` when you want to find the value of the first entry that matches a specific condition. Provide a predicate function that tests each entry, and it returns the value of the first matching entry or undefined if none is found. ```typescript import { findValue } from 'es-toolkit/map'; const map = new Map([ ['apple', { color: 'red', quantity: 10 }], ['banana', { color: 'yellow', quantity: 5 }], ['grape', { color: 'purple', quantity: 15 }], ]); const result = findValue(map, value => value.quantity > 10); // Result: { color: 'purple', quantity: 15 } ``` You can search based on various criteria. ```typescript import { findValue } from 'es-toolkit/map'; // Find by value property const products = new Map([ ['p1', { name: 'Laptop', price: 1000, inStock: true }], ['p2', { name: 'Mouse', price: 25, inStock: false }], ['p3', { name: 'Keyboard', price: 75, inStock: true }], ]); const expensiveProduct = findValue(products, product => product.price > 500); // Result: { name: 'Laptop', price: 1000, inStock: true } // Find by key pattern const cache = new Map([ ['temp_1', { data: 'foo', timestamp: 100 }], ['perm_1', { data: 'bar', timestamp: 200 }], ['temp_2', { data: 'baz', timestamp: 300 }], ]); const permanent = findValue(cache, (value, key) => key.startsWith('perm_')); // Result: { data: 'bar', timestamp: 200 } ``` #### Parameters * `map` (`Map`): The Map to search. * `doesMatch` (`(value: V, key: K, map: Map) => boolean`): A predicate function that tests each entry. #### Returns (`V | undefined`): The value of the first entry that satisfies the predicate, or undefined if none found. --- --- url: /reference/compat/array/first.md --- # first (Lodash Compatibility) ::: warning Use `head` from `es-toolkit` This `first` function operates slowly due to handling `null` or `undefined` and array-like object conversion. The `head` function from `es-toolkit` operates faster and simpler without this additional processing. Use the faster and more modern [head](../../array/head.md) from `es-toolkit` instead. ::: Returns the first element of an array. ```typescript const firstElement = first(array); ``` ## Usage ### `first(array)` Use `first` when you want to get the first element of an array. Returns `undefined` if the array is empty or is `null` or `undefined`. ```typescript import { first } from 'es-toolkit/compat'; // Get the first element from a regular array first([1, 2, 3]); // Returns: 1 // Get the first element from a string array first(['a', 'b', 'c']); // Returns: 'a' // Empty array first([]); // Returns: undefined ``` `null` or `undefined` returns `undefined`. ```typescript import { first } from 'es-toolkit/compat'; first(null); // undefined first(undefined); // undefined ``` Can be used with array-like objects. ```typescript import { first } from 'es-toolkit/compat'; const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; first(arrayLike); // Returns: 'a' // Strings are also treated like arrays first('hello'); // Returns: 'h' ``` For type-guaranteed tuples, returns the exact type. ```typescript import { first } from 'es-toolkit/compat'; const tuple = [1, 'two', true] as const; first(tuple); // Returns: 1 (type is inferred as 1) ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to get the first element from. #### Returns (`T | undefined`): Returns the first element of the array. Returns `undefined` if the array is empty or invalid. --- --- url: /reference/array/flatMap.md --- # flatMap Transforms each element of an array with a function's return value, then flattens to a specified depth and returns a new array. ```typescript const result = flatMap(arr, iteratee, depth); ``` ## Usage ### `flatMap(arr, iteratee, depth = 1)` Use `flatMap` when you want to transform and flatten an array simultaneously. First, it applies a function to each element, then flattens the resulting array to the specified depth. It works identically to calling [Array#flat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) from JavaScript with [Array#map](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/map) as `map(iteratee).flat(depth)`, but it's faster. ```typescript import { flatMap } from 'es-toolkit/array'; // Duplicate each element twice in a number array. const arr = [1, 2, 3]; flatMap(arr, item => [item, item]); // Returns: [1, 1, 2, 2, 3, 3] // Flatten with depth 2. flatMap(arr, item => [[item, item]], 2); // Returns: [1, 1, 2, 2, 3, 3] ``` You can flatten to various depths. ```typescript import { flatMap } from 'es-toolkit/array'; const arr = [1, 2, 3]; // Flatten with default depth 1. flatMap(arr, item => [item, item]); // Returns: [1, 1, 2, 2, 3, 3] // Flatten with depth 3. flatMap(arr, item => [[[item, item]]], 3); // Returns: [1, 1, 2, 2, 3, 3] ``` #### Parameters * `arr` (`T[]`): The array to transform. * `iteratee` (`(item: T, index: number, array: readonly T[]) => U`): The function that transforms each array element. It receives the element, its index, and the array. * `depth` (`D`, optional): The depth to flatten. Default is `1`. #### Returns (`Array>`): Returns a new array where each element is transformed and flattened to the specified depth. ## Examples ```typescript // Using index parameter const arr = [1, 2, 3]; flatMap(arr, (item, index) => [item + index]); // Returns: [1, 3, 5] // Using array parameter flatMap(arr, (item, _index, array) => [item * array.length]); // Returns: [3, 6, 9] ``` --- --- url: /reference/compat/array/flatMap.md --- # flatMap (Lodash Compatibility) ::: warning Use `flatMap` from `es-toolkit` This `flatMap` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, and supporting various condition function formats. Use the faster and more modern [flatMap](../../array/flatMap.md) from `es-toolkit` instead. ::: Applies a function to each element and flattens the result. ```typescript const result = flatMap(collection, iteratee); ``` ## Usage ### `flatMap(collection, iteratee)` Applies an iteratee function to each element of a collection and returns an array flattened by one level. Supports arrays, objects, and strings, and can use various forms of iteratees. ```typescript import { flatMap } from 'es-toolkit/compat'; // Apply a function to an array function duplicate(n) { return [n, n]; } flatMap([1, 2], duplicate); // Result: [1, 1, 2, 2] // Apply a function to an object const obj = { a: 1, b: 2 }; flatMap(obj, (value, key) => [key, value]); // Result: ['a', 1, 'b', 2] // Map with a string property const users = [ { user: 'barney', hobbies: ['hiking', 'coding'] }, { user: 'fred', hobbies: ['reading'] }, ]; flatMap(users, 'hobbies'); // Result: ['hiking', 'coding', 'reading'] ``` Using without an iteratee flattens the values by one level. ```typescript import { flatMap } from 'es-toolkit/compat'; const obj = { a: [1, 2], b: [3, 4] }; flatMap(obj); // Result: [1, 2, 3, 4] ``` Conditional mapping with a partial object is also possible. ```typescript import { flatMap } from 'es-toolkit/compat'; const users = [ { user: 'barney', age: 36, active: true }, { user: 'fred', age: 40, active: false }, ]; flatMap(users, { active: false }); // Result: [false, true] (matching result of elements where active is false) ``` #### Parameters * `collection` (`object | null | undefined`): The collection to iterate over. Can be an array, object, or string. * `iteratee` (`ListIterator | ObjectIterator | string | object`, optional): The iteratee to apply to each element. Can be a function, property name, or partial object. #### Returns (`any[]`): Returns a new array flattened by one level after mapping. --- --- url: /reference/array/flatMapAsync.md --- # flatMapAsync Transforms each element in an array using an async function and flattens the result by one level to return a new array. ```typescript const result = await flatMapAsync(array, callback); ``` ## Reference ### `flatMapAsync(array, callback, options?)` Use `flatMapAsync` when performing async transformations where each element returns multiple values. It's equivalent to calling `mapAsync` followed by `flat()`, but more efficient. ```typescript import { flatMapAsync } from 'es-toolkit/array'; // Fetch posts for each user and combine into a single array. const users = [{ id: 1 }, { id: 2 }]; const allPosts = await flatMapAsync(users, async user => { return await fetchUserPosts(user.id); }); // Returns: [post1, post2, post3, ...] (all users' posts in a single array) // Limit concurrency. const numbers = [1, 2, 3]; const results = await flatMapAsync(numbers, async n => await fetchRelatedItems(n), { concurrency: 2 }); // Only 2 operations run concurrently at most. ``` Each callback function must return an array, and all returned arrays are merged into a single array. The `concurrency` option allows you to limit concurrent executions to manage server load. ```typescript import { flatMapAsync } from 'es-toolkit/array'; // Fetch product lists for each category and combine into a single array. const categories = ['electronics', 'books', 'clothing']; const products = await flatMapAsync(categories, async category => await fetchProducts(category), { concurrency: 2 }); // Returns: A single array containing products from all categories ``` #### Parameters * `array` (`readonly T[]`): The array to transform. * `callback` (`(item: T, index: number, array: readonly T[]) => Promise`): An async function that transforms each element into an array. * `options` (`FlatMapAsyncOptions`, optional): Options to control concurrency. * `concurrency` (`number`, optional): Maximum number of concurrent operations. If not specified, all operations run concurrently. #### Returns (`Promise`): A promise that resolves to an array of transformed values flattened by one level. --- --- url: /reference/array/flatMapDeep.md --- # flatMapDeep Transforms each element of an array with a function's return value, then flattens all depths and returns a new array. ```typescript const result = flatMapDeep(arr, iteratee); ``` ## Usage ### `flatMapDeep(arr, iteratee)` Use `flatMapDeep` when you want to transform an array while completely flattening all nested arrays. First, it applies a function to each element, then flattens the resulting array to all depths. ```typescript import { flatMapDeep } from 'es-toolkit/array'; // Duplicate each element twice and flatten completely. const result1 = flatMapDeep([1, 2, 3], item => [item, item]); // Returns: [1, 1, 2, 2, 3, 3] ``` It flattens all depths no matter how deeply nested. ```typescript import { flatMapDeep } from 'es-toolkit/array'; // Flatten nested arrays completely. const result = flatMapDeep([1, 2, 3], item => [[item, item]]); // Returns: [1, 1, 2, 2, 3, 3] // Flatten multiple levels of nesting. const result2 = flatMapDeep([1, 2, 3], item => [[[item, item]]]); // Returns: [1, 1, 2, 2, 3, 3] ``` #### Parameters * `arr` (`T[]`): The array to transform. * `iteratee` (`(item: T, index: number, array: readonly T[]) => U`): The function that transforms each array element. It receives the element, its index, and the array. #### Returns (`Array>`): Returns a new array where each element is transformed and all depths are flattened. ## Examples ```typescript // Using index parameter const arr = [1, 2, 3]; flatMapDeep(arr, (item, index) => [[item + index]]); // Returns: [1, 3, 5] // Using array parameter flatMapDeep(arr, (item, _index, array) => [[item * array.length]]); // Returns: [3, 6, 9] ``` --- --- url: /reference/compat/array/flatMapDeep.md --- # flatMapDeep (Lodash Compatibility) ::: warning Use [`flatMapDeep`](../../array/flatMapDeep.md) from `es-toolkit` This `flatMapDeep` function operates slowly due to complex collection type handling and deep flattening logic. Use the faster and more modern [flatMapDeep](../../array/flatMapDeep.md) from `es-toolkit` instead. ::: Applies a function to each element and recursively flattens the result. ```typescript const result = flatMapDeep(collection, iteratee); ``` ## Usage ### `flatMapDeep(collection, iteratee)` Applies an iteratee function to each element of a collection and returns an array flattened to infinite depth. All nested array structures are flattened into a one-dimensional array. ```typescript import { flatMapDeep } from 'es-toolkit/compat'; // Apply a function to an array and deeply flatten function duplicate(n) { return [[[n, n]]]; } flatMapDeep([1, 2], duplicate); // Result: [1, 1, 2, 2] // Apply a function to an object and deeply flatten const obj = { a: 1, b: 2 }; flatMapDeep(obj, (value, key) => [[[key, value]]]); // Result: ['a', 1, 'b', 2] // Map with a string property and deeply flatten const users = [ { user: 'barney', hobbies: [['hiking', 'coding']] }, { user: 'fred', hobbies: [['reading']] }, ]; flatMapDeep(users, 'hobbies'); // Result: ['hiking', 'coding', 'reading'] ``` Using without an iteratee recursively flattens the values. ```typescript import { flatMapDeep } from 'es-toolkit/compat'; const obj = { a: [[1, 2]], b: [[[3]]] }; flatMapDeep(obj); // Result: [1, 2, 3] ``` Conditional mapping with a partial object is also possible. ```typescript import { flatMapDeep } from 'es-toolkit/compat'; const users = [ { user: 'barney', active: [true, false] }, { user: 'fred', active: [false] }, ]; flatMapDeep(users, { active: [false] }); // Result: [true, true] (matching result of elements with active array containing [false]) ``` #### Parameters * `collection` (`object | null | undefined`): The collection to iterate over. Can be an array, object, or string. * `iteratee` (`ListIterator | ObjectIterator | string | object`, optional): The iteratee to apply to each element. Can be a function, property name, or partial object. #### Returns (`any[]`): Returns a new array recursively flattened after mapping. --- --- url: /reference/compat/array/flatMapDepth.md --- # flatMapDepth (Lodash Compatibility) ::: warning Use [flatMap](../../array/flatMap.md) from `es-toolkit` This `flatMapDepth` function is implemented in a complex way to support various forms of iteratees and handle `null` or `undefined` for Lodash compatibility. The `flatMap` function in the main library only supports simple function iteratees, so it operates faster. Use the faster and more modern [flatMap](../../array/flatMap.md) from `es-toolkit` instead. ::: Transforms each element of an array with an iteratee function and flattens to the specified depth. ```typescript const result = flatMapDepth(collection, iteratee, depth); ``` ## Usage ### `flatMapDepth(collection, iteratee, depth)` Transforms each element of an array or object with the given function, then flattens the result to the specified depth and returns a new array. Useful when you want to flatten nested array structures only to a desired depth. ```typescript import { flatMapDepth } from 'es-toolkit/compat'; // Transform an array and flatten to depth 2 flatMapDepth([1, 2], n => [[n, n]], 2); // => [1, 1, 2, 2] // When limited to depth 1, it's not fully flattened flatMapDepth([1, 2], n => [[n, n]], 1); // => [[1, 1], [2, 2]] // Extract values from an object and flatten const users = [ { user: 'barney', hobbies: [['hiking'], ['coding']] }, { user: 'fred', hobbies: [['reading']] }, ]; flatMapDepth(users, 'hobbies', 2); // => ['hiking', 'coding', 'reading'] ``` This function supports various forms of iteratees. ```typescript import { flatMapDepth } from 'es-toolkit/compat'; // Transform with a function flatMapDepth([1, 2, 3], n => [[n, n]], 2); // Extract values by property name const objects = [{ items: [['a'], ['b']] }, { items: [['c']] }]; flatMapDepth(objects, 'items', 2); // => ['a', 'b', 'c'] // Partial matching with an object const users = [{ active: [[true], [false]] }, { active: [[false]] }]; flatMapDepth(users, { active: [[false]] }, 2); // => [true, true] ``` `null` or `undefined` are treated as empty arrays. ```typescript import { flatMapDepth } from 'es-toolkit/compat'; flatMapDepth(null, n => [n], 1); // => [] flatMapDepth(undefined, n => [n], 1); // => [] ``` #### Parameters * `collection` (`ArrayLike | Record | Record | object | null | undefined`): The array or object to iterate over. * `iteratee` (`((value: T, index: number, collection: any) => any) | string | object`, optional): The transformation function or property name to execute for each element. Default is `identity`. * `depth` (`number`, optional): The maximum depth to flatten. Default is `1`. #### Returns (`T[]`): Returns a new array flattened to the specified depth after transformation with the iteratee. --- --- url: /reference/array/flatten.md --- # flatten Returns a new array that is flattened to the specified depth. ```typescript const result = flatten(arr, depth); ``` ## Usage ### `flatten(arr, depth = 1)` Use `flatten` when you want to flatten a nested array to a specific depth. It unwinds arrays within arrays to the specified level, creating a flatter structure. It works identically to the [Array#flat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) included in the JavaScript language, but it's faster. ```typescript import { flatten } from 'es-toolkit/array'; // Flatten with default depth of 1 const array = [1, [2, 3], [4, [5, 6]]]; flatten(array); // Returns: [1, 2, 3, 4, [5, 6]] // Flatten with depth of 2 flatten(array, 2); // Returns: [1, 2, 3, 4, 5, 6] ``` You can control the depth to flatten only to the desired level. ```typescript import { flatten } from 'es-toolkit/array'; const array = [1, [2, 3], [4, [5, 6]]]; // Flatten with depth of 1 (default) const result1 = flatten(array, 1); // Returns: [1, 2, 3, 4, [5, 6]] // Flatten with depth of 2 const result2 = flatten(array, 2); // Returns: [1, 2, 3, 4, 5, 6] ``` #### Parameters * `arr` (`T[]`): The nested array to flatten. * `depth` (`D`, optional): The depth to flatten. Defaults to `1`. #### Returns (`Array>`): Returns a new array flattened to the specified depth. --- --- url: /reference/compat/array/flatten.md --- # flatten (Lodash Compatibility) ::: warning Use `flatten` from `es-toolkit` This `flatten` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, and supporting various condition function formats. Use the faster and more modern [flatten](../../array/flatten.md) from `es-toolkit` instead. ::: Flattens an array by one level. ```typescript const result = flatten(array, depth); ``` ## Usage ### `flatten(value, depth)` Flattens a nested array by the specified depth. By default, it flattens only one level, and also supports Arguments objects and objects with Symbol.isConcatSpreadable. ```typescript import { flatten } from 'es-toolkit/compat'; // Basic flattening (one level) flatten([1, [2, [3, [4]], 5]]); // Result: [1, 2, [3, [4]], 5] // Specify depth flatten([1, [2, [3, [4]], 5]], 2); // Result: [1, 2, 3, [4], 5] // Support for Arguments objects function example() { return flatten(arguments); } example(1, [2, 3], [[4]]); // Result: [1, 2, 3, [4]] ``` Empty arrays, null, or undefined return empty arrays. ```typescript import { flatten } from 'es-toolkit/compat'; flatten(null); // [] flatten(undefined); // [] flatten([]); // [] ``` Objects with Symbol.isConcatSpreadable are also flattened like arrays. ```typescript import { flatten } from 'es-toolkit/compat'; const spreadable = { 0: 'a', 1: 'b', length: 2, [Symbol.isConcatSpreadable]: true }; flatten([1, spreadable, 3]); // Result: [1, 'a', 'b', 3] ``` #### Parameters * `value` (`ArrayLike | null | undefined`): The array to flatten. * `depth` (`number`, optional): The maximum depth to flatten. Default is `1`. #### Returns (`T[]`): Returns a new flattened array. --- --- url: /reference/array/flattenDeep.md --- # flattenDeep Returns a new array with all depths of a nested array flattened. ```typescript const result = flattenDeep(arr); ``` ## Usage ### `flattenDeep(arr)` Use `flattenDeep` when you want to completely flatten a nested array, no matter how deeply nested it is. It unwinds all nested arrays within the array, creating a single flat structure. It works identically to calling [Array#flat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) as `flat(Infinity)` in the JavaScript language, but it's faster. ```typescript import { flattenDeep } from 'es-toolkit/array'; // Flatten all nested levels const array = [1, [2, [3]], [4, [5, 6]]]; const result = flattenDeep(array); // Returns: [1, 2, 3, 4, 5, 6] ``` It completely flattens even highly complex nested structures. ```typescript import { flattenDeep } from 'es-toolkit/array'; const complexArray = [1, [2, [3, [4, [5]]]], 6]; const result = flattenDeep(complexArray); // Returns: [1, 2, 3, 4, 5, 6] ``` #### Parameters * `arr` (`T[]`): The nested array to flatten. #### Returns (`Array>`): Returns a new array with all depths flattened. --- --- url: /reference/compat/array/flattenDeep.md --- # flattenDeep (Lodash Compatibility) ::: warning Use `flattenDeep` from `es-toolkit` This `flattenDeep` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, and supporting various condition function formats. Use the faster and more modern [flattenDeep](../../array/flattenDeep.md) from `es-toolkit` instead. ::: Completely flattens an array. ```typescript const result = flattenDeep(array); ``` ## Usage ### `flattenDeep(value)` Recursively flattens a nested array at all depths. All nesting levels are removed, returning a completely flattened one-dimensional array. ```typescript import { flattenDeep } from 'es-toolkit/compat'; // Completely flatten a deeply nested array flattenDeep([1, [2, [3, [4]], 5]]); // Result: [1, 2, 3, 4, 5] // Completely flatten a complex nested structure flattenDeep([1, [2, [3, [[[[4]]]]], 5]]); // Result: [1, 2, 3, 4, 5] // Support for mixed types flattenDeep(['a', ['b', ['c', [['d']]]]]); // Result: ['a', 'b', 'c', 'd'] ``` Empty arrays, null, or undefined return empty arrays. ```typescript import { flattenDeep } from 'es-toolkit/compat'; flattenDeep(null); // [] flattenDeep(undefined); // [] flattenDeep([]); // [] ``` Already flattened arrays are copied as-is. ```typescript import { flattenDeep } from 'es-toolkit/compat'; flattenDeep([1, 2, 3, 4, 5]); // Result: [1, 2, 3, 4, 5] ``` #### Parameters * `value` (`ListOfRecursiveArraysOrValues | null | undefined`): The array to completely flatten. #### Returns (`Array`): Returns a new completely flattened array with all nesting removed. --- --- url: /reference/compat/array/flattenDepth.md --- # flattenDepth (Lodash Compatibility) ::: warning Use `flatten` from `es-toolkit` This `flattenDepth` function operates slowly due to handling `null` or `undefined`. The `flatten` function from `es-toolkit` operates faster and simpler without this additional processing. Use the faster and more modern [flatten](../../array/flatten.md) from `es-toolkit` instead. ::: Flattens an array to the specified depth. ```typescript const flattened = flattenDepth(array, depth); ``` ## Usage ### `flattenDepth(array, depth)` Use `flattenDepth` when you want to flatten a nested array to a desired depth. When you specify a depth, it flattens the nested array only to that depth. ```typescript import { flattenDepth } from 'es-toolkit/compat'; // Flatten to depth 1 flattenDepth([1, [2, [3, [4]], 5]], 1); // Returns: [1, 2, [3, [4]], 5] // Flatten to depth 2 flattenDepth([1, [2, [3, [4]], 5]], 2); // Returns: [1, 2, 3, [4], 5] // If no depth is specified, it defaults to 1 flattenDepth([1, [2, [3, [4]], 5]]); // Returns: [1, 2, [3, [4]], 5] ``` `null` or `undefined` are treated as empty arrays. ```typescript import { flattenDepth } from 'es-toolkit/compat'; flattenDepth(null, 2); // [] flattenDepth(undefined, 2); // [] ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to flatten. * `depth` (`number`, optional): The maximum depth to flatten. Default is `1`. #### Returns (`T[]`): Returns a new array flattened to the specified depth. --- --- url: /reference/object/flattenObject.md --- # flattenObject Converts a nested object into a flat object. ```typescript const flattened = flattenObject(object, options?); ``` ## Usage ### `flattenObject(object, options?)` Use `flattenObject` when you want to flatten deeply nested objects or arrays using dot (`.`) notation for keys. Each nested property becomes a single-level object with keys connected by a delimiter. ```typescript import { flattenObject } from 'es-toolkit/object'; // Flatten a nested object const nestedObject = { a: { b: { c: 1, }, }, d: [2, 3], e: 'simple', }; const flattened = flattenObject(nestedObject); console.log(flattened); // { // 'a.b.c': 1, // 'd.0': 2, // 'd.1': 3, // 'e': 'simple' // } // Use a custom delimiter const withCustomDelimiter = flattenObject(nestedObject, { delimiter: '/' }); console.log(withCustomDelimiter); // { // 'a/b/c': 1, // 'd/0': 2, // 'd/1': 3, // 'e': 'simple' // } ``` It's useful for flattening configuration objects like this: ```typescript // Flatten a configuration object const config = { database: { host: 'localhost', port: 5432, credentials: { username: 'admin', password: 'secret', }, }, features: ['auth', 'logging'], debug: true, }; const flatConfig = flattenObject(config); console.log(flatConfig); // { // 'database.host': 'localhost', // 'database.port': 5432, // 'database.credentials.username': 'admin', // 'database.credentials.password': 'secret', // 'features.0': 'auth', // 'features.1': 'logging', // 'debug': true // } ``` Using `options.delimiter`, you can flatten the object with custom characters like underscores (`_`) instead of dots (`.`). ```typescript // Environment variable style with underscores const envStyle = flattenObject(config, { delimiter: '_' }); console.log(envStyle); // { // 'database_host': 'localhost', // 'database_port': 5432, // 'database_credentials_username': 'admin', // 'database_credentials_password': 'secret', // 'features_0': 'auth', // 'features_1': 'logging', // 'debug': true // } ``` Empty objects and special cases are handled appropriately. ```typescript // Empty objects or arrays const emptyCase = { empty: {}, emptyArray: [], nullValue: null, undefinedValue: undefined, }; const result = flattenObject(emptyCase); console.log(result); // { // 'empty': {}, // 'emptyArray: [], // 'nullValue': null, // 'undefinedValue': undefined // } // Empty objects and empty arrays appear as keys ``` #### Parameters * `object` (`object`): The object to flatten. * `options` (`FlattenObjectOptions`, optional): Flattening options. * `delimiter` (`string`, optional): The delimiter to connect nested keys. Defaults to `'.'`. #### Returns (`Record`): A new object with all nested properties flattened. --- --- url: /reference/compat/function/flip.md --- # flip (Lodash Compatibility) ::: warning Use direct argument reversal This `flip` function simply reverses the order of function arguments. In most cases, it can be replaced with simpler approaches. Instead, use the faster and more modern `(...args) => func(...args.reverse())` or direct argument passing. ::: Creates a function that reverses the order of arguments for the given function. ```typescript const flippedFunc = flip(func); ``` ## Usage ### `flip(func)` Use `flip` when you want to create a new function by reversing the order of arguments. It changes the function to receive arguments from the last one first instead of the original order from the first one. ```typescript import { flip } from 'es-toolkit/compat'; function greet(greeting: string, name: string) { return `${greeting}, ${name}!`; } const flipped = flip(greet); flipped('John', 'Hello'); // 'Hello, John!' // The original function takes (greeting, name) order // But the flipped function takes (name, greeting) order ``` For functions that accept multiple arguments, all arguments are reversed. ```typescript import { flip } from 'es-toolkit/compat'; function fn(a: string, b: string, c: string, d: string) { return [a, b, c, d]; } const flipped = flip(fn); flipped('1', '2', '3', '4'); // ['4', '3', '2', '1'] ``` #### Parameters * `func` (`F`): The function to reverse arguments for. #### Returns (`(...args: Reversed>) => ReturnType`): Returns a new function with reversed arguments. --- --- url: /reference/compat/math/floor.md --- # floor (Lodash Compatibility) ::: warning Use `Math.floor` This `floor` function operates slowly due to decimal place calculations and internal function calls. Use the faster and more modern `Math.floor` instead. ::: Rounds a number down to the specified decimal places. ```typescript const result = floor(number, precision); ``` ## Usage ### `floor(number, precision?)` Use `floor` when you want to round a number down to a specific decimal place. ```typescript import { floor } from 'es-toolkit/compat'; // Basic floor (to integer) floor(4.9); // Returns: 4 floor(4.1); // Returns: 4 // Floor to 2 decimal places floor(6.994, 2); // Returns: 6.99 floor(6.999, 2); // Returns: 6.99 // Floor with negative precision (units of 10) floor(6040, -2); // Returns: 6000 floor(1234, -2); // Returns: 1200 // Negative numbers are also floored floor(-4.1); // Returns: -5 floor(-6.994, 2); // Returns: -7.00 ``` #### Parameters * `number` (`number`): The number to round down. * `precision` (`number`, optional): The number of decimal places to round down to. Defaults to `0`. #### Returns (`number`): Returns the number rounded down to the specified decimal places. --- --- url: /reference/function/flow.md --- # flow Creates a new function that executes multiple functions in sequence. ```typescript const combinedFunc = flow(func1, func2, func3); ``` ## Usage ### `flow(...funcs)` Use `flow` when you want to chain functions together to create a pipeline. The result of the previous function becomes the input of the next function. This is useful for transforming data through multiple steps. ```typescript import { flow } from 'es-toolkit/function'; const add = (x: number, y: number) => x + y; const square = (n: number) => n * n; const double = (n: number) => n * 2; const combined = flow(add, square, double); // First add(1, 2) = 3 // Then square(3) = 9 // Finally double(9) = 18 combined(1, 2); // Returns: 18 ``` This is especially useful for creating data transformation pipelines. ```typescript const processData = flow( (text: string) => text.trim(), (text: string) => text.toLowerCase(), (text: string) => text.split(' '), (words: string[]) => words.filter(word => word.length > 3) ); processData(' Hello World JavaScript '); // Returns: ['hello', 'world', 'javascript'] ``` #### Parameters * `funcs` (`Array<(...args: any[]) => any>`): The functions to execute in sequence. #### Returns (`(...args: any[]) => any`): A new function that executes the given functions in sequence. The first function can accept multiple arguments, and the remaining functions receive the result of the previous function. --- --- url: /reference/compat/function/flow.md --- # flow (Lodash Compatibility) ::: warning Use `es-toolkit`'s `flow` This `flow` function has become complex with added array flattening for Lodash compatibility. Instead, use the faster and more modern `es-toolkit`'s [flow](../../function/flow.md). ::: Creates a new function that executes the given functions from left to right sequentially. ```typescript const combinedFunc = flow(...functions); ``` ## Usage ### `flow(...functions)` Use `flow` when you want to create a single composed function that executes multiple functions from left to right sequentially. It's useful for creating data transformation pipelines. ```typescript import { flow } from 'es-toolkit/compat'; // Basic usage function add(x, y) { return x + y; } function square(n) { return n * n; } function double(n) { return n * 2; } // Executes from left to right: double(square(add(x, y))) const calculate = flow(add, square, double); console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 // Passing functions as an array const calculate2 = flow([add, square], double); console.log(calculate2(2, 3)); // 50 // Modern alternative (recommended) const modernCalculate = (x, y) => double(square(add(x, y))); console.log(modernCalculate(1, 2)); // 18 // Using pipe operator (future JavaScript) const pipeCalculate = (x, y) => add(x, y) |> square |> double; // Or chaining pattern class Calculator { constructor(value) { this.value = value; } add(n) { this.value += n; return this; } square() { this.value *= this.value; return this; } double() { this.value *= 2; return this; } valueOf() { return this.value; } } const chainedResult = new Calculator(3).square().double().valueOf(); // 18 ``` #### Parameters * `...functions` (`Array`): Functions to execute from left to right. Can be passed as arrays. #### Returns (`Function`): Returns a new composed function that executes all functions from left to right sequentially. --- --- url: /reference/function/flowRight.md --- # flowRight Creates a new function that executes the given functions in sequence from right to left. ```typescript const combined = flowRight(func1, func2, func3); ``` ## Usage ### `flowRight(...funcs)` Use `flowRight` when you want to create a new function that executes multiple functions from right to left in sequence. The return value of the previous function is passed as a parameter to the next function. This is useful for creating data transformation pipelines by composing functions in reverse order. It executes functions in the opposite direction to `flow`. ```typescript import { flowRight } from 'es-toolkit/function'; const add = (x: number, y: number) => x + y; const square = (n: number) => n * n; const double = (n: number) => n * 2; // Executes from right to left: double -> square -> add const combined = flowRight(double, square, add); console.log(combined(1, 2)); // 18 // Execution order: add(1, 2) = 3, square(3) = 9, double(9) = 18 // Can also be used with a single function const single = flowRight((x: number) => x + 1); console.log(single(5)); // 6 ``` The `this` context is also passed to the functions. ```typescript import { flowRight } from 'es-toolkit/function'; const context = { multiplier: 3, }; function multiply(this: typeof context, x: number) { return x * this.multiplier; } const add = (x: number) => x + 10; const combined = flowRight(multiply, add).bind(context); console.log(combined(5)); // 45 // Execution order: add(5) = 15, multiply(15) = 45 ``` #### Parameters * `funcs` (`(...args: any[]) => any`): The functions to compose. #### Returns (`(...args: any[]) => any`): Returns a new function that executes the given functions from right to left in sequence. --- --- url: /reference/compat/function/flowRight.md --- # flowRight (Lodash Compatibility) ::: warning Use `es-toolkit`'s `flowRight` This `flowRight` function has become complex with added array flattening for Lodash compatibility. Instead, use the faster and more modern `es-toolkit`'s [flowRight](../../function/flowRight.md). ::: Creates a new function that executes the given functions from right to left sequentially. ```typescript const combinedFunc = flowRight(...functions); ``` ## Usage ### `flowRight(...functions)` Use `flowRight` when you want to create a single composed function that executes multiple functions from right to left sequentially. It's useful for creating data transformation pipelines. ```typescript import { flowRight } from 'es-toolkit/compat'; // Basic usage function add(x, y) { return x + y; } function square(n) { return n * n; } function double(n) { return n * 2; } // Executes from right to left: double(square(add(x, y))) const calculate = flowRight(double, square, add); console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 // Passing functions as an array const calculate2 = flowRight([double, square], add); console.log(calculate2(2, 3)); // 50 // Modern alternative (recommended) const modernCalculate = (x, y) => double(square(add(x, y))); console.log(modernCalculate(1, 2)); // 18 // Or using function chaining const chainedCalculate = (x, y) => [x, y] .reduce((acc, val, idx) => idx === 0 ? val : acc + val) .valueOf() |> (n => n * n) |> (n => n * 2); ``` Generally works in the opposite order of `flow`. It works similarly to function composition, making it intuitive. #### Parameters * `...functions` (`Array`): Functions to execute from right to left. Can be passed as arrays. #### Returns (`Function`): Returns a new composed function that executes all functions from right to left sequentially. --- --- url: /reference/map/forEach.md --- # forEach (for `Map`s) Executes a provided function once for each entry in a Map. ```typescript forEach(map, callback); ``` ::: info This function is available exclusively from `es-toolkit/map` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `forEach(map, callback)` Use `forEach` when you want to execute a function for each entry in a Map. The callback function receives the value, key, and the Map itself as arguments. This is useful for side effects like logging, updating external state, or performing operations on each entry. ```typescript import { forEach } from 'es-toolkit/map'; const map = new Map([ ['a', 1], ['b', 2], ['c', 3], ]); forEach(map, (value, key) => { console.log(`${key}: ${value}`); }); // Output: // a: 1 // b: 2 // c: 3 ``` You can perform various operations on each entry. ```typescript import { forEach } from 'es-toolkit/map'; // Accumulate values const prices = new Map([ ['apple', 1.5], ['banana', 0.75], ['orange', 2.0], ]); let total = 0; forEach(prices, value => { total += value; }); // total is now 4.25 // Collect entries into an array const users = new Map([ ['user1', { name: 'Alice', age: 25 }], ['user2', { name: 'Bob', age: 30 }], ]); const userList: string[] = []; forEach(users, (value, key) => { userList.push(`${key}: ${value.name} (${value.age})`); }); // userList: ['user1: Alice (25)', 'user2: Bob (30)'] // Update external Map based on conditions const inventory = new Map([ ['item1', { stock: 10, price: 5 }], ['item2', { stock: 0, price: 10 }], ['item3', { stock: 5, price: 15 }], ]); const outOfStock = new Map(); forEach(inventory, (value, key) => { if (value.stock === 0) { outOfStock.set(key, value); } }); // outOfStock contains item2 ``` #### Parameters * `map` (`Map`): The Map to iterate over. * `callback` (`(value: V, key: K, map: Map) => void`): A function to execute for each entry. #### Returns (`void`): This function does not return a value. --- --- url: /reference/set/forEach.md --- # forEach (for `Set`s) Executes a provided function once for each element in a Set. ```typescript forEach(set, callback); ``` ::: info This function is available exclusively from `es-toolkit/set` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `forEach(set, callback)` Use `forEach` when you want to execute a function for each element in a Set. The callback function receives the value twice (for consistency with Map.forEach) and the Set itself as arguments. This is useful for side effects like logging, updating external state, or performing operations on each element. ```typescript import { forEach } from 'es-toolkit/set'; const set = new Set([1, 2, 3]); forEach(set, value => { console.log(value * 2); }); // Output: // 2 // 4 // 6 ``` You can perform various operations on each element. ```typescript import { forEach } from 'es-toolkit/set'; // Accumulate values const numbers = new Set([1, 2, 3, 4, 5]); let sum = 0; forEach(numbers, value => { sum += value; }); // sum is now 15 // Collect elements into an array with transformation const names = new Set(['alice', 'bob', 'charlie']); const uppercased: string[] = []; forEach(names, value => { uppercased.push(value.toUpperCase()); }); // uppercased: ['ALICE', 'BOB', 'CHARLIE'] // Update external Set based on conditions const scores = new Set([85, 92, 78, 95, 88]); const highScores = new Set(); forEach(scores, value => { if (value >= 90) { highScores.add(value); } }); // highScores contains 92 and 95 // Process objects const users = new Set([ { id: 1, name: 'Alice', active: true }, { id: 2, name: 'Bob', active: false }, { id: 3, name: 'Charlie', active: true }, ]); const activeUserIds: number[] = []; forEach(users, user => { if (user.active) { activeUserIds.push(user.id); } }); // activeUserIds: [1, 3] ``` #### Parameters * `set` (`Set`): The Set to iterate over. * `callback` (`(value: T, value2: T, set: Set) => void`): A function to execute for each element. #### Returns (`void`): This function does not return a value. --- --- url: /reference/compat/array/forEach.md --- # forEach (Lodash compatible) ::: warning Use `Array.prototype.forEach()` instead This `forEach` function operates slowly due to complex object processing, early termination logic, and more. Use the faster and more modern `Array.prototype.forEach()` instead. ::: Executes a function for each element of an array or object. ```typescript forEach(collection, callback); ``` ## Usage ### `forEach(collection, callback)` Use `forEach` when you want to iterate over all elements of an array or object and execute a callback function for each element. The iteration stops if the callback returns `false`. ```typescript import { forEach } from 'es-toolkit/compat'; // Iterate over array const numbers = [1, 2, 3, 4, 5]; const results: number[] = []; forEach(numbers, value => { results.push(value * 2); }); // results is [2, 4, 6, 8, 10] // Early termination const numbers2 = [1, 2, 3, 4, 5]; const results2: number[] = []; forEach(numbers2, value => { if (value > 3) { return false; // Stop iteration } results2.push(value); }); // results2 is [1, 2, 3] ``` Works the same way with objects. ```typescript import { forEach } from 'es-toolkit/compat'; const obj = { a: 1, b: 2, c: 3 }; const keys: string[] = []; const values: number[] = []; forEach(obj, (value, key) => { keys.push(key); values.push(value); }); // keys is ['a', 'b', 'c'] // values is [1, 2, 3] ``` `null` or `undefined` are treated as empty collections. ```typescript import { forEach } from 'es-toolkit/compat'; forEach(null, value => { console.log(value); // Not executed }); forEach(undefined, value => { console.log(value); // Not executed }); ``` #### Parameters * `collection` (`ArrayLike | Record | null | undefined`): The array or object to iterate over. * `callback` (`(value: T, index: number | string, collection: any) => void | false`): The function to execute for each element. Returns `false` to stop iteration. #### Returns (`T`): Returns the original collection that was iterated over. --- --- url: /reference/array/forEachAsync.md --- # forEachAsync Executes an async function for each element in an array. ```typescript await forEachAsync(array, callback); ``` ## Reference ### `forEachAsync(array, callback, options?)` Use `forEachAsync` to perform async operations with side effects for each element in an array. Unlike regular `forEach`, it returns a promise that resolves when all async operations complete. ```typescript import { forEachAsync } from 'es-toolkit/array'; // Update all user information. const users = [{ id: 1 }, { id: 2 }, { id: 3 }]; await forEachAsync(users, async user => { await updateUser(user.id); }); // All user updates completed. // Limit concurrency. const items = [1, 2, 3, 4, 5]; await forEachAsync(items, async item => await processItem(item), { concurrency: 2 }); // Only 2 items are processed concurrently at most. ``` The `concurrency` option allows you to limit concurrent executions to control load on servers or databases. It's useful for operations that don't return values, like logging, file uploads, or database updates. ```typescript import { forEachAsync } from 'es-toolkit/array'; // Upload files sequentially. const files = ['file1.txt', 'file2.txt', 'file3.txt']; await forEachAsync(files, async file => await uploadFile(file), { concurrency: 1 }); // Only one file is uploaded at a time. ``` #### Parameters * `array` (`readonly T[]`): The array to iterate over. * `callback` (`(item: T, index: number, array: readonly T[]) => Promise`): An async function to execute for each element. * `options` (`ForEachAsyncOptions`, optional): Options to control concurrency. * `concurrency` (`number`, optional): Maximum number of concurrent operations. If not specified, all operations run concurrently. #### Returns (`Promise`): A promise that resolves when all operations complete. --- --- url: /reference/array/forEachRight.md --- # forEachRight Iterates over the elements of an array from right to left, executing a function for each element. ```typescript forEachRight(arr, callback); ``` ## Usage ### `forEachRight(arr, callback)` Use `forEachRight` when you want to traverse an array in reverse order and perform an operation on each element. It calls the callback function sequentially from the last element to the first element of the array. This is useful when you need reverse processing or when you need to work from the end of the array. ```typescript import { forEachRight } from 'es-toolkit/array'; const array = [1, 2, 3]; const result: number[] = []; // Use the forEachRight function to traverse the array in reverse order forEachRight(array, value => { result.push(value); }); console.log(result); // [3, 2, 1] ``` The callback function receives three parameters. ```typescript import { forEachRight } from 'es-toolkit/array'; const array = ['a', 'b', 'c']; forEachRight(array, (value, index, arr) => { console.log(`Value: ${value}, Index: ${index}, Array:`, arr); }); // Output: // Value: c, Index: 2, Array: ['a', 'b', 'c'] // Value: b, Index: 1, Array: ['a', 'b', 'c'] // Value: a, Index: 0, Array: ['a', 'b', 'c'] ``` #### Parameters * `arr` (`T[]`): The array to iterate over. * `callback` (`(value: T, index: number, arr: T[]) => void`): The function to be executed for each element. * `value`: The current array element being processed. * `index`: The index of the current element being processed. * `arr`: The array that the `forEachRight` function was called upon. --- --- url: /reference/compat/array/forEachRight.md --- # forEachRight (Lodash Compatibility) ::: warning Use `forEachRight` from `es-toolkit` This `forEachRight` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, support for various predicate function formats, etc. Instead, use the faster and more modern [`forEachRight`](../../array/forEachRight.md) from `es-toolkit`. ::: Iterates over elements of an array or object from right to left and executes a function for each element. ```typescript forEachRight(collection, callback); ``` ## Usage ### `forEachRight(collection, callback)` Iterates through each element of an array, object, or string from right to left and executes the given callback function. The iteration stops if the callback returns `false`. ```typescript import { forEachRight } from 'es-toolkit/compat'; // Iterate array in reverse order forEachRight([1, 2, 3], (value, index) => { console.log(value, index); }); // Output: 3 2, 2 1, 1 0 // Iterate string in reverse order forEachRight('abc', (char, index) => { console.log(char, index); }); // Output: 'c' 2, 'b' 1, 'a' 0 // Iterate object in reverse order forEachRight({ a: 1, b: 2, c: 3 }, (value, key) => { console.log(value, key); }); // Output: 3 'c', 2 'b', 1 'a' ``` `null` or `undefined` are returned as is. ```typescript import { forEachRight } from 'es-toolkit/compat'; forEachRight(null, value => console.log(value)); // null forEachRight(undefined, value => console.log(value)); // undefined ``` The iteration stops if the callback returns `false`. ```typescript import { forEachRight } from 'es-toolkit/compat'; forEachRight([1, 2, 3, 4], value => { console.log(value); if (value === 2) { return false; // Stop iteration } }); // Output: 4, 3, 2 ``` #### Parameters * `collection` (`ArrayLike | Record | string | null | undefined`): The collection to iterate over. Can be an array, object, string, or null/undefined. * `callback` (`(item: any, index: any, arr: any) => unknown`, optional): The function to execute for each element. Returns `false` to stop iteration. Default is the `identity` function. #### Returns (`ArrayLike | Record | string | null | undefined`): Returns the original collection as is. --- --- url: /reference/compat/object/forIn.md --- # forIn (Lodash Compatibility) ::: warning Use `Object.keys` and `for...in` loop instead This `forIn` function operates slowly due to handling `null` or `undefined`, setting up default `iteratee`, and more. Instead, use the faster and more modern `Object.keys` and `for...in` loop. ::: Iterates over all properties of an object (including inherited properties) and invokes a function for each property. ```typescript const result = forIn(obj, iteratee); ``` ## Usage ### `forIn(object, iteratee)` Iterates over all properties of an object and invokes the `iteratee` function. It iterates not only over the object's own properties but also over properties inherited through the prototype chain. If the `iteratee` function returns `false`, the iteration stops. ```typescript import { forIn } from 'es-toolkit/compat'; // Iterate over all properties of an object const obj = { a: 1, b: 2 }; forIn(obj, (value, key) => { console.log(key, value); }); // Output: 'a' 1, 'b' 2 // Iterate including inherited properties function Parent() { this.inherited = 'value'; } Parent.prototype.protoProperty = 'proto'; const child = new Parent(); child.own = 'ownValue'; forIn(child, (value, key) => { console.log(key, value); }); // Output: 'inherited' 'value', 'own' 'ownValue', 'protoProperty' 'proto' // Early exit based on condition forIn(obj, (value, key) => { console.log(key, value); return key !== 'a'; // Stop after 'a' }); // Output: 'a' 1 ``` `null` or `undefined` is returned as is. ```typescript import { forIn } from 'es-toolkit/compat'; forIn(null, iteratee); // null forIn(undefined, iteratee); // undefined ``` #### Parameters * `object` (`T | null | undefined`): The object to iterate over. * `iteratee` (`(value: T[keyof T], key: string, collection: T) => any`, optional): The function to invoke for each property. Defaults to the `identity` function. #### Returns (`T | null | undefined`): Returns the original object. --- --- url: /reference/compat/object/forInRight.md --- # forInRight (Lodash compatibility) ::: warning Use `Object.keys` and `for...in` loops instead This `forInRight` function performs slowly due to creating key arrays, reverse iteration, and handling `null` or `undefined`. Instead, use the faster and more modern `Object.keys` and `for...in` loops. ::: Iterates over all properties of an object (including inherited properties) in reverse order, calling a function for each property. ```typescript const result = forInRight(obj, iteratee); ``` ## Usage ### `forInRight(object, iteratee)` Iterates over all properties of the object in reverse order, calling the `iteratee` function. It iterates not only over the object's own properties but also over properties inherited through the prototype chain. Since it collects keys into an array and then iterates in reverse order, it's slower than normal iteration. If the `iteratee` function returns `false`, the iteration stops. ```typescript import { forInRight } from 'es-toolkit/compat'; // Iterate over all properties in reverse order const obj = { a: 1, b: 2 }; forInRight(obj, (value, key) => { console.log(key, value); }); // Output: 'b' 2, 'a' 1 // Iterate in reverse order including inherited properties function Parent() { this.inherited = 'value'; } Parent.prototype.protoProperty = 'proto'; const child = new Parent(); child.own = 'ownValue'; forInRight(child, (value, key) => { console.log(key, value); }); // Output: 'protoProperty' 'proto', 'own' 'ownValue', 'inherited' 'value' // Early termination based on condition forInRight(obj, (value, key) => { console.log(key, value); return key !== 'a'; // Stop at 'a' }); // Output: 'b' 2, 'a' 1 ``` `null` or `undefined` is returned as is. ```typescript import { forInRight } from 'es-toolkit/compat'; forInRight(null, iteratee); // null forInRight(undefined, iteratee); // undefined ``` #### Parameters * `object` (`T | null | undefined`): The object to iterate over. * `iteratee` (`(value: T[keyof T], key: string, collection: T) => any`, optional): The function to call for each property. Defaults to the `identity` function. #### Returns (`T | null | undefined`): Returns the original object. --- --- url: /reference/compat/object/forOwn.md --- # forOwn (Lodash compatibility) ::: warning Use `Object.keys` with a loop instead This `forOwn` function operates slowly due to internally calling the `keys` function, object conversion processes, and handling of `null` or `undefined`. Instead, use the faster and more modern `Object.keys` with a loop. ::: Iterates over only the object's own properties, calling a function for each property. ```typescript const result = forOwn(obj, iteratee); ``` ## Usage ### `forOwn(object, iteratee)` Iterates over only the object's own properties, calling the `iteratee` function. It iterates only over properties directly owned by the object, excluding inherited properties and `Symbol` keys. If the `iteratee` function returns `false`, iteration stops. ```typescript import { forOwn } from 'es-toolkit/compat'; // Iterate over only own properties of the object const obj = { a: 1, b: 2 }; forOwn(obj, (value, key) => { console.log(key, value); }); // Output: 'a' 1, 'b' 2 // Exclude inherited properties function Parent() { this.inherited = 'value'; } Parent.prototype.protoProperty = 'proto'; const child = new Parent(); child.own = 'ownValue'; forOwn(child, (value, key) => { console.log(key, value); }); // Output: 'inherited' 'value', 'own' 'ownValue' (protoProperty is excluded) // Early termination based on condition forOwn(obj, (value, key) => { console.log(key, value); return key !== 'a'; // Stop after 'a' }); // Output: 'a' 1 ``` Returns `null` or `undefined` as is. ```typescript import { forOwn } from 'es-toolkit/compat'; forOwn(null, iteratee); // null forOwn(undefined, iteratee); // undefined ``` #### Parameters * `object` (`T | null | undefined`): The object to iterate over. * `iteratee` (`(value: T[keyof T], key: string, collection: T) => any`, optional): The function to call for each property. Defaults to the `identity` function. #### Returns (`T | null | undefined`): Returns the original object. --- --- url: /reference/compat/object/forOwnRight.md --- # forOwnRight (Lodash compatibility) ::: warning Use `Object.keys` and loops This `forOwnRight` function operates slowly due to internal calls to the `keys` function, object transformation processes, and reverse iteration. Instead, use the faster and more modern `Object.keys` with loops. ::: Iterates over only own properties of an object in reverse order, calling a function for each property. ```typescript const result = forOwnRight(obj, iteratee); ``` ## Usage ### `forOwnRight(object, iteratee)` Iterates over only own properties of an object in reverse order, calling the `iteratee` function. It iterates only over properties directly owned by the object in reverse order, excluding inherited properties and `Symbol` keys. Since it collects keys into an array and then iterates in reverse order, it is slower than normal iteration. If the `iteratee` function returns `false`, iteration is stopped. ```typescript import { forOwnRight } from 'es-toolkit/compat'; // Iterate only own properties in reverse order const obj = { a: 1, b: 2 }; forOwnRight(obj, (value, key) => { console.log(key, value); }); // Output: 'b' 2, 'a' 1 // Iterate in reverse order excluding inherited properties function Parent() { this.inherited = 'value'; } Parent.prototype.protoProperty = 'proto'; const child = new Parent(); child.own = 'ownValue'; forOwnRight(child, (value, key) => { console.log(key, value); }); // Output: 'own' 'ownValue', 'inherited' 'value' (protoProperty is excluded) // Early termination based on condition forOwnRight(obj, (value, key) => { console.log(key, value); return key !== 'a'; // Stop at 'a' }); // Output: 'b' 2, 'a' 1 ``` `null` or `undefined` is returned as is. ```typescript import { forOwnRight } from 'es-toolkit/compat'; forOwnRight(null, iteratee); // null forOwnRight(undefined, iteratee); // undefined ``` #### Parameters * `object` (`T | null | undefined`): The object to iterate over. * `iteratee` (`(value: T[keyof T], key: string, collection: T) => any`, optional): The function to call for each property. Defaults to the `identity` function. #### Returns (`T | null | undefined`): Returns the original object. --- --- url: /reference/compat/object/fromPairs.md --- # fromPairs (Lodash compatibility) ::: warning Use `Object.fromEntries` This `fromPairs` function operates slowly due to array-like object checks and iteration processing. Use the faster and more modern `Object.fromEntries` instead. ::: Converts an array of key-value pairs into an object. ```typescript const result = fromPairs(pairs); ``` ## Usage ### `fromPairs(pairs)` Takes an array of key-value pairs and converts them into an object. Each key-value pair must be an array with 2 elements. The first element becomes the key, and the second element becomes the value. This is useful when organizing or transforming data. ```typescript import { fromPairs } from 'es-toolkit/compat'; // Basic key-value pair conversion const pairs = [ ['a', 1], ['b', 2], ['c', 3], ]; const result = fromPairs(pairs); // Result: { a: 1, b: 2, c: 3 } // Handling various value types const mixedPairs = [ ['name', 'John'], ['age', 30], ['active', true], ]; const user = fromPairs(mixedPairs); // Result: { name: 'John', age: 30, active: true } ``` Values that are `null`, `undefined`, or not array-like objects are treated as empty objects. ```typescript import { fromPairs } from 'es-toolkit/compat'; fromPairs(null); // {} fromPairs(undefined); // {} fromPairs('invalid'); // {} ``` #### Parameters * `pairs` (`ArrayLike<[PropertyName, T]> | ArrayLike | null | undefined`): An array of key-value pairs to convert into an object. #### Returns (`Record | Record`): Returns an object created from the key-value pairs. --- --- url: /reference/compat/object/functions.md --- # functions (Lodash compatibility) ::: warning Use `Object.keys` and `typeof` check This `functions` function operates slowly as it internally goes through the `keys` function and filtering process. Instead, use the faster and more modern `Object.keys` and `typeof` check. ::: Returns an array of the names of the object's own properties that are functions. ```typescript const functionNames = functions(obj); ``` ## Usage ### `functions(object)` Checks the object's own properties and returns an array of only the names of properties that are functions. It excludes inherited properties and `Symbol` keys, checking only string key properties that the object directly owns. This is useful when finding methods of an object or handling only function properties separately. ```typescript import { functions } from 'es-toolkit/compat'; // Basic usage const obj = { name: 'John', age: 30, greet: () => 'Hello', calculate: function (x, y) { return x + y; }, }; const functionNames = functions(obj); // Result: ['greet', 'calculate'] // Finding functions in a class instance class Calculator { constructor() { this.value = 0; this.add = function (n) { this.value += n; }; } multiply(n) { this.value *= n; } } Calculator.prototype.divide = function (n) { this.value /= n; }; const calc = new Calculator(); const methods = functions(calc); // Result: ['add'] (inherited multiply, divide are excluded) // Object with no functions const data = { x: 1, y: 2, z: 'text' }; const noFunctions = functions(data); // Result: [] ``` `null` or `undefined` are treated as empty arrays. ```typescript import { functions } from 'es-toolkit/compat'; functions(null); // [] functions(undefined); // [] ``` #### Parameters * `object` (`any`): The object to check. #### Returns (`string[]`): Returns an array of the names of properties that are functions. --- --- url: /reference/compat/object/functionsIn.md --- # functionsIn (Lodash compatibility) ::: warning Use `for...in` loop and `typeof` check instead This `functionsIn` function operates slowly due to the `for...in` loop and function checking process. Instead, use the faster and more modern `for...in` loop and `typeof` check. ::: Returns an array of the names of all properties (including inherited properties) of an object that are functions. ```typescript const functionNames = functionsIn(obj); ``` ## Usage ### `functionsIn(object)` Checks all properties of an object and returns an array of only the names of properties that are functions. It checks not only the object's own properties but also all properties inherited through the prototype chain. This is useful for finding all methods (including inherited methods) of an object. ```typescript import { functionsIn } from 'es-toolkit/compat'; // Basic usage const obj = { name: 'John', age: 30, greet: () => 'Hello', calculate: function (x, y) { return x + y; }, }; const functionNames = functionsIn(obj); // Result: ['greet', 'calculate'] // Including inherited functions class Calculator { constructor() { this.value = 0; this.add = function (n) { this.value += n; }; } multiply(n) { this.value *= n; } } Calculator.prototype.divide = function (n) { this.value /= n; }; const calc = new Calculator(); const allMethods = functionsIn(calc); // Result: ['add', 'divide'] (`multiply` is non-enumerable) // Inheritance through prototype chain function Parent() { this.parentMethod = function () { return 'parent'; }; } Parent.prototype.protoMethod = function () { return 'proto'; }; function Child() { Parent.call(this); this.childMethod = function () { return 'child'; }; } Child.prototype = Object.create(Parent.prototype); const child = new Child(); const inheritedFunctions = functionsIn(child); // Result: ['parentMethod', 'childMethod', 'protoMethod'] ``` `null` or `undefined` are treated as empty arrays. ```typescript import { functionsIn } from 'es-toolkit/compat'; functionsIn(null); // [] functionsIn(undefined); // [] ``` #### Parameters * `object` (`any`): The object to inspect. #### Returns (`string[]`): Returns an array of the names of properties that are functions (including inherited functions). --- --- url: /reference/compat/object/get.md --- # get (Lodash Compatibility) ::: warning Use dot notation or bracket notation instead This `get` function performs slowly due to complex path parsing, handling `null` or `undefined`, and default value processing. Instead, use the faster and more modern dot notation (`.`), bracket notation (`[]`), or optional chaining (`?.`). ::: Gets the value at the specified path of an object. ```typescript const value = get(object, path, defaultValue); ``` ## Usage ### `get(object, path, defaultValue?)` Use `get` to safely retrieve a value from an object path. When the path doesn't exist or the value is `undefined`, it returns the default value. ```typescript import { get } from 'es-toolkit/compat'; // Access nested object with dot notation const object = { a: { b: { c: 3 } } }; get(object, 'a.b.c'); // => 3 // Access with array notation get(object, ['a', 'b', 'c']); // => 3 // Provide default value for non-existent path get(object, 'a.b.d', 'default'); // => 'default' // Path with array index const arrayObject = { users: [{ name: 'john' }, { name: 'jane' }] }; get(arrayObject, 'users[0].name'); // => 'john' ``` Safely accesses `null` or `undefined` objects. ```typescript import { get } from 'es-toolkit/compat'; get(null, 'a.b.c', 'default'); // => 'default' get(undefined, ['a', 'b'], 'default'); // => 'default' ``` #### Parameters * `object` (`any`): The object to query. * `path` (`PropertyPath`): The path of the property to get. Can be represented as a string, number, symbol, or array. * `defaultValue` (`any`, optional): The default value to return when the value is `undefined`. #### Returns (`any`): Returns the resolved value or the default value. --- --- url: /reference/array/groupBy.md --- # groupBy Returns a new object with array elements grouped according to a key-generating function. ```typescript const grouped = groupBy(arr, getKeyFromItem); ``` ## Usage ### `groupBy(arr, getKeyFromItem)` Use `groupBy` when you want to classify array elements based on specific criteria. Provide a function that generates a key from each element, and it groups elements with the same key together and returns them as an object. The values in the returned object are arrays of elements belonging to each group. This is useful for organizing data by category or performing group-based analysis. ```typescript import { groupBy } from 'es-toolkit/array'; // Group an array of objects by category const items = [ { category: 'fruit', name: 'apple' }, { category: 'fruit', name: 'banana' }, { category: 'vegetable', name: 'carrot' }, ]; const result = groupBy(items, item => item.category); // Result: // { // fruit: [ // { category: 'fruit', name: 'apple' }, // { category: 'fruit', name: 'banana' } // ], // vegetable: [ // { category: 'vegetable', name: 'carrot' } // ] // } ``` You can group by various criteria. ```typescript import { groupBy } from 'es-toolkit/array'; // Group by string length const words = ['one', 'two', 'three', 'four', 'five']; const byLength = groupBy(words, word => word.length); // Result: { 3: ['one', 'two'], 4: ['four', 'five'], 5: ['three'] } // Group by even/odd const numbers = [1, 2, 3, 4, 5, 6]; const byParity = groupBy(numbers, num => (num % 2 === 0 ? 'even' : 'odd')); // Result: { odd: [1, 3, 5], even: [2, 4, 6] } ``` #### Parameters * `arr` (`T[]`): The array to group. * `getKeyFromItem` (`(item: T, index: number, array: T[]) => K`): A function that generates a key from each element, its index, and the array. #### Returns (`Record`): Returns an object with elements grouped by key. ## Examples ```typescript // Using index parameter const items = ['a', 'b', 'c', 'd']; const result = groupBy(items, (item, index) => (index % 2 === 0 ? 'even' : 'odd')); // Result: { even: ['a', 'c'], odd: ['b', 'd'] } // Using array parameter const numbers = [1, 2, 3, 4]; const result2 = groupBy(numbers, (item, index, arr) => (item < arr.length / 2 ? 'small' : 'large')); // Result: { small: [1], large: [2, 3, 4] } ``` --- --- url: /reference/compat/array/groupBy.md --- # groupBy (Lodash Compatibility) ::: warning Use [`groupBy`](../../array/groupBy.md) from `es-toolkit` This `groupBy` function operates slowly due to handling `null` or `undefined`, object support, complex type processing, etc. Instead, use the faster and more modern [`groupBy`](../../array/groupBy.md) from `es-toolkit`. ::: Groups elements of an array or object based on a given condition. ```typescript const grouped = groupBy(collection, iteratee); ``` ## Usage ### `groupBy(collection, iteratee)` Groups each element of an array or object based on a given condition function and returns an object with groups. The condition can be provided in various forms such as a function, property name, partial object, etc. ```typescript import { groupBy } from 'es-toolkit/compat'; // Group by function const array = [6.1, 4.2, 6.3]; const result = groupBy(array, Math.floor); // result is { '4': [4.2], '6': [6.1, 6.3] } // Group by property name const users = [ { name: 'john', age: 30 }, { name: 'jane', age: 25 }, { name: 'bob', age: 30 }, ]; const byAge = groupBy(users, 'age'); // byAge is { '25': [{ name: 'jane', age: 25 }], '30': [{ name: 'john', age: 30 }, { name: 'bob', age: 30 }] } // Group from object const obj = { a: 6.1, b: 4.2, c: 6.3 }; const groupedObj = groupBy(obj, Math.floor); // groupedObj is { '4': [4.2], '6': [6.1, 6.3] } ``` `null` or `undefined` are treated as empty objects. ```typescript import { groupBy } from 'es-toolkit/compat'; groupBy(null, x => x); // {} groupBy(undefined, x => x); // {} ``` You can also group by partial object or property-value pair. ```typescript import { groupBy } from 'es-toolkit/compat'; const products = [ { category: 'fruit', name: 'apple' }, { category: 'fruit', name: 'banana' }, { category: 'vegetable', name: 'carrot' }, ]; // Group by partial object const byCategory = groupBy(products, { category: 'fruit' }); // Group by property-value pair const byName = groupBy(products, ['name', 'apple']); ``` #### Parameters * `collection` (`ArrayLike | Record | null | undefined`): The array or object to group. * `iteratee` (`Function | PropertyKey | Array | Object`, optional): The condition to group by. Can be a function, property name, property-value pair, or partial object. Default is the `identity` function. #### Returns (`Record`): Returns an object where each key is the condition value and the value is an array of elements belonging to that group. --- --- url: /reference/compat/util/gt.md --- # gt (Lodash Compatibility) ::: warning Use the `>` operator instead This `gt` function performs slower due to additional processing like `toNumber` function calls and string type checking. Instead, use the faster and more modern `>` operator. ::: Checks if value is greater than other. ```typescript const result = gt(value, other); ``` ## Usage ### `gt(value, other)` Use `gt` when you want to compare two values to check if the first value is greater than the second. Strings are compared lexicographically, and other types are converted to numbers for comparison. ```typescript import { gt } from 'es-toolkit/compat'; gt(3, 1); // Returns: true gt(3, 3); // Returns: false gt(1, 3); // Returns: false // String comparison (lexicographical) gt('def', 'abc'); // Returns: true gt('abc', 'def'); // Returns: false // Other types are converted to numbers for comparison gt('10', 5); // Returns: true (10 > 5) gt(1, null); // Returns: true (1 > 0) ``` #### Parameters * `value` (`unknown`): The first value to compare. * `other` (`unknown`): The second value to compare. #### Returns (`boolean`): Returns `true` if the first value is greater than the second, `false` otherwise. --- --- url: /reference/compat/util/gte.md --- # gte (Lodash Compatibility) ::: warning Use the `>=` operator instead This `gte` function performs slower due to additional processing like `toNumber` function calls and string type checking. Instead, use the faster and more modern `>=` operator. ::: Checks if value is greater than or equal to other. ```typescript const result = gte(value, other); ``` ## Usage ### `gte(value, other)` Use `gte` when you want to compare two values to check if the first value is greater than or equal to the second. Strings are compared lexicographically, and other types are converted to numbers for comparison. ```typescript import { gte } from 'es-toolkit/compat'; gte(3, 1); // Returns: true gte(3, 3); // Returns: true gte(1, 3); // Returns: false // String comparison (lexicographical) gte('def', 'abc'); // Returns: true gte('abc', 'def'); // Returns: false // Other types are converted to numbers for comparison gte('10', 5); // Returns: true (10 >= 5) gte(1, null); // Returns: true (1 >= 0) ``` #### Parameters * `value` (`unknown`): The first value to compare. * `other` (`unknown`): The second value to compare. #### Returns (`boolean`): Returns `true` if the first value is greater than or equal to the second, `false` otherwise. --- --- url: /reference/compat/object/has.md --- # has (Lodash Compatibility) ::: warning Use `Object.hasOwn` or `in` operator instead This `has` function is slow due to complex path parsing and array index handling. Instead, use the faster and more modern `Object.hasOwn()` or the `in` operator. ::: Checks if a property at the specified path exists in an object. ```typescript const exists = has(object, path); ``` ## Usage ### `has(object, path)` Use `has` to check if an object has a property at a specific path. It only checks own properties and does not check inherited properties. ```typescript import { has } from 'es-toolkit/compat'; // Simple property check const object = { a: 1, b: 2 }; has(object, 'a'); // => true // Nested object check const nested = { a: { b: { c: 3 } } }; has(nested, 'a.b.c'); // => true has(nested, ['a', 'b', 'c']); // => true // Non-existent property has(nested, 'a.b.d'); // => false // Array index check const array = [1, 2, 3]; has(array, 2); // => true has(array, 5); // => false ``` It works correctly with sparse arrays too. ```typescript import { has } from 'es-toolkit/compat'; const sparse = [1, , 3]; // index 1 is empty has(sparse, 0); // true has(sparse, 1); // true - actually exists, but value is undefined has(sparse, 2); // true ``` #### Parameters * `object` (`any`): The object to query. * `path` (`PropertyPath`): The path of the property to check. Can be represented as a string, number, symbol, or array. #### Returns (`boolean`): Returns `true` if the property exists at the path, otherwise `false`. --- --- url: /reference/compat/object/hasIn.md --- # hasIn (Lodash compatibility) ::: warning Use the `in` operator instead This `hasIn` function performs slowly due to complex path parsing and prototype chain checking. Instead, use the faster and more modern `in` operator or `Object.hasOwn()` function. ::: Checks if a property at the specified path exists in the object, including inherited properties. ```typescript const exists = hasIn(object, path); ``` ## Usage ### `hasIn(object, path)` Use `hasIn` when you want to check if an object has a property at a specific path. Unlike `has`, it also checks inherited properties (properties in the prototype chain). ```typescript import { hasIn } from 'es-toolkit/compat'; // Check own properties const object = { a: 1, b: 2 }; hasIn(object, 'a'); // => true // Check nested objects const nested = { a: { b: { c: 3 } } }; hasIn(nested, 'a.b.c'); // => true hasIn(nested, ['a', 'b', 'c']); // => true // Non-existent property hasIn(nested, 'a.b.d'); // => false // Check array indices const array = [1, 2, 3]; hasIn(array, 2); // => true hasIn(array, 5); // => false ``` It also checks inherited properties. ```typescript import { hasIn } from 'es-toolkit/compat'; // Check properties in the prototype chain function Rectangle() {} Rectangle.prototype.area = function () {}; const rect = new Rectangle(); hasIn(rect, 'area'); // true - finds inherited properties too has(rect, 'area'); // false - has only checks own properties ``` Safely handles `null` and `undefined`. ```typescript import { hasIn } from 'es-toolkit/compat'; hasIn(null, 'a'); // => false hasIn(undefined, 'b'); // => false ``` #### Parameters * `object` (`any`): The object to inspect. * `path` (`PropertyPath`): The path of the property to check. This can be represented as a string, number, symbol, or array. #### Returns (`boolean`): Returns `true` if the property at the path exists (whether it's an own property or inherited property), otherwise `false`. --- --- url: /reference/map/hasValue.md --- # hasValue (for `Map`s) Checks if a Map contains a specific value. ```typescript const exists = hasValue(map, searchElement); ``` ::: info This function is available exclusively from `es-toolkit/map` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `hasValue(map, searchElement)` Use `hasValue` when you want to check if a Map contains a specific value. This function uses SameValueZero comparison (similar to Array.prototype.includes), which means that NaN is considered equal to NaN. ```typescript import { hasValue } from 'es-toolkit/map'; const map = new Map([ ['a', 1], ['b', 2], ['c', 3], ]); const result = hasValue(map, 2); // Result: true const result2 = hasValue(map, 5); // Result: false ``` You can search for various value types. ```typescript import { hasValue } from 'es-toolkit/map'; // Search for NaN (using SameValueZero comparison) const numbers = new Map([ ['a', 1], ['b', NaN], ['c', 3], ]); const hasNaN = hasValue(numbers, NaN); // Result: true // Search for objects (reference equality) const obj = { id: 1 }; const objects = new Map([ ['first', obj], ['second', { id: 2 }], ]); const hasObj = hasValue(objects, obj); // Result: true const hasSimilar = hasValue(objects, { id: 1 }); // Result: false (different reference) ``` #### Parameters * `map` (`Map`): The Map to search. * `searchElement` (`V`): The value to search for. #### Returns (`boolean`): true if the Map contains the value, false otherwise. --- --- url: /reference/array/head.md --- # head Returns the first element of an array. ```typescript const firstElement = head(arr); ``` ## Usage ### `head(arr)` Use `head` when you want to get the first element of an array. If the array is empty, it returns `undefined`. This is useful when accessing data at the beginning of an array. ```typescript import { head } from 'es-toolkit/array'; // Get the first element of a number array const numbers = [1, 2, 3, 4, 5]; head(numbers); // Returns: 1 // Get the first element of a string array const strings = ['a', 'b', 'c']; head(strings); // Returns: 'a' // Empty array returns undefined const emptyArray: number[] = []; head(emptyArray); // Returns: undefined ``` Type handling is safe. ```typescript import { head } from 'es-toolkit/array'; // For non-empty arrays, the type is certain const nonEmptyArray = [1, 2, 3] as const; head(nonEmptyArray); // Returns: 1 (type: 1) // For regular arrays, undefined is possible const maybeEmptyArray = [1, 2, 3]; head(maybeEmptyArray); // Returns: 1 | undefined (type: number | undefined) ``` #### Parameters * `arr` (`readonly T[]`): The array from which to get the first element. #### Returns (`T | undefined`): The first element of the array. Returns `undefined` if the array is empty. --- --- url: /reference/compat/array/head.md --- # head (Lodash Compatibility) ::: warning Use [`head`](../../array/head.md) from `es-toolkit` This `head` function operates slowly due to `ArrayLike` object processing and array conversion process. Instead, use the faster and more modern [`head`](../../array/head.md) from `es-toolkit`. ::: Returns the first element of an array. ```typescript const firstElement = head(array); ``` ## Usage ### `head(array)` Returns the first element of an array or array-like object. Returns `undefined` if the array is empty or invalid. ```typescript import { head } from 'es-toolkit/compat'; // First element of number array const numbers = [1, 2, 3, 4]; const first = head(numbers); // first is 1 // First element of string array const strings = ['a', 'b', 'c']; const firstChar = head(strings); // firstChar is 'a' // Array-like object const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; const firstItem = head(arrayLike); // firstItem is 'x' ``` Empty arrays or invalid inputs return `undefined`. ```typescript import { head } from 'es-toolkit/compat'; const emptyArray: number[] = []; const noElement = head(emptyArray); // noElement is undefined head(null); // undefined head(undefined); // undefined ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array or array-like object to get the first element from. #### Returns (`T | undefined`): Returns the first element of the array, or `undefined` if the array is empty or invalid. --- --- url: /reference/function/identity.md --- # identity Returns the input value as is. ```typescript const result = identity(value); ``` ## Usage ### `identity(value)` Use `identity` when you want to return a value without modifying it. This is useful as a default value for functions passed as arguments. It's commonly used to return the value itself in array `map` or `filter` operations, or as a placeholder in functional programming. ```typescript import { identity } from 'es-toolkit/function'; // Returns the number as is const num = identity(5); console.log(num); // 5 // Returns the string as is const str = identity('hello'); console.log(str); // 'hello' // Returns the object as is const obj = identity({ key: 'value' }); console.log(obj); // { key: 'value' } // Example using with an array const numbers = [1, 2, 3, 4, 5]; const same = numbers.map(identity); console.log(same); // [1, 2, 3, 4, 5] ``` #### Parameters * `value` (`T`): The value to return. #### Returns (`T`): Returns the input value as is. --- --- url: /reference/compat/function/identity.md --- # identity (Lodash Compatibility) ::: warning Use `es-toolkit`'s `identity` This `identity` function has the same functionality in the main `es-toolkit` library. It simply returns the input value as is. Instead, use the faster and more modern `es-toolkit`'s [identity](../../function/identity.md). ::: Returns the received value as is. ```typescript const result = identity(value); ``` ## Usage ### `identity(value)` Use `identity` when you want to return the received value as is. It's mainly used as a default value or placeholder function, and is frequently used in functional programming. ```typescript import { identity } from 'es-toolkit/compat'; // Basic usage console.log(identity(5)); // 5 console.log(identity('hello')); // 'hello' console.log(identity({ key: 'value' })); // { key: 'value' } // Use with array's map (value copy) const numbers = [1, 2, 3, 4, 5]; const copied = numbers.map(identity); console.log(copied); // [1, 2, 3, 4, 5] // Use as default value in filtering const values = [1, 0, '', 'hello', null, undefined, false, true]; const filtered = values.filter(identity); // Keep only truthy values console.log(filtered); // [1, 'hello', true] // Use as default transformation function function processData(data, transform = identity) { return transform(data); } console.log(processData('hello')); // 'hello' console.log(processData('hello', x => x.toUpperCase())); // 'HELLO' ``` In most cases, it can be replaced with a simpler arrow function `x => x`: ```typescript // Using arrow function instead of identity (recommended) const copied = numbers.map(x => x); const filtered = values.filter(x => x); ``` #### Parameters * `value` (`T`): The value to return. #### Returns (`T`): Returns the received value as is. --- --- url: /reference/compat/array/includes.md --- # includes (Lodash Compatibility) ::: warning Use `Array.prototype.includes` This `includes` function operates slowly due to object iteration and SameValueZero comparison processing. For arrays, JavaScript's native `Array.prototype.includes` method is faster and more standardized. Instead, use the faster and more modern `Array.prototype.includes`. ::: Checks if a specific value is included in an array, object, or string. ```typescript const hasValue = includes(collection, target, fromIndex); ``` ## Usage ### `includes(collection, target, fromIndex)` Use `includes` when you want to check if a specific value exists in an array, object, or string. It compares values using the SameValueZero method. ```typescript import { includes } from 'es-toolkit/compat'; // Find value in array includes([1, 2, 3], 2); // Returns: true // Find in object values includes({ a: 1, b: 'a', c: NaN }, 'a'); // Returns: true // Find substring in string includes('hello world', 'world'); // Returns: true ``` You can start searching from a specific index. ```typescript import { includes } from 'es-toolkit/compat'; // Search from index 2 includes([1, 2, 3, 2], 2, 2); // Returns: true (found at index 3) // Negative index counts from the end includes([1, 2, 3], 2, -2); // Returns: true ``` `null` or `undefined` always return `false`. ```typescript import { includes } from 'es-toolkit/compat'; includes(null, 1); // false includes(undefined, 1); // false ``` You can also search for substrings in strings. ```typescript import { includes } from 'es-toolkit/compat'; // Search from beginning includes('hello', 'e'); // Returns: true // Search from specific position includes('hello', 'e', 2); // Returns: false (no 'e' after index 2) ``` It can correctly find `NaN` values. ```typescript import { includes } from 'es-toolkit/compat'; includes([1, 2, NaN], NaN); // Returns: true includes({ a: 1, b: NaN }, NaN); // Returns: true ``` #### Parameters * `collection` (`Array | Record | string | null | undefined`): The array, object, or string to search. * `target` (`any`): The value to find. * `fromIndex` (`number`, optional): The index to start searching from. Negative values count from the end. Default is `0`. #### Returns (`boolean`): Returns `true` if the value exists, `false` otherwise. --- --- url: /reference/compat/array/indexOf.md --- # indexOf (Lodash Compatibility) ::: warning Use `Array.prototype.indexOf` or `Array.prototype.findIndex` This `indexOf` function operates slowly due to additional logic for handling `NaN`. If you're not looking for `NaN`, use the faster `Array.prototype.indexOf`. To find `NaN`, use `Array.prototype.findIndex` with `Number.isNaN`. ::: Finds the index of the first occurrence of a given element in an array. ```typescript const index = indexOf(array, searchElement, fromIndex); ``` ## Usage ### `indexOf(array, searchElement, fromIndex?)` Works almost the same as `Array.prototype.indexOf`, but can find `NaN` values. Use this when you need to find the position of a specific value in an array. ```typescript import { indexOf } from 'es-toolkit/compat'; // Find element in number array const array = [1, 2, 3, 4]; indexOf(array, 3); // => 2 // Find NaN value (Array.prototype.indexOf cannot find it) const arrayWithNaN = [1, 2, NaN, 4]; indexOf(arrayWithNaN, NaN); // => 2 ``` You can start searching from a specific index. ```typescript import { indexOf } from 'es-toolkit/compat'; const array = [1, 2, 3, 1, 2, 3]; indexOf(array, 2, 2); // => 4 (start searching from index 2) ``` `null` or `undefined` are treated as empty arrays. ```typescript import { indexOf } from 'es-toolkit/compat'; indexOf(null, 1); // => -1 indexOf(undefined, 1); // => -1 ``` #### Parameters * `array` (`T[]`): The array to search. ::: info `array` can be `ArrayLike`, `null`, or `undefined` To ensure full compatibility with lodash, the `indexOf` function handles `array` as follows: * If `array` is `ArrayLike`, it uses `Array.from(...)` to convert it to an array. * If `array` is `null` or `undefined`, it's treated as an empty array. ::: * `searchElement` (`T`): The value to find. * `fromIndex` (`number`, optional): The index to start searching from. If negative, it's calculated from the end of the array. Defaults to `0`. #### Returns (`number`): Returns the index of the first element in the array that matches the given value. Returns `-1` if no matching element is found. --- --- url: /reference/array/initial.md --- # initial Returns a new array containing all elements except the last one. ```typescript const result = initial(arr); ``` ## Usage ### `initial(arr)` Use `initial` when you want to get all elements except the last one from an array. If the array is empty or has only one element, it returns an empty array. This is useful when processing while excluding the end of the array. ```typescript import { initial } from 'es-toolkit/array'; // Exclude the last element from a number array const numbers = [1, 2, 3, 4, 5]; initial(numbers); // Returns: [1, 2, 3, 4] // Exclude the last element from a string array const strings = ['a', 'b', 'c']; initial(strings); // Returns: ['a', 'b'] // An array with only one element returns an empty array const single = [42]; initial(single); // Returns: [] ``` It safely handles empty arrays and special cases. ```typescript import { initial } from 'es-toolkit/array'; // An empty array returns an empty array const empty: number[] = []; initial(empty); // Returns: [] // It can also handle nested arrays const nested = [ [1, 2], [3, 4], [5, 6], ]; initial(nested); // Returns: [[1, 2], [3, 4]] ``` #### Parameters * `arr` (`readonly T[]`): The array from which to exclude the last element. #### Returns (`T[]`): Returns a new array excluding the last element. If the input array is empty or has only one element, it returns an empty array. --- --- url: /reference/compat/array/initial.md --- # initial (Lodash Compatibility) ::: warning Use [`initial`](../../array/initial.md) from `es-toolkit` This `initial` function operates slowly due to `ArrayLike` object processing and array conversion process. Instead, use the faster and more modern [`initial`](../../array/initial.md) from `es-toolkit`. ::: Returns a new array with all elements except the last one from an array. ```typescript const result = initial(array); ``` ## Usage ### `initial(array)` Returns a new array containing all elements except the last one from an array or array-like object. Returns an empty array if the array is empty or has only one element. ```typescript import { initial } from 'es-toolkit/compat'; // Exclude last element from number array const numbers = [1, 2, 3, 4]; const result = initial(numbers); // result is [1, 2, 3] // Exclude last element from string array const strings = ['a', 'b', 'c', 'd']; const withoutLast = initial(strings); // withoutLast is ['a', 'b', 'c'] // Array-like object const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; const items = initial(arrayLike); // items is ['x', 'y'] ``` Empty arrays or invalid inputs return an empty array. ```typescript import { initial } from 'es-toolkit/compat'; const emptyArray: number[] = []; const result = initial(emptyArray); // result is [] const singleItem = [42]; const onlyOne = initial(singleItem); // onlyOne is [] initial(null); // [] initial(undefined); // [] ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array or array-like object to exclude the last element from. #### Returns (`T[]`): Returns a new array with the last element excluded. --- --- url: /reference/math/inRange.md --- # inRange Checks if a value is within a specified range. ```typescript const result = inRange(value, maximum); const result = inRange(value, minimum, maximum); ``` ## Usage ### `inRange(value, maximum)` Use `inRange` when you want to check if a value is within the range from 0 to less than the maximum value. The minimum value is automatically set to 0. ```typescript import { inRange } from 'es-toolkit/math'; // Check within the range from 0 to less than 5 const result1 = inRange(3, 5); // result1 is true (0 <= 3 < 5) const result2 = inRange(5, 5); // result2 is false (5 is not less than 5) const result3 = inRange(-1, 5); // result3 is false (-1 < 0) ``` #### Parameters * `value` (`number`): The value to check. * `maximum` (`number`): The maximum value of the range (exclusive). #### Returns (`boolean`): Returns `true` if the value is within the range from 0 (inclusive) to the maximum value (exclusive), otherwise `false`. ### `inRange(value, minimum, maximum)` Use `inRange` when you want to check if a value is within a specified minimum and maximum range. ```typescript import { inRange } from 'es-toolkit/math'; // Check within the minimum and maximum range const result1 = inRange(3, 2, 5); // result1 is true (2 <= 3 < 5) const result2 = inRange(1, 2, 5); // result2 is false (1 < 2) const result3 = inRange(5, 2, 5); // result3 is false (5 is not less than 5) // Can be used with negative ranges const result4 = inRange(-3, -5, -1); // result4 is true (-5 <= -3 < -1) ``` #### Parameters * `value` (`number`): The value to check. * `minimum` (`number`): The minimum value of the range (inclusive). * `maximum` (`number`): The maximum value of the range (exclusive). #### Returns (`boolean`): Returns `true` if the value is within the specified range, otherwise `false`. #### Throws Throws an error if the minimum is greater than or equal to the maximum. --- --- url: /reference/compat/math/inRange.md --- # inRange (Lodash Compatibility) ::: warning Use [inRange](../../math/inRange.md) from `es-toolkit` This `inRange` function works slowly due to complex type conversion and null/undefined handling. Use the faster and more modern [inRange](../../math/inRange.md) from `es-toolkit` instead. ::: Checks if a number is within a specified range. ```typescript const result = inRange(value, minimum, maximum); ``` ## Usage ### `inRange(value, minimum, maximum?)` Use `inRange` when you want to check if a number is within a specific range. The minimum value is inclusive and the maximum value is exclusive. ```typescript import { inRange } from 'es-toolkit/compat'; // Basic usage inRange(3, 2, 4); // Returns: true (2 ≤ 3 < 4) inRange(1, 2, 5); // Returns: false (1 < 2) inRange(5, 2, 5); // Returns: false (5 is not included) // Range boundary values inRange(2, 2, 4); // Returns: true (minimum value is included) inRange(4, 2, 4); // Returns: false (maximum value is not included) ``` ### `inRange(value, maximum)` When only two arguments are provided, it treats the range as from 0 to maximum. ```typescript import { inRange } from 'es-toolkit/compat'; inRange(3, 5); // Returns: true (0 ≤ 3 < 5) inRange(-1, 5); // Returns: false (-1 < 0) inRange(0, 5); // Returns: true (0 ≤ 0 < 5) inRange(5, 5); // Returns: false (5 is not included) ``` If the minimum value is greater than the maximum value, they are automatically swapped. ```typescript import { inRange } from 'es-toolkit/compat'; inRange(3, 5, 2); // Returns: true (range becomes 2~5, and 2 ≤ 3 < 5) inRange(1, 5, 2); // Returns: false (1 < 2) ``` Invalid values are appropriately converted. ```typescript import { inRange } from 'es-toolkit/compat'; // String number conversion inRange(3, '2', '4'); // Returns: true // Falsy values are treated as 0 inRange(1, null, 5); // Returns: true (null is treated as 0, so range is 0~5) inRange(3, false, 5); // Returns: true (false is treated as 0) ``` #### Parameters * `value` (`number`): The number to check if it's within the range. * `minimum` (`number`): The minimum value of the range (inclusive). If `maximum` is not provided, this value becomes the maximum. * `maximum` (`number`, optional): The maximum value of the range (exclusive). #### Returns (`boolean`): Returns `true` if the value is within the specified range, otherwise `false`. --- --- url: /usage.md description: How to use es-toolkit --- # Installation & Usage es-toolkit is available via [npm](https://npmjs.com/package/es-toolkit) for Node.js and Bun, and through [JSR](https://jsr.io/@es-toolkit/es-toolkit) for Deno. You can also use es-toolkit in browsers by [importing them in CDNs](#browsers). ## Node.js es-toolkit supports Node.js 18 or later. Install es-toolkit with the following command: ::: code-group ```sh [npm] npm install es-toolkit ``` ```sh [pnpm] pnpm add es-toolkit ``` ```sh [yarn] yarn add es-toolkit ``` ::: To use a function from es-toolkit, simply import it and use as shown below. ```typescript import { sum } from 'es-toolkit'; sum([1, 2, 3]); ``` ## Deno es-toolkit is also available via [JSR](https://jsr.io/@es-toolkit/es-toolkit) for Deno. To install es-toolkit, use the following command: ```sh deno add jsr:@es-toolkit/es-toolkit ``` Note that the package name includes an additional scope, distinct from npm, as per JSR restrictions. ```typescript import { sum } from '@es-toolkit/es-toolkit'; sum([1, 2, 3]); ``` ## Bun es-toolkit is also available on Bun. You can install it via the following command: ```sh bun add es-toolkit ``` ## Browsers You can find es-toolkit on CDNs such as [jsdelivr](https://www.jsdelivr.com), [unpkg](https://unpkg.com). We define `_` to include all functions, similar to Lodash. ::: code-group ```html [jsdelivr] ``` ```html [unpkg] ``` ::: es-toolkit is also available on [esm.sh](https://esm.sh) for modern browsers. ::: code-group ```html [esm.sh] ``` ::: --- --- url: /reference/array/intersection.md --- # intersection Returns a new array containing elements that are commonly included in both arrays. ```typescript const result = intersection(firstArr, secondArr); ``` ## Usage ### `intersection(firstArr, secondArr)` Use `intersection` when you want to find only common elements in two arrays. It returns a new array containing only elements from the first array that also exist in the second array. This is useful for finding the intersection of two data sets. ```typescript import { intersection } from 'es-toolkit/array'; // Find the intersection of number arrays const numbers1 = [1, 2, 3, 4, 5]; const numbers2 = [3, 4, 5, 6, 7]; intersection(numbers1, numbers2); // Returns: [3, 4, 5] // Find the intersection of string arrays const strings1 = ['apple', 'banana', 'cherry']; const strings2 = ['banana', 'cherry', 'date']; intersection(strings1, strings2); // Returns: ['banana', 'cherry'] ``` It also handles cases with no intersection or special cases. ```typescript import { intersection } from 'es-toolkit/array'; // Returns an empty array when there's no intersection const noCommon1 = [1, 2, 3]; const noCommon2 = [4, 5, 6]; intersection(noCommon1, noCommon2); // Returns: [] // Also returns an empty array when one side is empty const numbers = [1, 2, 3]; const empty: number[] = []; intersection(numbers, empty); // Returns: [] ``` #### Parameters * `firstArr` (`readonly T[]`): The first array to compare. * `secondArr` (`readonly T[]`): The second array to compare. #### Returns (`T[]`): Returns a new array containing elements commonly included in both arrays. --- --- url: /reference/compat/array/intersection.md --- # intersection (Lodash Compatibility) ::: warning Use [`intersection`](../../array/intersection.md) from `es-toolkit` This `intersection` function operates slowly due to handling `null` or `undefined`, multiple array support, and duplicate removal process. Instead, use the faster and more modern [`intersection`](../../array/intersection.md) from `es-toolkit`. ::: Finds the intersection of multiple arrays. ```typescript const result = intersection(...arrays); ``` ## Usage ### `intersection(...arrays)` Finds elements that exist in all arrays and returns them as a new array. The result is deduplicated and maintains the order of the first array. ```typescript import { intersection } from 'es-toolkit/compat'; // Intersection of two arrays const array1 = [1, 2, 3, 4]; const array2 = [2, 3, 5, 6]; const result = intersection(array1, array2); // result is [2, 3] // Intersection of three arrays const array3 = [3, 4, 7, 8]; const multiResult = intersection(array1, array2, array3); // multiResult is [3] // String arrays const strings1 = ['a', 'b', 'c']; const strings2 = ['b', 'c', 'd']; const stringResult = intersection(strings1, strings2); // stringResult is ['b', 'c'] // Array-like objects const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; const arrayLike2 = { 0: 2, 1: 3, 2: 4, length: 3 }; const likeResult = intersection(arrayLike1, arrayLike2); // likeResult is [2, 3] ``` `null` or `undefined` arrays are treated as empty arrays. ```typescript import { intersection } from 'es-toolkit/compat'; const array1 = [1, 2, 3]; const result1 = intersection(array1, null); // result1 is [] const result2 = intersection(null, undefined); // result2 is [] ``` Duplicate elements are removed from the result. ```typescript import { intersection } from 'es-toolkit/compat'; const array1 = [1, 1, 2, 3]; const array2 = [1, 2, 2, 4]; const result = intersection(array1, array2); // result is [1, 2] (duplicates removed) ``` #### Parameters * `...arrays` (`Array | null | undefined>`): The arrays to find the intersection of. Array-like objects, null, or undefined are also allowed. #### Returns (`T[]`): Returns a new array of elements that exist in all arrays. Duplicates are removed and the order follows the first array. --- --- url: /reference/array/intersectionBy.md --- # intersectionBy Returns a new array containing the intersection of two arrays based on the result of a transformation function. ```typescript const result = intersectionBy(firstArr, secondArr, mapper); ``` ## Usage ### `intersectionBy(firstArr, secondArr, mapper)` Use `intersectionBy` when you want to find common elements in two arrays based on a specific attribute or transformed value. It compares the results of processing each element with a transformation function to find the intersection. This is useful when comparing by a specific property in object arrays or when complex transformation logic is needed. ```typescript import { intersectionBy } from 'es-toolkit/array'; // Find intersection based on object's id property const users1 = [ { id: 1, name: 'john' }, { id: 2, name: 'jane' }, { id: 3, name: 'bob' }, ]; const users2 = [ { id: 2, name: 'jane' }, { id: 4, name: 'alice' }, ]; intersectionBy(users1, users2, user => user.id); // Returns: [{ id: 2, name: 'jane' }] // Can also compare arrays of different types const objects = [ { id: 1, name: 'apple' }, { id: 2, name: 'banana' }, ]; const ids = [2, 3, 4]; intersectionBy(objects, ids, item => (typeof item === 'object' ? item.id : item)); // Returns: [{ id: 2, name: 'banana' }] ``` Complex transformation logic can also be applied. ```typescript import { intersectionBy } from 'es-toolkit/array'; // Compare strings after converting to lowercase const words1 = ['Apple', 'Banana', 'Cherry']; const words2 = ['apple', 'DATE', 'elderberry']; intersectionBy(words1, words2, word => word.toLowerCase()); // Returns: ['Apple'] // Compare numbers after converting to absolute value const numbers1 = [1, -2, 3, -4]; const numbers2 = [2, -3, 4, 5]; intersectionBy(numbers1, numbers2, num => Math.abs(num)); // Returns: [-2, 3, -4] ``` #### Parameters * `firstArr` (`readonly T[]`): The first array to compare. * `secondArr` (`readonly U[]`): The second array to compare. * `mapper` (`(item: T | U) => unknown`): A function that transforms each element to create comparison criteria. #### Returns (`T[]`): Returns a new array containing elements commonly included in both arrays based on the result of the transformation function. The result consists of elements from the first array. --- --- url: /reference/compat/array/intersectionBy.md --- # intersectionBy (Lodash Compatibility) ::: warning Use [`intersectionBy`](../../array/intersectionBy.md) from `es-toolkit` This `intersectionBy` function operates slowly due to complex condition processing, multiple array support, property path parsing, etc. Instead, use the faster and more modern [`intersectionBy`](../../array/intersectionBy.md) from `es-toolkit`. ::: Finds the intersection of multiple arrays using a given condition function. ```typescript const result = intersectionBy(...arrays, iteratee); ``` ## Usage ### `intersectionBy(...arrays, iteratee)` Finds the intersection of multiple arrays based on values transformed by a given condition function. The condition can be provided in various forms such as a function, property name, partial object, etc. ```typescript import { intersectionBy } from 'es-toolkit/compat'; // Intersection by function const array1 = [2.1, 1.2]; const array2 = [2.3, 3.4]; const result = intersectionBy(array1, array2, Math.floor); // result is [2.1] (2 is common based on Math.floor) // Intersection by property const users1 = [ { id: 1, name: 'john' }, { id: 2, name: 'jane' }, ]; const users2 = [ { id: 2, name: 'jane' }, { id: 3, name: 'bob' }, ]; const byId = intersectionBy(users1, users2, 'id'); // byId is [{ id: 2, name: 'jane' }] // Intersection of three arrays const array3 = [2.5, 4.1]; const multiResult = intersectionBy(array1, array2, array3, Math.floor); // multiResult is [2.1] // Array-like objects const arrayLike1 = { 0: { x: 1 }, 1: { x: 2 }, length: 2 }; const arrayLike2 = { 0: { x: 2 }, 1: { x: 3 }, length: 2 }; const byProperty = intersectionBy(arrayLike1, arrayLike2, 'x'); // byProperty is [{ x: 2 }] ``` `null` or `undefined` arrays are treated as empty arrays. ```typescript import { intersectionBy } from 'es-toolkit/compat'; const array1 = [{ x: 1 }, { x: 2 }]; const result = intersectionBy(array1, null, 'x'); // result is [] ``` You can also specify conditions with partial objects or property-value pairs. ```typescript import { intersectionBy } from 'es-toolkit/compat'; const products1 = [ { category: 'fruit', name: 'apple' }, { category: 'vegetable', name: 'carrot' }, ]; const products2 = [ { category: 'fruit', name: 'banana' }, { category: 'meat', name: 'beef' }, ]; // Specify condition with partial object const byCategory = intersectionBy(products1, products2, { category: 'fruit' }); // Specify condition with property-value pair const byCategoryPair = intersectionBy(products1, products2, ['category', 'fruit']); ``` #### Parameters * `...arrays` (`Array | null | undefined>`): The arrays to find the intersection of. * `iteratee` (`Function | PropertyKey | Array | Object`): The condition to transform each element. Can be a function, property name, property-value pair, or partial object. #### Returns (`T[]`): Returns a new array of elements that exist in all arrays based on the transformed values. --- --- url: /reference/array/intersectionWith.md --- # intersectionWith Returns a new array containing the intersection of two arrays based on a custom comparison function. ```typescript const result = intersectionWith(firstArr, secondArr, areItemsEqual); ``` ## Usage ### `intersectionWith(firstArr, secondArr, areItemsEqual)` Use `intersectionWith` when you want to find common elements in two arrays using a user-defined comparison function. This is useful for complex objects that are difficult to handle with simple value comparisons or when special comparison logic is needed. ```typescript import { intersectionWith } from 'es-toolkit/array'; // Compare by object's id property const users1 = [ { id: 1, name: 'john' }, { id: 2, name: 'jane' }, ]; const users2 = [ { id: 2, name: 'jane' }, { id: 3, name: 'bob' }, ]; intersectionWith(users1, users2, (a, b) => a.id === b.id); // Returns: [{ id: 2, name: 'jane' }] // Can also compare different types const objects = [ { id: 1, name: 'apple' }, { id: 2, name: 'banana' }, ]; const ids = [2, 3]; intersectionWith(objects, ids, (obj, id) => obj.id === id); // Returns: [{ id: 2, name: 'banana' }] ``` Complex comparison logic can also be implemented. ```typescript import { intersectionWith } from 'es-toolkit/array'; // Case-insensitive string comparison const words1 = ['Apple', 'Banana']; const words2 = ['apple', 'cherry']; intersectionWith(words1, words2, (a, b) => a.toLowerCase() === b.toLowerCase()); // Returns: ['Apple'] // Number comparison within a range const numbers1 = [1.1, 2.3, 3.7]; const numbers2 = [1.0, 2.5, 4.0]; intersectionWith(numbers1, numbers2, (a, b) => Math.abs(a - b) < 0.5); // Returns: [1.1] (difference between 1.1 and 1.0 is less than 0.5) ``` #### Parameters * `firstArr` (`readonly T[]`): The first array to compare. * `secondArr` (`readonly U[]`): The second array to compare. * `areItemsEqual` (`(x: T, y: U) => boolean`): A function to determine if two elements are equal. Should return `true` if equal, `false` otherwise. #### Returns (`T[]`): Returns a new array containing elements commonly included in both arrays based on the custom comparison function. The result consists of elements from the first array. --- --- url: /reference/compat/array/intersectionWith.md --- # intersectionWith (Lodash Compatibility) ::: warning Use [`intersectionWith`](../../array/intersectionWith.md) from `es-toolkit` This `intersectionWith` function operates slowly due to handling `null` or `undefined`, support for various overloads, etc. Instead, use the faster and more modern [`intersectionWith`](../../array/intersectionWith.md) from `es-toolkit`. ::: Creates an array of common elements found in all arrays using a custom comparison function. ```typescript const result = intersectionWith(array, ...otherArrays, comparator); ``` ## Usage ### `intersectionWith(array, ...otherArrays, comparator)` Finds the intersection of the first array with the rest using a custom comparison function. The comparison function determines if elements are equal, and only elements found in all arrays are returned. ```typescript import { intersectionWith } from 'es-toolkit/compat'; const objects = [ { id: 1, name: 'john' }, { id: 2, name: 'jane' }, ]; const others = [ { id: 1, name: 'john' }, { id: 3, name: 'joe' }, ]; intersectionWith(objects, others, (a, b) => a.id === b.id); // => [{ id: 1, name: 'john' }] // You can compare with multiple arrays const array1 = [{ x: 1 }, { x: 2 }]; const array2 = [{ x: 1 }, { x: 3 }]; const array3 = [{ x: 1 }, { x: 4 }]; intersectionWith(array1, array2, array3, (a, b) => a.x === b.x); // => [{ x: 1 }] ``` `null` or `undefined` are treated as empty arrays. ```typescript import { intersectionWith } from 'es-toolkit/compat'; intersectionWith(null, [1, 2], (a, b) => a === b); // [] intersectionWith([1, 2], undefined, (a, b) => a === b); // [] ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The first array to compare. * `...otherArrays` (`Array | ((a: T, b: T | U) => boolean)>`): The other arrays to compare and the comparison function as the last element. * `comparator` (`(a: T, b: T | U) => boolean`): The function to determine if two elements are equal. #### Returns (`T[]`): Returns a new array of elements commonly found in all arrays. --- --- url: /reference/util/invariant.md --- # invariant Asserts that a given condition is true. If the condition is false, it throws an error. ```typescript invariant(condition, message); ``` ## Usage ### `invariant(condition, message)` Use `invariant` when a specific condition must be satisfied in your code. If the condition is false, it immediately throws an error to stop program execution. ```typescript import { invariant } from 'es-toolkit/util'; // If the condition is true, nothing happens invariant(true, 'This message will not appear'); // If the condition is false, it throws an error invariant(false, 'This condition is false'); // Error: This condition is false // When checking that a value is not null or undefined const value = getValue(); invariant(value !== null && value !== undefined, 'Value must not be null or undefined'); // Now you can be sure that value is neither null nor undefined // When checking if a number is positive const number = getNumber(); invariant(number > 0, 'Number must be positive'); ``` You can also pass an error object directly. ```typescript import { invariant } from 'es-toolkit/util'; // Passing an Error object invariant(false, new Error('Custom error message')); // Using a custom error class class ValidationError extends Error { constructor(message: string) { super(message); this.name = 'ValidationError'; } } invariant(false, new ValidationError('Validation failed')); ``` It is particularly useful for validating code assumptions during development or ensuring that function inputs are within expected ranges. #### Parameters * `condition` (`unknown`): The condition to evaluate. If it evaluates to a falsy value, an error is thrown. * `message` (`string | Error`): The error message or error object to throw when the condition is false. #### Returns (`void`): Returns nothing if the condition is true. #### Errors Throws the provided message or error object if the condition evaluates to false. --- --- url: /reference/object/invert.md --- # invert Creates a new object with keys and values swapped. ```typescript const inverted = invert(obj); ``` ## Usage ### `invert(obj)` Use `invert` when you want to create a new object with keys and values swapped. The keys of the original object become the values of the new object, and the values of the original object become the keys of the new object. If there are duplicate values, the key that appears later will be used. ```typescript import { invert } from 'es-toolkit/object'; // Basic usage const original = { a: 1, b: 2, c: 3 }; const inverted = invert(original); console.log(inverted); // { 1: 'a', 2: 'b', 3: 'c' } // When there are duplicate values const withDuplicates = { a: 1, b: 1, c: 2 }; const result = invert(withDuplicates); console.log(result); // { 1: 'b', 2: 'c' } (later appearing 'b' is used as the value for key 1) // String keys and number values const grades = { alice: 85, bob: 92, charlie: 88 }; const invertedGrades = invert(grades); console.log(invertedGrades); // { 85: 'alice', 92: 'bob', 88: 'charlie' } ``` Can be used with various types of keys and values. ```typescript // Number keys and string values const statusCodes = { 200: 'OK', 404: 'Not Found', 500: 'Internal Server Error' }; const invertedCodes = invert(statusCodes); console.log(invertedCodes); // { 'OK': '200', 'Not Found': '404', 'Internal Server Error': '500' } // Useful when reverse lookup is needed const userRoles = { admin: 'administrator', user: 'regular_user', guest: 'visitor' }; const roleToKey = invert(userRoles); console.log(roleToKey); // { 'administrator': 'admin', 'regular_user': 'user', 'visitor': 'guest' } // Now you can find keys by values function findRoleKey(roleName: string) { return roleToKey[roleName]; } console.log(findRoleKey('administrator')); // 'admin' ``` Useful when used with enums or constant objects. ```typescript // Color code mapping const colorCodes = { red: '#FF0000', green: '#00FF00', blue: '#0000FF', }; const codeToColor = invert(colorCodes); console.log(codeToColor); // { '#FF0000': 'red', '#00FF00': 'green', '#0000FF': 'blue' } // Now you can find color names by color codes function getColorName(code: string) { return codeToColor[code] || 'unknown'; } console.log(getColorName('#FF0000')); // 'red' ``` #### Parameters * `obj` (`Record`): The object to swap keys and values. Both keys and values must be strings, numbers, or symbols. #### Returns (`Record`): A new object with the keys and values of the original object swapped. --- --- url: /reference/compat/object/invert.md --- # invert (Lodash compatibility) ::: warning Use `invert` from `es-toolkit` This `invert` function operates slower due to the complex processing required for Lodash compatibility. Instead, use the faster and more modern [`invert`](../../object/invert.md) from `es-toolkit`. ::: Inverts the keys and values of an object. ```typescript const inverted = invert(object); ``` ## Usage ### `invert(object)` Use `invert` when you want to swap the keys and values of an object. The original object's keys become the values in the new object, and the original object's values become the keys in the new object. ```typescript import { invert } from 'es-toolkit/compat'; // Basic key-value inversion const object = { a: 1, b: 2, c: 3 }; invert(object); // => { '1': 'a', '2': 'b', '3': 'c' } // Inverting string values const colors = { red: '#ff0000', green: '#00ff00', blue: '#0000ff' }; invert(colors); // => { '#ff0000': 'red', '#00ff00': 'green', '#0000ff': 'blue' } // Mixed key and value types const mixed = { a: 1, 2: 'b', c: 3, 4: 'd' }; invert(mixed); // => { '1': 'a', 'b': '2', '3': 'c', 'd': '4' } ``` When there are duplicate values, the last key is used. ```typescript import { invert } from 'es-toolkit/compat'; // Case with duplicate values const object = { a: 1, b: 1, c: 2 }; invert(object); // => { '1': 'b', '2': 'c' } // 'a' is overwritten and lost ``` #### Parameters * `object` (`object`): The object to invert. #### Returns (`Record`): Returns a new object with keys and values inverted. --- --- url: /reference/compat/object/invertBy.md --- # invertBy (Lodash compatibility) ::: warning Use modern JavaScript APIs This `invertBy` function operates slowly due to complex iterator processing and grouping logic. Instead, use the faster and more modern `Object.entries()` with `reduce()` or `Map`. ::: Inverts the keys and values of an object while grouping identical values into arrays. ```typescript const inverted = invertBy(object, iteratee); ``` ## Usage ### `invertBy(object, iteratee?)` Use `invertBy` when you want to invert the keys and values of an object and group keys with the same value into arrays. You can optionally provide an iteratee function to transform the values. ```typescript import { invertBy } from 'es-toolkit/compat'; // Basic key-value inversion (identical values are grouped into arrays) const object = { a: 1, b: 2, c: 1 }; invertBy(object); // => { '1': ['a', 'c'], '2': ['b'] } // Value transformation using iteratee function const ages = { john: 25, jane: 30, bob: 25 }; invertBy(ages, age => `age_${age}`); // => { 'age_25': ['john', 'bob'], 'age_30': ['jane'] } // Grouping by string length const words = { a: 'hello', b: 'world', c: 'hi', d: 'test' }; invertBy(words, word => word.length); // => { '5': ['a', 'b'], '2': ['c'], '4': ['d'] } ``` You can also group by object properties. ```typescript import { invertBy } from 'es-toolkit/compat'; // Grouping by object property const users = { user1: { department: 'IT', age: 30 }, user2: { department: 'HR', age: 25 }, user3: { department: 'IT', age: 35 }, }; invertBy(users, user => user.department); // => { 'IT': ['user1', 'user3'], 'HR': ['user2'] } ``` Safely handles `null` or `undefined`. ```typescript import { invertBy } from 'es-toolkit/compat'; invertBy(null); // => {} invertBy(undefined); // => {} ``` #### Parameters * `object` (`object`): The object to invert. * `iteratee` (`ValueIteratee`, optional): The function to transform values. Defaults to a function that uses the value as-is. #### Returns (`Record`): Returns a new object with transformed values as keys and arrays of original keys as values. --- --- url: /reference/compat/util/invoke.md --- # invoke (Lodash Compatibility) ::: warning Call methods directly This `invoke` function performs slower due to complex processing like path resolution, object traversal, and `get` function calls. Instead, use faster and more modern direct method calls. ::: Invokes the method at the path of the object with the given arguments. ```typescript const result = invoke(object, path, args); ``` ## Usage ### `invoke(object, path, args)` Use `invoke` when you want to call a method at a specific path of an object with arguments. The path can be specified as a dot notation string or an array of property keys. ```typescript import { invoke } from 'es-toolkit/compat'; const object = { a: { b: function (x, y) { return x + y; }, }, }; // Specify path using dot notation invoke(object, 'a.b', [1, 2]); // Returns: 3 // Specify path using array invoke(object, ['a', 'b'], [1, 2]); // Returns: 3 // Non-existent path invoke(object, 'a.c.d', [1, 2]); // Returns: undefined // Various types of arguments const obj = { calculate: { sum: function (...numbers) { return numbers.reduce((a, b) => a + b, 0); }, multiply: function (a, b) { return a * b; }, }, }; invoke(obj, 'calculate.sum', [1, 2, 3, 4]); // Returns: 10 invoke(obj, ['calculate', 'multiply'], [5, 6]); // Returns: 30 ``` #### Parameters * `object` (`unknown`): The object to invoke the method on. * `path` (`PropertyKey | PropertyKey[]`): The path of the method to invoke. Can be a string, symbol, number, or an array of these. * `args` (`any[]`): The array of arguments to invoke the method with. #### Returns (`any`): Returns the result of the invoked method. If the method doesn't exist, returns `undefined`. --- --- url: /reference/compat/array/invokeMap.md --- # invokeMap (Lodash Compatibility) ::: warning Use `Array.map` and `Object.values(...).map` This `invokeMap` function is slow due to handling `null` or `undefined`, method lookups, etc. Use the faster and more modern `Array.map` and `Object.values(...).map` instead. For example, `invokeMap([1, 2, 3], 'toString')` can be written as `[1, 2, 3].map(x => x.toString())`. ::: Invokes the specified method on each element in the array or object and returns an array of results. ```typescript const result = invokeMap(collection, method, ...args); ``` ## Usage ### `invokeMap(collection, method, ...args)` Invokes the specified method on each element in the array or object. You can pass the method name as a string or pass a function directly. Additional arguments are passed to each method invocation. ```typescript import { invokeMap } from 'es-toolkit/compat'; // Invoke method on each element of the array invokeMap( [ [5, 1, 7], [3, 2, 1], ], 'sort' ); // => [[5, 1, 7].sort(), [3, 2, 1].sort()] // => [[1, 5, 7], [1, 2, 3]] // Invoke method with arguments invokeMap([123, 456], 'toString', 2); // => [(123).toString(2), (456).toString(2)] // => ['1111011', '111001000'] // Pass a function directly invokeMap(['a', 'b', 'c'], String.prototype.toUpperCase); // => [String.prototype.toUpperCase('a'), String.prototype.toUpperCase('b'), String.prototype.toUpperCase('c')] // => ['A', 'B', 'C'] ``` For objects, the method is invoked on each value. ```typescript import { invokeMap } from 'es-toolkit/compat'; const obj = { a: 1.1, b: 2.2, c: 3.3 }; invokeMap(obj, 'toFixed', 1); // => ['1.1', '2.2', '3.3'] ``` `null` or `undefined` are treated as empty arrays. ```typescript import { invokeMap } from 'es-toolkit/compat'; invokeMap(null, 'toString'); // [] invokeMap(undefined, 'toString'); // [] ``` #### Parameters * `collection` (`ArrayLike | Record | null | undefined`): The array or object to invoke the method on. * `method` (`string | ((...args: any[]) => R)`): The method name or function to invoke. * `...args` (`any[]`): Additional arguments to pass to each method invocation. #### Returns (`Array`): Returns a new array containing the results of each method invocation. --- --- url: /reference/compat/predicate/isArguments.md --- # isArguments (Lodash Compatibility) Checks if a value is an arguments object. ```typescript const result = isArguments(value); ``` ## Usage ### `isArguments(value)` Use `isArguments` when you need to check if a given value is a function's arguments object. This function also works as a type guard in TypeScript, narrowing the type of the value to `IArguments`. ```typescript import { isArguments } from 'es-toolkit/compat'; // In regular functions function normalFunction() { return isArguments(arguments); // true } // In strict mode function strictFunction() { 'use strict'; return isArguments(arguments); // true } // Non-arguments values isArguments([1, 2, 3]); // false isArguments({ 0: 'a', 1: 'b', length: 2 }); // false isArguments(null); // false isArguments(undefined); // false // Practical usage example function example() { if (isArguments(arguments)) { console.log('This is an arguments object'); console.log('Length:', arguments.length); } } ``` #### Parameters * `value` (`any`): The value to check. #### Returns (`boolean`): Returns `true` if the value is an arguments object, otherwise `false`. --- --- url: /reference/compat/predicate/isArray.md --- # isArray (Lodash Compatibility) ::: warning Use `Array.isArray` This `isArray` function operates slowly due to additional function calls. Instead, use the faster and modern `Array.isArray`. ::: Checks if a value is an array. ```typescript const result = isArray(value); ``` ## Usage ### `isArray(value)` Use `isArray` when you want to check if a value is an array. This function also works as a type guard in TypeScript. ```typescript import { isArray } from 'es-toolkit/compat'; // Array check isArray([1, 2, 3]); // Returns: true isArray('abc'); // Returns: false isArray(() => {}); // Returns: false // Distinguish from objects isArray({ 0: 'a', 1: 'b', length: 2 }); // Returns: false isArray(null); // Returns: false ``` #### Parameters * `value` (`unknown`): The value to check if it's an array. #### Returns (`value is any[]`): Returns `true` if the value is an array, otherwise `false`. --- --- url: /reference/predicate/isArrayBuffer.md --- # isArrayBuffer Checks if a value is an `ArrayBuffer` instance. ```typescript const result = isArrayBuffer(value); ``` ## Usage ### `isArrayBuffer(value)` Use `isArrayBuffer` when you want to check if a value is an `ArrayBuffer`. It can also be used as a type guard in TypeScript. ```typescript import { isArrayBuffer } from 'es-toolkit/predicate'; // Checking ArrayBuffer instances const buffer = new ArrayBuffer(16); const notBuffer = new Array(16); console.log(isArrayBuffer(buffer)); // true console.log(isArrayBuffer(notBuffer)); // false // Useful when processing binary data const data: unknown = getDataFromAPI(); if (isArrayBuffer(data)) { // In TypeScript, data is narrowed to ArrayBuffer const uint8View = new Uint8Array(data); console.log(`Buffer size: ${data.byteLength} bytes`); } // Comparison with various types console.log(isArrayBuffer(new ArrayBuffer(8))); // true console.log(isArrayBuffer(new Uint8Array(8))); // false console.log(isArrayBuffer(new DataView(new ArrayBuffer(8)))); // false console.log(isArrayBuffer([])); // false console.log(isArrayBuffer({})); // false console.log(isArrayBuffer(null)); // false console.log(isArrayBuffer(undefined)); // false ``` Frequently used in file processing and network communication. ```typescript import { isArrayBuffer } from 'es-toolkit/predicate'; // Processing file read results async function processFileData(file: File) { const result = await file.arrayBuffer(); if (isArrayBuffer(result)) { console.log(`File size: ${result.byteLength} bytes`); // Process binary data const view = new DataView(result); const header = view.getUint32(0, true); console.log(`File header: ${header.toString(16)}`); } } // Checking data received from WebSocket function handleWebSocketMessage(data: unknown) { if (isArrayBuffer(data)) { console.log('Received binary message'); const bytes = new Uint8Array(data); // Process byte data } else if (typeof data === 'string') { console.log('Received text message'); // Process string data } } ``` #### Parameters * `value` (`unknown`): The value to check if it's an `ArrayBuffer`. #### Returns (`value is ArrayBuffer`): Returns `true` if the value is an `ArrayBuffer`, `false` otherwise. --- --- url: /reference/compat/predicate/isArrayBuffer.md --- # isArrayBuffer (Lodash Compatibility) ::: warning Use es-toolkit's [isArrayBuffer](../../predicate/isArrayBuffer.md) This `isArrayBuffer` function operates slowly due to complex handling for Lodash compatibility. Instead, use the faster and modern [isArrayBuffer](../../predicate/isArrayBuffer.md) from `es-toolkit`. ::: Checks if a value is an ArrayBuffer. ```typescript const result = isArrayBuffer(value); ``` ## Usage ### `isArrayBuffer(value)` Use `isArrayBuffer` when you want to type-safely check if a value is an ArrayBuffer. It also works as a type guard in TypeScript. ```typescript import { isArrayBuffer } from 'es-toolkit/compat'; // ArrayBuffer check const buffer = new ArrayBuffer(16); isArrayBuffer(buffer); // true // Other types return false isArrayBuffer(new Array()); // false isArrayBuffer(new Map()); // false isArrayBuffer({}); // false isArrayBuffer('hello'); // false isArrayBuffer(123); // false isArrayBuffer(null); // false isArrayBuffer(undefined); // false ``` #### Parameters * `value` (`unknown`): The value to check if it's an ArrayBuffer. #### Returns (`value is ArrayBuffer`): Returns `true` if the value is an ArrayBuffer, otherwise `false`. --- --- url: /reference/compat/predicate/isArrayLike.md --- # isArrayLike (Lodash Compatibility) Checks if a value is an array-like object. ```typescript const result = isArrayLike(value); ``` ## Usage ### `isArrayLike(value)` Use `isArrayLike` when you need to check if a given value is an array-like object. Arrays, strings, arguments objects, and NodeLists are all considered array-like objects. ```typescript import { isArrayLike } from 'es-toolkit/compat'; // Arrays and strings isArrayLike([1, 2, 3]); // true isArrayLike('abc'); // true isArrayLike(''); // true // Array-like objects isArrayLike({ 0: 'a', 1: 'b', length: 2 }); // true isArrayLike({ length: 0 }); // true // arguments object function example() { return isArrayLike(arguments); // true } // Non-array-like values isArrayLike({}); // false isArrayLike({ length: 'invalid' }); // false isArrayLike(null); // false isArrayLike(undefined); // false isArrayLike(() => {}); // false isArrayLike(123); // false ``` #### Parameters * `value` (`any`): The value to check. #### Returns (`boolean`): Returns `true` if the value is an array-like object, otherwise `false`. --- --- url: /reference/compat/predicate/isArrayLikeObject.md --- # isArrayLikeObject (Lodash Compatibility) Checks if a value is an array-like object that is not a primitive. ```typescript const result = isArrayLikeObject(value); ``` ## Usage ### `isArrayLikeObject(value)` Use `isArrayLikeObject` when you need to check if a given value is an array-like object that is not a primitive. This includes arrays, arguments objects, NodeLists, etc., but excludes strings since they are primitive values. ```typescript import { isArrayLikeObject } from 'es-toolkit/compat'; // Array-like objects (not primitives) isArrayLikeObject([1, 2, 3]); // true isArrayLikeObject({ 0: 'a', 1: 'b', length: 2 }); // true isArrayLikeObject({ length: 0 }); // true // arguments object function example() { return isArrayLikeObject(arguments); // true } // NodeList or HTMLCollection (in browsers) isArrayLikeObject(document.querySelectorAll('div')); // true // Primitives are false (including strings) isArrayLikeObject('abc'); // false isArrayLikeObject(''); // false isArrayLikeObject(123); // false isArrayLikeObject(true); // false // Other objects isArrayLikeObject({}); // false isArrayLikeObject(null); // false isArrayLikeObject(undefined); // false isArrayLikeObject(() => {}); // false ``` #### Parameters * `value` (`any`): The value to check. #### Returns (`boolean`): Returns `true` if the value is an array-like object that is not a primitive, otherwise `false`. --- --- url: /reference/predicate/isBlob.md --- # isBlob Checks if a value is a Blob instance. ```typescript const result = isBlob(value); ``` ## Usage ### `isBlob(value)` Use `isBlob` when you want to check if a value is a Blob instance. Useful when handling files or binary data in browser environments. ```typescript import { isBlob } from 'es-toolkit/predicate'; // Basic Blob instances const blob = new Blob(['hello'], { type: 'text/plain' }); const file = new File(['content'], 'example.txt', { type: 'text/plain' }); console.log(isBlob(blob)); // true console.log(isBlob(file)); // true (File extends Blob) // Non-Blob values console.log(isBlob(new ArrayBuffer(8))); // false console.log(isBlob('text data')); // false console.log(isBlob({})); // false console.log(isBlob(null)); // false ``` Useful for file processing and API response validation. ```typescript import { isBlob } from 'es-toolkit/predicate'; // Processing uploaded files function processUploadedFile(file: unknown) { if (isBlob(file)) { // TypeScript infers file as Blob console.log(`File size: ${file.size} bytes`); console.log(`MIME type: ${file.type}`); // Safely use Blob methods file.text().then(text => console.log('Content:', text)); } else { console.log('Invalid file'); } } // Implementing download functionality async function handleDownload(data: unknown, filename: string) { if (isBlob(data)) { const url = URL.createObjectURL(data); const link = document.createElement('a'); link.href = url; link.download = filename; link.click(); URL.revokeObjectURL(url); } } ``` #### Parameters * `value` (`unknown`): The value to check if it's a Blob instance. #### Returns (`value is Blob`): Returns `true` if the value is a Blob instance, `false` otherwise. --- --- url: /reference/predicate/isBoolean.md --- # isBoolean Checks if a value is a boolean type. ```typescript const result = isBoolean(value); ``` ## Usage ### `isBoolean(value)` Use `isBoolean` when you want to check if a value is exactly `true` or `false`. It acts as a type guard in TypeScript, narrowing the value's type to `boolean`. ```typescript import { isBoolean } from 'es-toolkit/predicate'; // Checking basic boolean values isBoolean(true); // true isBoolean(false); // true // Distinguishing from other types isBoolean(1); // false isBoolean(0); // false isBoolean('true'); // false isBoolean('false'); // false ``` Particularly useful when used as a type guard in TypeScript. ```typescript import { isBoolean } from 'es-toolkit/predicate'; function processValue(value: unknown) { if (isBoolean(value)) { // value is narrowed to boolean console.log(value ? "It's true" : "It's false"); } else { console.log('Not a boolean value'); } } ``` Can also be used for validating API responses or user input. ```typescript import { isBoolean } from 'es-toolkit/predicate'; // Validating API response interface APIResponse { success: unknown; data: any; } function validateResponse(response: APIResponse) { if (isBoolean(response.success)) { console.log(`API call ${response.success ? 'succeeded' : 'failed'}`); return response.success; } console.log('Invalid response format'); return false; } ``` #### Parameters * `value` (`unknown`): The value to check if it's a boolean type. #### Returns (`value is boolean`): Returns `true` if the value is `true` or `false`, `false` otherwise. --- --- url: /reference/compat/predicate/isBoolean.md --- # isBoolean (Lodash Compatibility) ::: warning Use `typeof` operator This `isBoolean` function is complex due to handling Boolean object wrappers. Instead, use the simpler and modern `typeof value === 'boolean'`. ::: Checks if a value is of boolean type. ```typescript const result = isBoolean(value); ``` ## Usage ### `isBoolean(value)` Use `isBoolean` when you want to type-safely check if a value is of boolean type. It checks both primitive boolean values and Boolean object wrappers. It also works as a type guard in TypeScript. ```typescript import { isBoolean } from 'es-toolkit/compat'; // Primitive boolean values isBoolean(true); // true isBoolean(false); // true // Boolean object wrappers isBoolean(new Boolean(true)); // true isBoolean(new Boolean(false)); // true // Other types return false isBoolean(0); // false isBoolean(1); // false isBoolean('true'); // false isBoolean('false'); // false isBoolean(null); // false isBoolean(undefined); // false isBoolean({}); // false isBoolean([]); // false ``` #### Parameters * `value` (`unknown`): The value to check if it's of boolean type. #### Returns (`value is boolean`): Returns `true` if the value is of boolean type, otherwise `false`. --- --- url: /reference/predicate/isBrowser.md --- # isBrowser Checks if the current execution environment is a browser. ```typescript const result = isBrowser(); ``` ## Usage ### `isBrowser()` Use `isBrowser` when you have code that should only run in browser environments. It determines if the environment is a browser by checking for the existence of `window.document`. Useful in SSR (Server-Side Rendering) or Node.js environments. ```typescript import { isBrowser } from 'es-toolkit/predicate'; // Manipulate DOM only in browser environment if (isBrowser()) { document.getElementById('app').innerHTML = 'Hello World'; console.log('Running in browser environment'); } else { console.log('Running in server environment'); } ``` Can be used to implement conditional logic based on the environment. ```typescript import { isBrowser } from 'es-toolkit/predicate'; function getWindowWidth() { if (isBrowser()) { return window.innerWidth; } return 0; // Return default value on server } // Registering event listeners function addWindowListener() { if (isBrowser()) { window.addEventListener('resize', () => { console.log('Window size changed'); }); } } ``` Particularly useful in SSR frameworks like Next.js or Nuxt.js. ```typescript import { isBrowser } from 'es-toolkit/predicate'; function initializeAnalytics() { if (isBrowser()) { // Load analytics script only in browser const script = document.createElement('script'); script.src = 'https://analytics.example.com/script.js'; document.head.appendChild(script); } } // Accessing local storage function getStoredValue(key: string) { if (isBrowser()) { return localStorage.getItem(key); } return null; } ``` #### Returns (`boolean`): Returns `true` if the current environment is a browser, `false` otherwise. --- --- url: /reference/predicate/isBuffer.md --- # isBuffer Checks if a value is a Buffer instance. ```typescript const result = isBuffer(value); ``` ## Usage ### `isBuffer(value)` Use `isBuffer` when you want to check if a value is a Buffer object in Node.js environments. Useful for file processing, network communication, and binary data manipulation. It acts as a type guard in TypeScript, narrowing the value's type to `Buffer`. ```typescript import { isBuffer } from 'es-toolkit/predicate'; // Checking Buffer instances const buffer = Buffer.from('hello world', 'utf8'); isBuffer(buffer); // true // Distinguishing from other types isBuffer('hello world'); // false isBuffer(new Uint8Array([1, 2, 3])); // false isBuffer(new ArrayBuffer(8)); // false ``` Particularly useful when used as a type guard in TypeScript. ```typescript import { isBuffer } from 'es-toolkit/predicate'; function processData(data: unknown) { if (isBuffer(data)) { // data is narrowed to Buffer console.log(`Buffer size: ${data.length} bytes`); console.log(`Buffer content: ${data.toString('utf8')}`); // Can safely use Buffer methods const slice = data.slice(0, 10); } } ``` Frequently used in file processing and network communication. ```typescript import { isBuffer } from 'es-toolkit/predicate'; // Processing file data function readFileData(data: unknown) { if (isBuffer(data)) { const text = data.toString('utf8'); const header = data.readUInt32BE(0); console.log('File content:', text); } } // Processing network data function handleNetworkData(chunk: unknown) { if (isBuffer(chunk)) { console.log(`Received data size: ${chunk.length} bytes`); const processed = Buffer.concat([chunk, Buffer.from('\n')]); return processed; } return null; } ``` #### Parameters * `value` (`unknown`): The value to check if it's a Buffer instance. #### Returns (`boolean`): Returns `true` if the value is a Buffer instance, `false` otherwise. --- --- url: /reference/compat/predicate/isBuffer.md --- # isBuffer (Lodash Compatibility) ::: warning Use es-toolkit's [isBuffer](../../predicate/isBuffer.md) instead This `isBuffer` function operates slowly due to complex processing for Lodash compatibility. Use the faster and more modern `es-toolkit`'s [isBuffer](../../predicate/isBuffer.md) instead. ::: Checks if a value is a Buffer instance. ```typescript const result = isBuffer(value); ``` ## Usage ### `isBuffer(value)` Use `isBuffer` when you want to type-safely check if a value is a Buffer instance. It's useful when working with Buffer objects in Node.js environments. It also works as a type guard in TypeScript. ```typescript import { isBuffer } from 'es-toolkit/compat'; // Check Buffer instance const buffer = Buffer.from('hello'); isBuffer(buffer); // true // Other types return false isBuffer('hello'); // false isBuffer([1, 2, 3]); // false isBuffer(new Uint8Array([1, 2, 3])); // false isBuffer({}); // false isBuffer(null); // false isBuffer(undefined); // false ``` #### Parameters * `value` (`unknown`): The value to check if it's a Buffer instance. #### Returns (`boolean`): Returns `true` if the value is a Buffer instance, `false` otherwise. --- --- url: /reference/predicate/isDate.md --- # isDate Checks if a value is a Date object. ```typescript const result = isDate(value); ``` ## Usage ### `isDate(value)` Use `isDate` when you want to check if a value is a date object. Useful for distinguishing Date objects from string or number representations of dates. It acts as a type guard in TypeScript, narrowing the value's type to `Date`. ```typescript import { isDate } from 'es-toolkit/predicate'; // Checking Date objects const date = new Date(); isDate(date); // true // Distinguishing from other types isDate('2024-01-01'); // false - string isDate(1640995200000); // false - timestamp isDate({}); // false ``` Particularly useful when used as a type guard in TypeScript. ```typescript import { isDate } from 'es-toolkit/predicate'; function formatDate(value: unknown): string { if (isDate(value)) { // value is narrowed to Date return value.toISOString(); } return 'Invalid date'; } ``` Can be used for processing API responses or validating user input. ```typescript import { isDate } from 'es-toolkit/predicate'; // Processing API response function processResponse(response: { createdAt: unknown }) { if (isDate(response.createdAt)) { console.log(`Created at: ${response.createdAt.toLocaleDateString()}`); } } // Validating date function validateBirthDate(value: unknown): boolean { if (isDate(value)) { const now = new Date(); const minAge = new Date(now.getFullYear() - 150, now.getMonth(), now.getDate()); return value <= now && value >= minAge; } return false; } ``` #### Parameters * `value` (`unknown`): The value to check if it's a Date object. #### Returns (`value is Date`): Returns `true` if the value is a Date object, `false` otherwise. --- --- url: /reference/compat/predicate/isDate.md --- # isDate (Lodash Compatibility) ::: warning Use es-toolkit's [isDate](../../predicate/isDate.md) instead This `isDate` function operates slowly due to complex processing for Lodash compatibility. Use the faster and more modern `es-toolkit`'s [isDate](../../predicate/isDate.md) instead. ::: Checks if a value is a Date object. ```typescript const result = isDate(value); ``` ## Usage ### `isDate(value)` Use `isDate` when you want to type-safely check if a value is a Date object. It also works as a type guard in TypeScript. ```typescript import { isDate } from 'es-toolkit/compat'; // Check Date object const date = new Date(); isDate(date); // true // Invalid Date is also recognized as a Date object const invalidDate = new Date('invalid'); isDate(invalidDate); // true // Other types return false isDate('2024-01-01'); // false isDate(1640995200000); // false isDate({}); // false isDate(null); // false isDate(undefined); // false ``` #### Parameters * `value` (`unknown`): The value to check if it's a Date object. #### Returns (`value is Date`): Returns `true` if the value is a Date object, `false` otherwise. --- --- url: /reference/compat/predicate/isElement.md --- # isElement (Lodash Compatibility) ::: warning Use `instanceof HTMLElement` This `isElement` function performs structural checks which can be inaccurate and slow. Instead, use the more accurate and modern `instanceof HTMLElement` or `element.nodeType === 1` checks. ::: Checks if a value is a DOM element. ```typescript const result = isElement(value); ``` ## Usage ### `isElement(value)` Use `isElement` when you need to check if a given value is a DOM element. This function performs structural checks, so the results may not be completely accurate. ```typescript import { isElement } from 'es-toolkit/compat'; // DOM elements isElement(document.body); // true isElement(document.createElement('div')); // true isElement(document.querySelector('p')); // true (if element exists) // Non-DOM element values isElement(''); // false isElement({}); // false isElement(null); // false isElement(undefined); // false // Text nodes or other node types isElement(document.createTextNode('text')); // false isElement(document.createComment('comment')); // false ``` #### Parameters * `value` (`any`): The value to check. #### Returns (`boolean`): Returns `true` if the value appears to be a DOM element, otherwise `false`. --- --- url: /reference/compat/predicate/isEmpty.md --- # isEmpty (Lodash Compatibility) Checks if a given value is empty. ```typescript const result = isEmpty(value); ``` ## Usage ### `isEmpty(value)` Use `isEmpty` when you want to check if various types of values are empty. It can handle strings, arrays, objects, Maps, Sets, and more. ```typescript import { isEmpty } from 'es-toolkit/compat'; // String checks isEmpty(''); // true isEmpty('hello'); // false // Array checks isEmpty([]); // true isEmpty([1, 2, 3]); // false // Object checks isEmpty({}); // true isEmpty({ a: 1 }); // false // Map and Set checks isEmpty(new Map()); // true isEmpty(new Set()); // true isEmpty(new Map([['key', 'value']])); // false isEmpty(new Set([1, 2, 3])); // false // null and undefined isEmpty(null); // true isEmpty(undefined); // true isEmpty(); // true // Array-like objects isEmpty({ 0: 'a', length: 1 }); // false isEmpty({ length: 0 }); // false ``` All primitive values are treated as empty: ```typescript import { isEmpty } from 'es-toolkit/compat'; isEmpty(0); // true isEmpty(false); // true isEmpty(123); // true isEmpty('text'); // false (strings are judged by length) ``` #### Parameters * `value` (`unknown`, optional): The value to check. #### Returns (`boolean`): Returns `true` if the value is empty, otherwise `false`. --- --- url: /reference/predicate/isEmptyObject.md --- # isEmptyObject Checks if a plain object has no properties (`{}`). ```typescript const result = isEmptyObject(value); ``` ## Usage ### `isEmptyObject(value)` Use `isEmptyObject` when you want to check if a plain object has no properties like `{}`. Returns `false` for other object types like arrays, Map, or Set. ```typescript import { isEmptyObject } from 'es-toolkit'; // Plain objects with no properties isEmptyObject({}); // true isEmptyObject(new Object()); // true isEmptyObject(Object.create(null)); // true // Objects with properties isEmptyObject({ a: 1 }); // false isEmptyObject({ key: 'value' }); // false // Non-plain object types isEmptyObject([]); // false (array) isEmptyObject(null); // false isEmptyObject(new Map()); // false isEmptyObject(new Set()); // false ``` #### Parameters * `value` (`unknown`): The value to check. #### Returns (`value is Record`): Returns `true` if it's a plain object with no properties, `false` otherwise. --- --- url: /reference/predicate/isEqual.md --- # isEqual Performs a deep comparison to check if two values are equal. ```typescript const result = isEqual(a, b); ``` ## Usage ### `isEqual(a, b)` Use `isEqual` when you want to check if two values are deeply equal, including objects, arrays, Date, RegExp, etc. Returns `true` if the contents are the same even if the references are different. Useful for unit testing and data comparison. ```typescript import { isEqual } from 'es-toolkit/predicate'; // Primitive type comparison isEqual(1, 1); // true isEqual('hello', 'hello'); // true isEqual(true, true); // true // Special value handling isEqual(NaN, NaN); // true isEqual(+0, -0); // true ``` Supports deep comparison of objects and arrays. ```typescript import { isEqual } from 'es-toolkit/predicate'; // Deep object comparison const obj1 = { a: 1, b: { c: 2, d: [3, 4] } }; const obj2 = { a: 1, b: { c: 2, d: [3, 4] } }; isEqual(obj1, obj2); // true // Array comparison const arr1 = [1, 2, [3, 4]]; const arr2 = [1, 2, [3, 4]]; isEqual(arr1, arr2); // true ``` Can also compare objects like Date, RegExp, Map, Set. ```typescript import { isEqual } from 'es-toolkit/predicate'; // Date comparison const date1 = new Date('2020-01-01'); const date2 = new Date('2020-01-01'); isEqual(date1, date2); // true // RegExp comparison const regex1 = /hello/g; const regex2 = /hello/g; isEqual(regex1, regex2); // true // Map and Set comparison const map1 = new Map([['key', 'value']]); const map2 = new Map([['key', 'value']]); isEqual(map1, map2); // true const set1 = new Set([1, 2, 3]); const set2 = new Set([1, 2, 3]); isEqual(set1, set2); // true ``` Frequently used in unit testing. ```typescript import { isEqual } from 'es-toolkit/predicate'; function testApiResponse() { const expected = { status: 200, data: { message: 'success' } }; const actual = { status: 200, data: { message: 'success' } }; if (isEqual(expected, actual)) { console.log('Test passed!'); } else { console.log('Test failed!'); } } ``` #### Parameters * `a` (`unknown`): The first value to compare. * `b` (`unknown`): The second value to compare. #### Returns (`boolean`): Returns `true` if the two values are deeply equal, `false` otherwise. --- --- url: /reference/compat/predicate/isEqual.md --- # isEqual (Lodash Compatibility) ::: warning Use `es-toolkit`'s [isEqual](../../predicate/isEqual.md) This `isEqual` function operates slowly due to complex handling for Lodash compatibility. Instead, use the faster and modern [isEqual](../../predicate/isEqual.md) from `es-toolkit`. ::: Performs a deep comparison between two values to determine if they are equal. ```typescript const result = isEqual(value1, value2); ``` ## Usage ### `isEqual(a, b)` Use `isEqual` when you want to perform a deep comparison between two values. It compares complex types like Date, RegExp, objects, and arrays by their content. ```typescript import { isEqual } from 'es-toolkit/compat'; // Basic type comparison isEqual(1, 1); // true isEqual('hello', 'hello'); // true isEqual(true, true); // true // Object deep comparison isEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // true isEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // true isEqual({ a: 1 }, { a: 1, b: undefined }); // false // Array deep comparison isEqual([1, 2, 3], [1, 2, 3]); // true isEqual([1, [2, 3]], [1, [2, 3]]); // true // Date object comparison isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true isEqual(new Date('2020-01-01'), new Date('2020-01-02')); // false // RegExp object comparison isEqual(/abc/g, /abc/g); // true isEqual(/abc/g, /abc/i); // false ``` It also recursively compares nested objects and arrays. ```typescript import { isEqual } from 'es-toolkit/compat'; const obj1 = { user: { name: 'John', details: { age: 30, hobbies: ['reading', 'gaming'], }, }, }; const obj2 = { user: { name: 'John', details: { age: 30, hobbies: ['reading', 'gaming'], }, }, }; isEqual(obj1, obj2); // true ``` #### Parameters * `a` (`unknown`): The first value to compare. * `b` (`unknown`): The second value to compare. #### Returns (`boolean`): Returns `true` if the values are equal, otherwise `false`. --- --- url: /reference/predicate/isEqualWith.md --- # isEqualWith Checks if two values are equal using a custom comparison function. ```typescript const result = isEqualWith(a, b, areValuesEqual); ``` ## Usage ### `isEqualWith(a, b, areValuesEqual)` Use `isEqualWith` when you need special comparison logic. If the custom function returns `true` or `false`, that result is used; if it returns `undefined`, the default comparison method is used. Useful for case-insensitive comparison, excluding specific properties, approximate value comparison, etc. ```typescript import { isEqualWith } from 'es-toolkit/predicate'; // Case-insensitive string comparison const caseInsensitiveCompare = (a, b) => { if (typeof a === 'string' && typeof b === 'string') { return a.toLowerCase() === b.toLowerCase(); } }; isEqualWith('Hello', 'hello', caseInsensitiveCompare); // true isEqualWith({ name: 'Alice' }, { name: 'ALICE' }, caseInsensitiveCompare); // true ``` Can also be used for approximate number comparison. ```typescript import { isEqualWith } from 'es-toolkit/predicate'; // Floating-point error tolerance comparison const approximateCompare = (a, b) => { if (typeof a === 'number' && typeof b === 'number') { return Math.abs(a - b) < 0.01; // Treat differences under 0.01 as equal } }; isEqualWith(0.1 + 0.2, 0.3, approximateCompare); // true isEqualWith({ price: 10.01 }, { price: 10.02 }, approximateCompare); // true ``` Useful when you want to ignore specific properties during comparison. ```typescript import { isEqualWith } from 'es-toolkit/predicate'; // Ignoring specific properties during comparison const ignoreTimestamp = (a, b, property) => { if (property === 'timestamp') { return true; // Always treat timestamp property as equal } }; const obj1 = { id: 1, name: 'Test', timestamp: 1000 }; const obj2 = { id: 1, name: 'Test', timestamp: 2000 }; isEqualWith(obj1, obj2, ignoreTimestamp); // true ``` Can implement complex custom comparison logic. ```typescript import { isEqualWith } from 'es-toolkit/predicate'; const areValuesEqual = (a, b, property) => { // Ignore ID if (property === 'id') { return true; } // Compare name case-insensitively if (property === 'name' && typeof a === 'string' && typeof b === 'string') { return a.toLowerCase() === b.toLowerCase(); } // Use default comparison for the rest return undefined; }; const user1 = { id: 1, name: 'Alice', age: 25 }; const user2 = { id: 999, name: 'ALICE', age: 25 }; isEqualWith(user1, user2, areValuesEqual); // true ``` #### Parameters * `a` (`unknown`): The first value to compare. * `b` (`unknown`): The second value to compare. * `areValuesEqual` (`(x: any, y: any, property?: PropertyKey, xParent?: any, yParent?: any, stack?: Map) => boolean | void`): A custom comparison function. If it returns `true` or `false`, that result is used; if it returns `undefined`, the default comparison method is used. #### Returns (`boolean`): Returns `true` if the two values are equal according to the custom criteria, `false` otherwise. --- --- url: /reference/compat/predicate/isEqualWith.md --- # isEqualWith (Lodash Compatibility) ::: warning Use es-toolkit's [isEqualWith](../../predicate/isEqualWith.md) instead This `isEqualWith` function operates slowly due to complex processing for Lodash compatibility. Use the faster and more modern `es-toolkit`'s [isEqualWith](../../predicate/isEqualWith.md) instead. ::: Checks if two values are equal using a custom comparison function. ```typescript const result = isEqualWith(a, b, customizer); ``` ## Usage ### `isEqualWith(a, b, areValuesEqual?)` Deeply compares two values using a custom comparison function. If the custom function returns a boolean value, that result is used. If it returns `undefined`, the default equality comparison is used. The custom comparison function is also used when comparing values inside complex structures like objects, arrays, Map, Set, etc., ensuring deep comparison. ```typescript import { isEqualWith } from 'es-toolkit/compat'; // Case-insensitive string comparison const customizer = (a: any, b: any) => { if (typeof a === 'string' && typeof b === 'string') { return a.toLowerCase() === b.toLowerCase(); } }; isEqualWith('Hello', 'hello', customizer); // true isEqualWith({ a: 'Hello' }, { a: 'hello' }, customizer); // true // Compare numbers by absolute value const absCustomizer = (a: any, b: any) => { if (typeof a === 'number' && typeof b === 'number') { return Math.abs(a) === Math.abs(b); } }; isEqualWith([-1, 2], [1, -2], absCustomizer); // true // Complex object comparison const obj1 = { name: 'JOHN', details: { age: 30, city: 'NYC' }, }; const obj2 = { name: 'john', details: { age: 30, city: 'nyc' }, }; isEqualWith(obj1, obj2, customizer); // true ``` Special handling for Map and Set: ```typescript import { isEqualWith } from 'es-toolkit/compat'; const customizer = (a: any, b: any) => { if (typeof a === 'string' && typeof b === 'string') { return a.toLowerCase() === b.toLowerCase(); } }; const map1 = new Map([['KEY', 'value']]); const map2 = new Map([['key', 'value']]); isEqualWith(map1, map2, customizer); // true const set1 = new Set(['HELLO']); const set2 = new Set(['hello']); isEqualWith(set1, set2, customizer); // true ``` #### Parameters * `a` (`any`): The first value to compare. * `b` (`any`): The second value to compare. * `areValuesEqual` (`(x: any, y: any, property?: PropertyKey, xParent?: any, yParent?: any, stack?: Map) => boolean | void`): The custom comparison function. * `x`: Value from the first object `a` * `y`: Value from the second object `b` * `property`: The property key used to get `x` and `y` * `xParent`: The parent object of the first value `x` * `yParent`: The parent object of the second value `y` * `stack`: Internal stack (Map) for handling circular references #### Returns (`boolean`): Returns `true` if the values are equal according to the custom function, `false` otherwise. --- --- url: /reference/predicate/isError.md --- # isError Checks if a value is an `Error` object. ```typescript const result = isError(value); ``` ## Usage ### `isError(value)` Use `isError` when you want to check if a value is an `Error` object. It can be used as a type guard in TypeScript to narrow the value's type to `Error`. Particularly useful in try-catch blocks or API response processing. ```typescript import { isError } from 'es-toolkit/predicate'; // Checking Error objects isError(new Error('Something went wrong')); // true isError(new TypeError('Type error')); // true // Distinguishing from other types isError('error'); // false isError({ name: 'Error', message: 'Custom error' }); // false ``` When used as a type guard in TypeScript, the value's type is narrowed. ```typescript function handleError(value: unknown) { if (isError(value)) { // value is narrowed to Error console.log(`Error occurred: ${value.message}`); return value.name; } return 'Not an error'; } ``` #### Parameters * `value` (`unknown`): The value to check if it's an `Error` object. #### Returns (`value is Error`): Returns `true` if the value is an `Error` object, `false` otherwise. --- --- url: /reference/compat/predicate/isError.md --- # isError (Lodash Compatibility) ::: warning Use `es-toolkit`'s [isError](../../predicate/isError.md) instead This `isError` function operates slowly due to complex handling for Lodash compatibility. Use the faster and more modern `es-toolkit`'s [isError](../../predicate/isError.md) instead. ::: Checks if a value is an Error object. ```typescript const result = isError(value); ``` ## Usage ### `isError(value)` Use `isError` when you want to type-safely check if a value is an Error object. It also works as a type guard in TypeScript. ```typescript import { isError } from 'es-toolkit/compat'; // Error object checking isError(new Error()); // true isError(new TypeError('Type error')); // true isError(new ReferenceError('Reference error')); // true // Custom errors that inherit from Error class CustomError extends Error {} isError(new CustomError()); // true // Other types return false isError('Error'); // false isError({ name: 'Error', message: 'Something went wrong' }); // false isError({}); // false isError(null); // false isError(undefined); // false ``` #### Parameters * `value` (`unknown`): The value to check if it's an Error object. #### Returns (`value is Error`): Returns `true` if the value is an Error object, `false` otherwise. --- --- url: /reference/predicate/isFile.md --- # isFile Checks if a value is a File object. ```typescript const result = isFile(value); ``` ## Usage ### `isFile(value)` Use `isFile` when you want to check if a value is a File instance. A File object represents a file uploaded by a user or obtained from the file system as part of the web API. Unlike Blob objects, it contains additional information such as the filename and last modified time. ```typescript import { isFile } from 'es-toolkit/predicate'; // Checking File objects const file = new File(['hello'], 'example.txt', { type: 'text/plain' }); console.log(isFile(file)); // true // Blob objects are not Files const blob = new Blob(['hello'], { type: 'text/plain' }); console.log(isFile(blob)); // false // Regular objects console.log(isFile({})); // false console.log(isFile([])); // false console.log(isFile('text')); // false console.log(isFile(null)); // false console.log(isFile(undefined)); // false ``` Can be used to validate if a given argument is a valid file. ```typescript // File upload handler function handleFileUpload(input: unknown) { if (isFile(input)) { console.log(`Filename: ${input.name}`); console.log(`File size: ${input.size} bytes`); console.log(`File type: ${input.type}`); console.log(`Last modified: ${input.lastModified}`); // Since it's confirmed to be a File, can safely access file-related properties return input; } throw new Error('Not a valid file'); } ``` Safely handles environments where `File` is not supported in JavaScript. ```typescript // Safe in Node.js environment or environments without File support console.log(isFile(new Date())); // false // Does not error even in environments where File is not defined if (typeof File === 'undefined') { console.log(isFile({})); // false } ``` #### Parameters * `value` (`unknown`): The value to check if it's a File object. #### Returns (`value is File`): Returns `true` if the value is a File object, `false` otherwise. --- --- url: /reference/compat/predicate/isFinite.md --- # isFinite (Lodash Compatibility) ::: warning Use `Number.isFinite` This `isFinite` function operates slowly due to additional type checking overhead. Instead, use the faster and modern `Number.isFinite`. ::: Checks if a value is a finite number. ```typescript const result = isFinite(value); ``` ## Usage ### `isFinite(value)` Use `isFinite` when you need to check if a given value is a finite number. This function also works as a type guard in TypeScript, narrowing the type of the value to `number`. ```typescript import { isFinite } from 'es-toolkit/compat'; // Finite numbers isFinite(100); // true isFinite(-50); // true isFinite(3.14); // true isFinite(0); // true // Infinity is false isFinite(Infinity); // false isFinite(-Infinity); // false // NaN is also false isFinite(NaN); // false // Other types are also false isFinite('100'); // false isFinite([]); // false isFinite({}); // false isFinite(null); // false isFinite(undefined); // false ``` #### Parameters * `value` (`any`): The value to check. #### Returns (`value is number`): Returns `true` if the value is a finite number, otherwise `false`.\ When `true`, TypeScript narrows the type of `value` to `number`. --- --- url: /reference/predicate/isFunction.md --- # isFunction Checks if a value is a function. ```typescript const result = isFunction(value); ``` ## Usage ### `isFunction(value)` Use `isFunction` when you want to check if a value is a function. Can detect all types of functions including regular functions, async functions, generator functions, and constructor functions. ```typescript import { isFunction } from 'es-toolkit/predicate'; // Regular functions console.log(isFunction(function () {})); // true console.log(isFunction(() => {})); // true console.log(isFunction(Array.prototype.slice)); // true // Async functions console.log(isFunction(async function () {})); // true console.log(isFunction(async () => {})); // true // Generator functions console.log(isFunction(function* () {})); // true // Constructors console.log(isFunction(Array)); // true console.log(isFunction(Date)); // true console.log(isFunction(RegExp)); // true console.log(isFunction(Promise)); // true ``` Also detects built-in JavaScript functions and classes: ```typescript // Built-in constructors console.log(isFunction(Object)); // true console.log(isFunction(String)); // true console.log(isFunction(Number)); // true console.log(isFunction(Boolean)); // true // Typed array constructors console.log(isFunction(Int8Array)); // true console.log(isFunction(Uint8Array)); // true console.log(isFunction(Float32Array)); // true // Proxy and Reflect console.log(isFunction(Proxy)); // true console.log(isFunction(Reflect.get)); // true ``` Distinguishes from non-function values: ```typescript // Non-functions console.log(isFunction({})); // false console.log(isFunction([])); // false console.log(isFunction('text')); // false console.log(isFunction(42)); // false console.log(isFunction(null)); // false console.log(isFunction(undefined)); // false // Function-like but not functions console.log(isFunction({ call: function () {} })); // false ``` Useful for callback function validation or dynamic function invocation: ```typescript // Callback function validation function processData(data: any[], callback?: unknown) { const result = data.map(item => item * 2); if (isFunction(callback)) { // Can safely call callback since it's confirmed to be a function callback(result); } return result; } // Dynamic function execution function executeIfFunction(fn: unknown, ...args: any[]) { if (isFunction(fn)) { return fn(...args); } console.log('Given value is not a function'); return null; } // Checking functions in method chaining const utils = { data: [1, 2, 3], process(fn: unknown) { if (isFunction(fn)) { this.data = this.data.map(fn); } return this; }, }; ``` #### Parameters * `value` (`unknown`): The value to check if it's a function. #### Returns (`value is (...args: any[]) => any`): Returns `true` if the value is a function, `false` otherwise. --- --- url: /reference/compat/predicate/isFunction.md --- # isFunction (Lodash Compatibility) ::: warning Use `es-toolkit`'s [isFunction](../../predicate/isFunction.md) instead This `isFunction` function operates slowly due to complex handling for Lodash compatibility. Use the faster and more modern `es-toolkit`'s [isFunction](../../predicate/isFunction.md) instead. ::: Checks if a value is a function. ```typescript const result = isFunction(value); ``` ## Usage ### `isFunction(value)` Use `isFunction` when you want to type-safely check if a value is a function. It also works as a type guard in TypeScript. ```typescript import { isFunction } from 'es-toolkit/compat'; // Regular functions isFunction(function () {}); // true isFunction(() => {}); // true // Built-in functions and constructors isFunction(Array.prototype.slice); // true isFunction(Proxy); // true isFunction(Int8Array); // true // Async functions and generator functions isFunction(async function () {}); // true isFunction(function* () {}); // true // Other types return false isFunction('function'); // false isFunction({}); // false isFunction([]); // false isFunction(null); // false isFunction(undefined); // false isFunction(123); // false ``` #### Parameters * `value` (`unknown`): The value to check if it's a function. #### Returns (`value is (...args: any[]) => any`): Returns `true` if the value is a function, `false` otherwise. --- --- url: /reference/compat/predicate/isInteger.md --- # isInteger (Lodash Compatibility) ::: warning Use `Number.isInteger` This `isInteger` function operates slowly due to additional type checking overhead. Instead, use the faster and modern `Number.isInteger`. ::: Checks if a value is an integer. ```typescript const result = isInteger(value); ``` ## Usage ### `isInteger(value)` Use `isInteger` when you need to check if a given value is an integer. This function also works as a type guard in TypeScript, narrowing the type of the value to `number`. ```typescript import { isInteger } from 'es-toolkit/compat'; // Integer value checks isInteger(3); // true isInteger(-5); // true isInteger(0); // true // Decimal values are false isInteger(3.14); // false isInteger(-2.5); // false // Infinity is false isInteger(Infinity); // false isInteger(-Infinity); // false // Other types are also false isInteger('3'); // false isInteger([]); // false isInteger({}); // false ``` #### Parameters * `value` (`any`): The value to check. #### Returns (`boolean`): Returns `true` if the value is an integer, otherwise `false`. --- --- url: /reference/predicate/isJSON.md --- # isJSON Checks if a value is a valid JSON string. ```typescript const result = isJSON(value); ``` ## Usage ### `isJSON(value)` Use `isJSON` when you want to check if a string is a valid JSON format. This function verifies if it can be parsed with `JSON.parse()`. According to JSON specifications, strings representing objects, arrays, strings, numbers, booleans, and `null` are all valid. ```typescript import { isJSON } from 'es-toolkit/predicate'; // Valid JSON strings console.log(isJSON('{"name":"John","age":30}')); // true console.log(isJSON('[1,2,3]')); // true console.log(isJSON('"hello world"')); // true console.log(isJSON('42')); // true console.log(isJSON('true')); // true console.log(isJSON('false')); // true console.log(isJSON('null')); // true // Invalid JSON strings console.log(isJSON('undefined')); // false console.log(isJSON('function() {}')); // false console.log(isJSON('{name: "John"}')); // false (keys without quotes) console.log(isJSON("{'name': 'John'}")); // false (single quotes) console.log(isJSON('{}')); // true (empty object is valid) console.log(isJSON('[]')); // true (empty array is valid) ``` All non-string values return `false`: ```typescript // Non-string values console.log(isJSON({ name: 'John' })); // false console.log(isJSON([1, 2, 3])); // false console.log(isJSON(42)); // false console.log(isJSON(true)); // false console.log(isJSON(null)); // false console.log(isJSON(undefined)); // false ``` Useful for API response or user input validation: ```typescript // API response validation function processApiResponse(response: unknown) { if (isJSON(response)) { try { const data = JSON.parse(response); console.log('Parsed data:', data); return data; } catch (error) { // Won't execute here since isJSON returned true console.error('Parsing failed:', error); } } console.log('Not a valid JSON string'); return null; } // User input validation function validateJsonInput(input: unknown): string | null { if (isJSON(input)) { // TypeScript infers input as string return input; } throw new Error('Input must be a valid JSON string'); } // Configuration file validation function loadConfig(configString: unknown) { if (isJSON(configString)) { const config = JSON.parse(configString); return { isValid: true, config, error: null, }; } return { isValid: false, config: null, error: 'Invalid JSON format', }; } ``` Accurately detects complex JSON structures: ```typescript const complexJson = `{ "users": [ { "id": 1, "name": "Alice", "preferences": { "theme": "dark", "notifications": true } } ], "meta": { "total": 1, "page": 1 } }`; console.log(isJSON(complexJson)); // true // Invalid formats console.log(isJSON('{ "name": "John", }')); // false (trailing comma) console.log(isJSON('{ name: "John" }')); // false (unquoted key) console.log(isJSON("{ 'name': 'John' }")); // false (single quotes) ``` #### Parameters * `value` (`unknown`): The value to check if it's a valid JSON string. #### Returns (`value is string`): Returns `true` if the value is a valid JSON string, `false` otherwise. --- --- url: /reference/predicate/isJSONArray.md --- # isJSONArray Checks if a value is a valid JSON array. ```typescript const result = isJSONArray(value); ``` ## Usage ### `isJSONArray(value)` Use `isJSONArray` when you want to check if all elements of an array are valid JSON values. A valid JSON array is an array consisting only of values that can be JSON-serialized (`null`, objects, arrays, strings, numbers, booleans). ```typescript import { isJSONArray } from 'es-toolkit/predicate'; // Valid JSON arrays console.log(isJSONArray([1, 2, 3])); // true console.log(isJSONArray(['hello', 'world'])); // true console.log(isJSONArray([true, false, null])); // true console.log(isJSONArray([{ name: 'John' }, { name: 'Jane' }])); // true console.log( isJSONArray([ [1, 2], [3, 4], ]) ); // true (nested arrays) console.log(isJSONArray([])); // true (empty array) // Complex valid JSON array const complexArray = [42, 'text', true, null, { key: 'value' }, [1, 2, 3]]; console.log(isJSONArray(complexArray)); // true ``` Distinguishes from invalid JSON arrays: ```typescript // Arrays containing functions - invalid console.log(isJSONArray([1, 2, () => {}])); // false console.log(isJSONArray([function () {}])); // false // Arrays containing undefined - invalid console.log(isJSONArray([1, undefined, 3])); // false // Arrays containing Symbols - invalid console.log(isJSONArray([Symbol('test')])); // false // Arrays containing Date objects - invalid (must be converted to string in JSON) console.log(isJSONArray([new Date()])); // false // Non-array values console.log(isJSONArray('not an array')); // false console.log(isJSONArray({ 0: 'a', 1: 'b', length: 2 })); // false (array-like object) console.log(isJSONArray(42)); // false console.log(isJSONArray(null)); // false ``` Useful for API response validation or pre-serialization data verification. ```typescript // API response validation function processApiArray(data: unknown) { if (isJSONArray(data)) { // Can safely use JSON.stringify const jsonString = JSON.stringify(data); console.log('Serialized array:', jsonString); return data; } throw new Error('Not a valid JSON array'); } // User input data validation function validateUserList(input: unknown): any[] { if (isJSONArray(input)) { // TypeScript infers input as any[] return input; } return []; } // Configuration array validation function loadArrayConfig(config: unknown) { if (isJSONArray(config)) { return { isValid: true, items: config, count: config.length, }; } return { isValid: false, items: [], count: 0, }; } // Works with nested structures const nestedData = [{ users: [{ name: 'Alice' }, { name: 'Bob' }] }, { users: [{ name: 'Charlie' }] }]; console.log(isJSONArray(nestedData)); // true ``` Returns `false` for arrays with functions as elements or objects like `TypedArray` that cannot be JSON-serialized. ```typescript // Regular array vs JSON array const regularArray = [1, 2, function () {}]; // Valid as regular array const jsonArray = [1, 2, 3]; // JSON-serializable array console.log(Array.isArray(regularArray)); // true (regular array check) console.log(isJSONArray(regularArray)); // false (JSON array check) console.log(Array.isArray(jsonArray)); // true console.log(isJSONArray(jsonArray)); // true // TypedArray is not a JSON array const typedArray = new Int32Array([1, 2, 3]); console.log(Array.isArray(typedArray)); // false console.log(isJSONArray(typedArray)); // false ``` #### Parameters * `value` (`unknown`): The value to check if it's a valid JSON array. #### Returns (`value is any[]`): Returns `true` if the value is a valid JSON array, `false` otherwise. --- --- url: /reference/predicate/isJSONObject.md --- # isJSONObject Checks if a value is a valid JSON object. ```typescript const result = isJSONObject(value); ``` ## Usage ### `isJSONObject(value)` Use `isJSONObject` when you want to check if an object has string keys and all values are valid JSON values. A valid JSON object is a plain object consisting only of string keys and JSON-serializable values (`null`, objects, arrays, strings, numbers, booleans). ```typescript import { isJSONObject } from 'es-toolkit/predicate'; // Valid JSON objects console.log(isJSONObject({ name: 'John', age: 30 })); // true console.log(isJSONObject({ active: true, score: null })); // true console.log(isJSONObject({})); // true (empty object) // Validates nested structures const nested = { user: { name: 'Alice', preferences: { theme: 'dark', notifications: true, }, }, data: [1, 2, 3], timestamp: null, }; console.log(isJSONObject(nested)); // true // Complex valid JSON object const complex = { id: 42, title: 'Example', published: true, tags: ['javascript', 'tutorial'], author: { name: 'Developer', email: 'dev@example.com', }, metadata: null, }; console.log(isJSONObject(complex)); // true ``` Accurately distinguishes invalid JSON objects containing non-JSON-serializable values like functions, `Symbol`, `Date` objects, `undefined`, or class instances. ```typescript // Objects containing functions - invalid console.log(isJSONObject({ name: 'John', greet: () => {} })); // false console.log(isJSONObject({ method: function () {} })); // false // Objects containing undefined - invalid console.log(isJSONObject({ name: 'John', age: undefined })); // false // Objects with Symbol keys or values - invalid console.log(isJSONObject({ [Symbol('key')]: 'value' })); // false console.log(isJSONObject({ name: Symbol('name') })); // false // Objects like Date, RegExp - invalid console.log(isJSONObject({ created: new Date() })); // false console.log(isJSONObject({ pattern: /test/ })); // false // Class instances - invalid class Person { constructor(public name: string) {} } console.log(isJSONObject(new Person('John'))); // false // Non-object values console.log(isJSONObject('not an object')); // false console.log(isJSONObject(42)); // false console.log(isJSONObject([1, 2, 3])); // false console.log(isJSONObject(null)); // false ``` Can be used to validate safe usage of `JSON.stringify`. ```typescript // API response validation function processApiResponse(data: unknown) { if (isJSONObject(data)) { // Can safely use JSON.stringify const jsonString = JSON.stringify(data); console.log('Serialized object:', jsonString); // TypeScript infers data as Record return data; } throw new Error('Not a valid JSON object'); } // Configuration object validation function loadConfig(config: unknown) { if (isJSONObject(config)) { return { isValid: true, config, keys: Object.keys(config), }; } return { isValid: false, config: {}, keys: [], }; } // User input data validation function validateUserData(input: unknown): Record { if (isJSONObject(input)) { // All properties are guaranteed to be JSON-serializable return input; } throw new Error('User data must be a valid JSON object'); } // Nested object validation function validateNestedConfig(data: unknown) { if (isJSONObject(data)) { // All nested objects and arrays are also guaranteed to be JSON-valid console.log('Configuration is fully JSON-compatible'); return data; } return null; } ``` `isJSONObject` has a different purpose than other object checking functions. `isPlainObject` checks if it's a plain object, while `isJSONObject` checks if it's an object that can be JSON-serialized. ```typescript import { isPlainObject } from 'es-toolkit/predicate'; const objectWithFunction = { name: 'John', greet: function () { return 'Hello'; }, }; const plainJsonObject = { name: 'John', age: 30, }; // Plain object vs JSON object console.log(isPlainObject(objectWithFunction)); // true (plain object) console.log(isJSONObject(objectWithFunction)); // false (not JSON object due to function) console.log(isPlainObject(plainJsonObject)); // true console.log(isJSONObject(plainJsonObject)); // true // Built-in objects console.log(isPlainObject(new Date())); // false console.log(isJSONObject(new Date())); // false // Arrays console.log(isPlainObject([])); // false console.log(isJSONObject([])); // false (arrays are JSON values but not JSON "objects") ``` #### Parameters * `value` (`unknown`): The value to check if it's a valid JSON object. #### Returns (`value is Record`): Returns `true` if the value is a valid JSON object, `false` otherwise. --- --- url: /reference/predicate/isJSONValue.md --- # isJSONValue Checks if a value is a valid JSON value. ```typescript const result = isJSONValue(value); ``` ## Usage ### `isJSONValue(value)` Use `isJSONValue` when you want to check if a value can be JSON-serialized. According to JSON specifications, valid values are `null`, objects, arrays, strings, numbers, and booleans. This function is the foundation for other JSON-related type guards. ```typescript import { isJSONValue } from 'es-toolkit/predicate'; // Primitive JSON values console.log(isJSONValue(null)); // true console.log(isJSONValue('hello')); // true console.log(isJSONValue(42)); // true console.log(isJSONValue(true)); // true console.log(isJSONValue(false)); // true // Objects and arrays (all internal values must also be valid) console.log(isJSONValue({ name: 'John', age: 30 })); // true console.log(isJSONValue([1, 2, 3, 'text'])); // true console.log(isJSONValue([])); // true (empty array) console.log(isJSONValue({})); // true (empty object) // Nested structures const complexData = { user: { name: 'Alice', active: true, scores: [95, 87, 92], }, metadata: null, }; console.log(isJSONValue(complexData)); // true ``` Accurately distinguishes values that cannot be JSON-serialized. Functions, `undefined`, `Symbol`, class instances, etc. are not supported by JSON specifications and return `false`: ```typescript // undefined is not supported in JSON console.log(isJSONValue(undefined)); // false // Functions cannot be JSON-serialized console.log(isJSONValue(() => {})); // false console.log(isJSONValue(function () {})); // false // Symbol is not supported in JSON console.log(isJSONValue(Symbol('test'))); // false // Date objects must be converted to strings in JSON console.log(isJSONValue(new Date())); // false // RegExp objects are not supported in JSON console.log(isJSONValue(/pattern/)); // false // Objects/arrays containing functions or undefined console.log(isJSONValue({ name: 'John', greet: () => {} })); // false console.log(isJSONValue([1, 2, undefined])); // false // BigInt is not supported in JSON console.log(isJSONValue(BigInt(123))); // false ``` Useful for data validation before JSON serialization: ```typescript // Safe JSON serialization function safeJsonStringify(data: unknown): string | null { if (isJSONValue(data)) { // Data is guaranteed to be a valid JSON value return JSON.stringify(data); } console.warn('Data is not JSON-serializable'); return null; } // API request data validation function sendApiRequest(data: unknown) { if (isJSONValue(data)) { const jsonPayload = JSON.stringify(data); // Send API request console.log('Data to send:', jsonPayload); return fetch('/api/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: jsonPayload, }); } throw new Error('API data must be JSON-serializable'); } // localStorage validation before saving function saveToStorage(key: string, value: unknown) { if (isJSONValue(value)) { localStorage.setItem(key, JSON.stringify(value)); return true; } console.error('Cannot save non-JSON-serializable data type to localStorage'); return false; } // Configuration file validation function validateConfig(config: unknown) { if (isJSONValue(config)) { return { isValid: true, config, serialized: JSON.stringify(config), }; } return { isValid: false, config: null, error: 'Config must be a valid JSON value', }; } ``` Can be combined with other type guards. ```typescript // Specific JSON type checking function processJsonData(data: unknown) { if (!isJSONValue(data)) { throw new Error('Invalid JSON value'); } // Now data is guaranteed to be a valid JSON value if (isJSONObject(data)) { console.log('Is a JSON object:', Object.keys(data)); } else if (isJSONArray(data)) { console.log('Is a JSON array:', data.length, 'items'); } else { console.log('Is a primitive JSON value:', typeof data, data); } } // Nested data validation const testData = { valid: { name: 'test', values: [1, 2, 3] }, invalid: { name: 'test', callback: () => {} }, }; console.log(isJSONValue(testData.valid)); // true console.log(isJSONValue(testData.invalid)); // false ``` Edge cases: ```typescript // Special number values console.log(isJSONValue(Infinity)); // false (converted to null in JSON) console.log(isJSONValue(-Infinity)); // false console.log(isJSONValue(NaN)); // false (converted to null in JSON) // Empty values console.log(isJSONValue('')); // true (empty string) console.log(isJSONValue(0)); // true console.log(isJSONValue(false)); // true // Objects with prototypes const obj = Object.create({ inherited: 'value' }); obj.own = 'property'; console.log(isJSONValue(obj)); // true (treated as plain object) ``` #### Parameters * `value` (`unknown`): The value to check if it's a valid JSON value. #### Returns (`value is Record | any[] | string | number | boolean | null`): Returns `true` if the value is a valid JSON value, `false` otherwise. --- --- url: /reference/predicate/isLength.md --- # isLength Checks if a value is a valid array length. ```typescript const result = isLength(value); ``` ## Usage ### `isLength(value)` Use `isLength` when you want to check if a value is a valid array length. A valid length must be an integer between 0 and `Number.MAX_SAFE_INTEGER`. ```typescript import { isLength } from 'es-toolkit/predicate'; // Valid lengths console.log(isLength(0)); // true console.log(isLength(42)); // true console.log(isLength(Number.MAX_SAFE_INTEGER)); // true // Invalid lengths console.log(isLength(-1)); // false (negative) console.log(isLength(1.5)); // false (decimal) console.log(isLength(Number.MAX_SAFE_INTEGER + 1)); // false (unsafe integer) console.log(isLength('42')); // false (string) console.log(isLength(null)); // false (null) ``` Can also be used as a type guard in TypeScript. ```typescript function processLength(value: unknown) { if (isLength(value)) { // Now value is narrowed to number type console.log(value.toFixed(2)); } } ``` #### Parameters * `value` (`unknown`): The value to check if it's a valid length. #### Returns (`boolean`): Returns `true` if the value is a valid length, `false` otherwise. --- --- url: /reference/compat/predicate/isLength.md --- # isLength (Lodash Compatibility) ::: warning Use `es-toolkit`'s [isLength](../../predicate/isLength.md) instead This `isLength` function operates slowly due to complex handling for Lodash compatibility. Use the faster and more modern `es-toolkit`'s [isLength](../../predicate/isLength.md) instead. ::: Checks if a value is a valid length. ```typescript const result = isLength(value); ``` ## Usage ### `isLength(value)` Use `isLength` when you want to check if a value is a valid length. A valid length is a number type, non-negative integer, and below JavaScript's maximum safe integer (`Number.MAX_SAFE_INTEGER`). It also works as a type guard in TypeScript. ```typescript import { isLength } from 'es-toolkit/compat'; // Valid lengths isLength(0); // true isLength(42); // true isLength(100); // true isLength(Number.MAX_SAFE_INTEGER); // true // Invalid lengths isLength(-1); // false (negative) isLength(1.5); // false (not an integer) isLength(Number.MAX_SAFE_INTEGER + 1); // false (exceeds safe range) isLength('3'); // false (string) isLength(null); // false isLength(undefined); // false isLength({}); // false isLength([]); // false ``` It's useful for validating the length property of arrays or strings. ```typescript import { isLength } from 'es-toolkit/compat'; function validateArrayLength(arr: any[]) { if (isLength(arr.length)) { console.log(`Array length ${arr.length} is valid`); return true; } return false; } validateArrayLength([1, 2, 3]); // "Array length 3 is valid" ``` #### Parameters * `value` (`any`): The value to check if it's a valid length. #### Returns (`boolean`): Returns `true` if the value is a valid length, `false` otherwise. --- --- url: /reference/predicate/isMap.md --- # isMap Checks if a value is a Map. ```typescript const result = isMap(value); ``` ## Usage ### `isMap(value)` Use `isMap` when you want to check if a value is a Map instance. It uses the `instanceof` operator to check if it's a `Map`. ```typescript import { isMap } from 'es-toolkit/predicate'; // Map instance const map = new Map([['key', 'value']]); console.log(isMap(map)); // true // Non-Map values console.log(isMap(new Set())); // false console.log(isMap(new WeakMap())); // false console.log(isMap({})); // false console.log(isMap([])); // false console.log(isMap(null)); // false ``` It can also be used as a type guard in TypeScript. ```typescript function processValue(value: unknown) { if (isMap(value)) { // Now value is narrowed to Map type console.log(value.size); value.set('new-key', 'new-value'); } } ``` #### Parameters * `value` (`unknown`): The value to check if it's a `Map`. #### Returns (`value is Map`): Returns `true` if the value is a Map, `false` otherwise. --- --- url: /reference/compat/predicate/isMap.md --- # isMap (Lodash Compatibility) ::: warning Use `es-toolkit`'s [isMap](../../predicate/isMap.md) instead This `isMap` function operates slowly due to complex handling for Lodash compatibility. Use the faster and more modern `es-toolkit`'s [isMap](../../predicate/isMap.md) instead. ::: Checks if a value is a Map. ```typescript const result = isMap(value); ``` ## Usage ### `isMap(value)` Use `isMap` when you want to type-safely check if a value is a Map. It also works as a type guard in TypeScript. ```typescript import { isMap } from 'es-toolkit/compat'; // Map checking const map = new Map(); isMap(map); // true // Other types return false isMap(new Set()); // false isMap(new WeakMap()); // false isMap({}); // false isMap([]); // false isMap('map'); // false isMap(123); // false isMap(null); // false isMap(undefined); // false ``` It also distinguishes from other similar collections. ```typescript import { isMap } from 'es-toolkit/compat'; // Map vs Set vs WeakMap isMap(new Map([['key', 'value']])); // true isMap(new Set(['value'])); // false isMap(new WeakMap()); // false // Map vs regular objects isMap({}); // false isMap({ key: 'value' }); // false isMap(Object.create(null)); // false ``` #### Parameters * `value` (`unknown`): The value to check if it's a Map. #### Returns (`value is Map`): Returns `true` if the value is a Map, `false` otherwise. --- --- url: /reference/compat/predicate/isMatch.md --- # isMatch (Lodash Compatibility) Checks if an object partially matches another object's shape and values. ```typescript const result = isMatch(target, source); ``` ## Usage ### `isMatch(target, source)` Use `isMatch` when you need to check if an object or array partially matches another object's structure and values. They don't need to be completely identical - all properties of source must exist in target with the same values. ```typescript import { isMatch } from 'es-toolkit/compat'; // Object partial matching isMatch({ a: 1, b: 2, c: 3 }, { a: 1, b: 2 }); // true (a, b match) isMatch({ a: 1, b: 2 }, { a: 1, b: 2, c: 3 }); // false (c is not in target) // Nested objects isMatch({ user: { name: 'Alice', age: 25, city: 'Seoul' } }, { user: { name: 'Alice', age: 25 } }); // true // Array partial matching (order independent) isMatch([1, 2, 3, 4], [2, 4]); // true (2 and 4 are in the array) isMatch([1, 2, 3], [1, 2, 3]); // true (complete match) isMatch([1, 2], [1, 2, 3]); // false (3 is not in target) // Map partial matching const targetMap = new Map([ ['a', 1], ['b', 2], ['c', 3], ]); const sourceMap = new Map([ ['a', 1], ['b', 2], ]); isMatch(targetMap, sourceMap); // true // Set partial matching const targetSet = new Set([1, 2, 3, 4]); const sourceSet = new Set([2, 4]); isMatch(targetSet, sourceSet); // true // Empty source always returns true isMatch({ a: 1 }, {}); // true isMatch([1, 2, 3], []); // true ``` More direct and faster alternatives: ```typescript // Complete equality check (faster) import { isEqual } from 'es-toolkit'; isEqual(obj1, obj2); // Specific property checks (clearer) target.a === source.a && target.b === source.b; // Object structure check Object.keys(source).every(key => target[key] === source[key]); ``` #### Parameters * `target` (`unknown`): The object to check for matching. * `source` (`unknown`): The object serving as the match pattern. #### Returns (`boolean`): Returns `true` if target partially matches source's shape and values, else `false`. --- --- url: /reference/compat/predicate/isMatchWith.md --- # isMatchWith (Lodash Compatibility) Checks if an object partially matches using a custom comparison function. ```typescript const result = isMatchWith(target, source, customizer); ``` ## Usage ### `isMatchWith(target, source, customizer)` Use `isMatchWith` when you need custom comparison logic. You have direct control over how each property is compared. ```typescript import { isMatchWith } from 'es-toolkit/compat'; // Case-insensitive string comparison const caseInsensitiveCompare = (objVal, srcVal) => { if (typeof objVal === 'string' && typeof srcVal === 'string') { return objVal.toLowerCase() === srcVal.toLowerCase(); } return undefined; // Use default behavior }; isMatchWith({ name: 'ALICE', age: 25 }, { name: 'alice' }, caseInsensitiveCompare); // true // Number range comparison const rangeCompare = (objVal, srcVal, key) => { if (key === 'age' && typeof srcVal === 'object' && srcVal.min !== undefined) { return objVal >= srcVal.min && objVal <= srcVal.max; } return undefined; }; isMatchWith({ name: 'John', age: 25 }, { age: { min: 18, max: 30 } }, rangeCompare); // true // Array length comparison const lengthCompare = (objVal, srcVal, key) => { if (key === 'items' && Array.isArray(objVal) && typeof srcVal === 'number') { return objVal.length === srcVal; } return undefined; }; isMatchWith({ items: ['a', 'b', 'c'], count: 3 }, { items: 3 }, lengthCompare); // true // Complex conditional comparison const conditionalCompare = (objVal, srcVal, key, object, source) => { // Apply special logic only to specific keys if (key === 'status') { return srcVal === 'active' || objVal === 'any'; } // Special handling in nested objects if (typeof srcVal === 'object' && srcVal !== null && objVal?.special) { return srcVal.id === objVal.special; } return undefined; // Default behavior }; isMatchWith({ user: { special: 123 }, status: 'any' }, { user: { id: 123, status: 'active' } }, conditionalCompare); // true ``` #### Parameters * `target` (`unknown`): The object to check for matching. * `source` (`unknown`): The object serving as the match pattern. * `customizer` (`function`, optional): Function to customize comparison logic. Should return `true`, `false`, or `undefined`. #### Returns (`boolean`): Returns `true` if target partially matches source using custom logic, else `false`. --- --- url: /reference/compat/predicate/isNaN.md --- # isNaN (Lodash Compatibility) ::: warning Use `Number.isNaN` This `isNaN` function operates slowly due to additional function calls. Instead, use the faster and modern `Number.isNaN`. ::: Checks if a value is `NaN`. ```typescript const result = isNaN(value); ``` ## Usage ### `isNaN(value)` Use `isNaN` when you want to check if a value is `NaN`. ```typescript import { isNaN } from 'es-toolkit/compat'; // NaN checks isNaN(NaN); // Returns: true isNaN(Number.NaN); // Returns: true // Other values isNaN(undefined); // Returns: false isNaN(null); // Returns: false isNaN(0); // Returns: false isNaN('NaN'); // Returns: false ``` #### Parameters * `value` (`unknown`): The value to check if it's NaN. #### Returns (`boolean`): Returns `true` if the value is NaN, otherwise `false`. --- --- url: /reference/compat/predicate/isNative.md --- # isNative (Lodash Compatibility) Checks if a value is a native function of the JavaScript engine. ```typescript const result = isNative(value); ``` ## Usage ### `isNative(value)` Use `isNative` when you need to check if a given value is a native function implemented in the JavaScript engine. You can distinguish built-in functions provided by browsers or Node.js. ```typescript import { isNative } from 'es-toolkit/compat'; // Native functions isNative(Array.prototype.push); // true isNative(Object.keys); // true isNative(Math.max); // true isNative(JSON.parse); // true isNative(console.log); // true (in browser/Node.js environment) // User-defined functions isNative(function () {}); // false isNative(() => {}); // false isNative(function customFunction() {}); // false // Library functions isNative(require('lodash').map); // false isNative(require('es-toolkit').chunk); // false // Non-function values isNative({}); // false isNative([]); // false isNative('function'); // false isNative(123); // false isNative(null); // false // Bound functions const boundFunction = Array.prototype.push.bind([]); isNative(boundFunction); // true (bound functions are native) // Methods const obj = { method: Array.prototype.push }; isNative(obj.method); // true (still a native function) ``` #### Parameters * `value` (`any`): The value to check. #### Returns (`boolean`): Returns `true` if the value appears to be a native function, otherwise `false`. --- --- url: /reference/predicate/isNil.md --- # isNil Checks if a value is `null` or `undefined`. ```typescript const result = isNil(value); ``` ## Usage ### `isNil(value)` Use `isNil` when you want to check if a value is `null` or `undefined`. ```typescript import { isNil } from 'es-toolkit/predicate'; // null or undefined values console.log(isNil(null)); // true console.log(isNil(undefined)); // true // Other values console.log(isNil(0)); // false console.log(isNil('')); // false console.log(isNil(false)); // false console.log(isNil([])); // false console.log(isNil({})); // false ``` It can also be used as a type guard in TypeScript: ```typescript function processValue(value: string | null | undefined) { if (isNil(value)) { // value is now narrowed to null | undefined console.log('Value is empty'); } else { // value is narrowed to string console.log(value.toUpperCase()); } } ``` #### Parameters * `value` (`unknown`): The value to check if it's `null` or `undefined`. #### Returns (`value is null | undefined`): Returns `true` if the value is `null` or `undefined`, `false` otherwise. --- --- url: /reference/compat/predicate/isNil.md --- # isNil (Lodash Compatibility) ::: warning Use `es-toolkit`'s [isNil](../../predicate/isNil.md) instead This `isNil` function operates slowly due to complex handling for Lodash compatibility. Use the faster and more modern `es-toolkit`'s [isNil](../../predicate/isNil.md) instead. ::: Checks if a value is `null` or `undefined`. ```typescript const result = isNil(value); ``` ## Usage ### `isNil(x)` Use `isNil` when you want to type-safely check if a value is `null` or `undefined`. It also works as a type guard in TypeScript. ```typescript import { isNil } from 'es-toolkit/compat'; // null and undefined return true isNil(null); // true isNil(undefined); // true // All other values return false isNil(0); // false isNil(''); // false isNil(false); // false isNil([]); // false isNil({}); // false isNil('hello'); // false isNil(42); // false ``` It distinguishes from values that are truthy but not `null` or `undefined`. ```typescript import { isNil } from 'es-toolkit/compat'; // Values that are falsy but not null/undefined isNil(0); // false isNil(''); // false isNil(false); // false isNil(NaN); // false // Only null and undefined return true isNil(null); // true isNil(undefined); // true ``` #### Parameters * `x` (`any`): The value to check if it's `null` or `undefined`. #### Returns (`x is null | undefined`): Returns `true` if the value is `null` or `undefined`, `false` otherwise. --- --- url: /reference/predicate/isNode.md --- # isNode Checks if the current runtime environment is Node.js. ```typescript const result = isNode(); ``` ## Usage ### `isNode()` Use `isNode` when you want to check if the current code is running in a Node.js environment. It's useful for verifying the environment before using Node.js-specific APIs. ```typescript import { isNode } from 'es-toolkit/predicate'; if (isNode()) { // Node.js-specific code console.log('This code is running in Node.js'); const fs = await import('node:fs'); const path = await import('node:path'); } else { // Browser-only code console.log('This code is running in a browser'); const response = await fetch('/api/data'); } ``` It's also useful when conditionally using Node.js modules: ```typescript function getEnvironmentInfo() { if (isNode()) { return { platform: process.platform, nodeVersion: process.version, environment: 'Node.js', }; } else { return { userAgent: navigator.userAgent, environment: 'Browser', }; } } ``` #### Returns (`boolean`): Returns `true` if the current environment is Node.js, `false` otherwise. --- --- url: /reference/predicate/isNotNil.md --- # isNotNil Checks if a value is neither `null` nor `undefined`. ```typescript const result = isNotNil(value); ``` ## Usage ### `isNotNil(value)` Use `isNotNil` when you want to check if a value is neither `null` nor `undefined`. It's particularly useful for filtering out `null` or `undefined` values from arrays. ```typescript import { isNotNil } from 'es-toolkit/predicate'; // Basic usage console.log(isNotNil(42)); // true console.log(isNotNil('hello')); // true console.log(isNotNil([])); // true console.log(isNotNil({})); // true console.log(isNotNil(null)); // false console.log(isNotNil(undefined)); // false // Useful for array filtering const mixedArray = [1, null, 'hello', undefined, true, 0]; const filteredArray = mixedArray.filter(isNotNil); // filteredArray becomes [1, 'hello', true, 0] (null and undefined removed) ``` It can also be used as a type guard in TypeScript. ```typescript function processItems(items: (string | null | undefined)[]) { // Filtering with isNotNil narrows the type to string[] const validItems = items.filter(isNotNil); validItems.forEach(item => { // item is now guaranteed to be of type string console.log(item.toUpperCase()); }); } ``` #### Parameters * `value` (`T | null | undefined`): The value to check if it's neither `null` nor `undefined`. #### Returns (`value is T`): Returns `true` if the value is neither `null` nor `undefined`, `false` otherwise. --- --- url: /reference/predicate/isNull.md --- # isNull Checks if a value is `null`. ```typescript const result = isNull(value); ``` ## Usage ### `isNull(value)` Use `isNull` when you want to check if a value is exactly `null`. It uses strict equality (`===`) to recognize only `null` and not undefined. ```typescript import { isNull } from 'es-toolkit/predicate'; // null value console.log(isNull(null)); // true // Non-null values console.log(isNull(undefined)); // false console.log(isNull(0)); // false console.log(isNull('')); // false console.log(isNull(false)); // false console.log(isNull([])); // false console.log(isNull({})); // false ``` It can also be used as a type guard in TypeScript. ```typescript function processValue(value: string | null | undefined) { if (isNull(value)) { // value is now narrowed to null console.log('Value is null'); } else { // value is narrowed to string | undefined console.log('Value is not null:', value); } } ``` `isNull` is different from [`isNil`](./isNil.md) in that it treats `undefined` as `false`. ```typescript import { isNil, isNull } from 'es-toolkit/predicate'; console.log(isNull(undefined)); // false console.log(isNil(undefined)); // true ``` #### Parameters * `value` (`unknown`): The value to check if it's `null`. #### Returns (`value is null`): Returns `true` if the value is `null`, `false` otherwise. --- --- url: /reference/compat/predicate/isNull.md --- # isNull (Lodash Compatibility) ::: warning Use `es-toolkit`'s [isNull](../../predicate/isNull.md) instead This `isNull` function is a Lodash compatibility function, but has the same implementation as the main library. Use the faster and more modern `es-toolkit`'s [isNull](../../predicate/isNull.md) instead. ::: Checks if a value is `null`. ```typescript const result = isNull(value); ``` ## Usage ### `isNull(value)` Use `isNull` when you want to type-safely check if a value is exactly `null`. It also works as a type guard in TypeScript. ```typescript import { isNull } from 'es-toolkit/compat'; // Only null returns true isNull(null); // true // undefined also returns false isNull(undefined); // false // All other values also return false isNull(0); // false isNull(''); // false isNull(false); // false isNull([]); // false isNull({}); // false isNull('null'); // false isNull(NaN); // false ``` You can distinguish between `null` and `undefined`. ```typescript import { isNull } from 'es-toolkit/compat'; function handleValue(value: string | null | undefined) { if (isNull(value)) { console.log('Value is explicitly null'); } else if (value === undefined) { console.log('Value is undefined'); } else { console.log(`Value exists: ${value}`); } } handleValue(null); // "Value is explicitly null" handleValue(undefined); // "Value is undefined" handleValue('hello'); // "Value exists: hello" ``` #### Parameters * `value` (`any`): The value to check if it's `null`. #### Returns (`value is null`): Returns `true` if the value is `null`, `false` otherwise. --- --- url: /reference/predicate/isNumber.md --- # isNumber Checks if a value is a number type. ```typescript const result = isNumber(value); ``` ## Usage ### `isNumber(value)` Use `isNumber` when you want to check if a value is a number. ```typescript import { isNumber } from 'es-toolkit'; // Checking basic number values isNumber(123); // true isNumber(3.14); // true isNumber(NaN); // true isNumber(Infinity); // true // Distinguishing from other types isNumber('123'); // false isNumber(true); // false isNumber(null); // false isNumber(undefined); // false ``` Particularly useful when used as a type guard in TypeScript. ```typescript import { isNumber } from 'es-toolkit'; function processValue(value: unknown) { if (isNumber(value)) { // value is narrowed to number console.log(value * 2); } else { console.log('Not a number'); } } ``` #### Parameters * `value` (`unknown`): The value to check if it's a number type. #### Returns (`value is number`): Returns `true` if the value is a number, `false` otherwise. --- --- url: /reference/compat/predicate/isNumber.md --- # isNumber (Lodash Compatibility) ::: warning Use `typeof` operator This `isNumber` function is complex due to handling Number object wrappers. Instead, use the simpler and modern `typeof value === 'number'`. ::: Checks if a value is a number. ```typescript const result = isNumber(value); ``` ## Usage ### `isNumber(value)` Use `isNumber` when you want to check if a value is a number. This function recognizes both primitive numbers and Number objects as numbers. ```typescript import { isNumber } from 'es-toolkit/compat'; // Primitive numbers isNumber(123); // Returns: true isNumber(3.14); // Returns: true isNumber(NaN); // Returns: true // Number objects isNumber(new Number(42)); // Returns: true // Other types isNumber('123'); // Returns: false isNumber(true); // Returns: false isNumber(null); // Returns: false ``` #### Parameters * `value` (`unknown`): The value to check if it's a number. #### Returns (`value is number`): Returns `true` if the value is a number, otherwise `false`. --- --- url: /reference/compat/predicate/isObject.md --- # isObject (Lodash Compatibility) Checks if a value is an object. ```typescript const result = isObject(value); ``` ## Usage ### `isObject(value)` Use `isObject` when you want to check if a value is an object. In JavaScript, arrays, functions, objects, regular expressions, dates, etc. are all treated as objects. ```typescript import { isObject } from 'es-toolkit/compat'; // Plain objects isObject({}); // Returns: true // Arrays are also objects isObject([1, 2, 3]); // Returns: true // Functions are also objects isObject(() => {}); // Returns: true // Dates are also objects isObject(new Date()); // Returns: true // null is not an object isObject(null); // Returns: false // Primitive types are not objects isObject('string'); // Returns: false isObject(123); // Returns: false ``` #### Parameters * `value` (`unknown`): The value to check if it's an object. #### Returns (`value is object`): Returns `true` if the value is an object, otherwise `false`. --- --- url: /reference/compat/predicate/isObjectLike.md --- # isObjectLike (Lodash Compatibility) Checks if a value is object-like. ```typescript const result = isObjectLike(value); ``` ## Usage ### `isObjectLike(value)` Use `isObjectLike` when you need to check if a given value is object-like. An object-like value is a value where the result of the `typeof` operation is `'object'` and is not `null`. ```typescript import { isObjectLike } from 'es-toolkit/compat'; // Object-like values isObjectLike({ a: 1 }); // true isObjectLike([1, 2, 3]); // true isObjectLike(new Date()); // true isObjectLike(/regex/); // true isObjectLike(new Map()); // true isObjectLike(new Set()); // true // Non object-like values isObjectLike('abc'); // false isObjectLike(123); // false isObjectLike(true); // false isObjectLike(() => {}); // false isObjectLike(Symbol('sym')); // false // Special cases isObjectLike(null); // false (null has typeof 'object' but is not object-like) isObjectLike(undefined); // false ``` #### Parameters * `value` (`any`): The value to check. #### Returns (`boolean`): Returns `true` if the value is object-like, otherwise `false`. --- --- url: /reference/predicate/isPlainObject.md --- # isPlainObject Checks if a value is a plain object. ```typescript const result = isPlainObject(value); ``` ## Usage ### `isPlainObject(value)` Use `isPlainObject` when you want to check if a value is a plain object. A plain object is an object created with an object literal (`{}`) or the `Object` constructor. Class instances, arrays, or other special objects are not plain objects. ```typescript import { isPlainObject } from 'es-toolkit/predicate'; // Plain objects console.log(isPlainObject({})); // true console.log(isPlainObject({ name: 'John', age: 30 })); // true console.log(isPlainObject(Object.create(null))); // true console.log(isPlainObject(new Object())); // true // Non-plain objects console.log(isPlainObject([])); // false (array) console.log(isPlainObject(new Date())); // false (Date object) console.log(isPlainObject(new Set())); // false (Set object) console.log(isPlainObject(new Map())); // false (Map object) console.log(isPlainObject(null)); // false (null) console.log(isPlainObject(42)); // false (number) console.log(isPlainObject('hello')); // false (string) // Class instances class MyClass {} console.log(isPlainObject(new MyClass())); // false ``` It's useful when serializing data or validating configuration objects. ```typescript function processConfig(config: unknown) { if (isPlainObject(config)) { // config is now narrowed to Record console.log('Valid configuration object'); Object.keys(config).forEach(key => { console.log(`${key}: ${config[key]}`); }); } else { throw new Error('Configuration must be a plain object'); } } ``` #### Parameters * `value` (`unknown`): The value to check if it's a plain object. #### Returns (`value is Record`): Returns `true` if the value is a plain object, `false` otherwise. ## Performance Comparison | | [Bundle Size](../../bundle-size.md) | [Runtime Performance](../../performance.md) | | ----------------- | ----------------------------------- | ------------------------------------------- | | es-toolkit | 279 bytes (82.4% smaller) | 1,505,684 times (1.70× faster) | | es-toolkit/compat | 435 bytes (72.5% smaller) | 2,013,760 times (2.28× faster) | | lodash-es | 1,586 bytes | 882,669 times | --- --- url: /reference/compat/predicate/isPlainObject.md --- # isPlainObject (Lodash Compatibility) ::: warning Use `es-toolkit`'s [isPlainObject](../../predicate/isPlainObject.md) instead This `isPlainObject` function operates slowly due to complex handling for Lodash compatibility. Use the faster and more modern `es-toolkit`'s [isPlainObject](../../predicate/isPlainObject.md) instead. ::: Checks if a value is a plain object. ```typescript const result = isPlainObject(object); ``` ## Usage ### `isPlainObject(object)` Use `isPlainObject` when you want to check if a value is a plain object. A plain object is an object created by the `{}` literal, `new Object()`, or `Object.create(null)`. It also works as a type guard in TypeScript. ```typescript import { isPlainObject } from 'es-toolkit/compat'; // Plain objects isPlainObject({}); // true isPlainObject(new Object()); // true isPlainObject(Object.create(null)); // true isPlainObject({ name: 'John', age: 30 }); // true // Not plain objects isPlainObject([]); // false (array) isPlainObject(new Date()); // false (Date instance) isPlainObject(new Map()); // false (Map instance) isPlainObject(new Set()); // false (Set instance) isPlainObject(/regex/); // false (regular expression) isPlainObject(function () {}); // false (function) isPlainObject(null); // false isPlainObject(undefined); // false isPlainObject('object'); // false (string) isPlainObject(42); // false (number) ``` It distinguishes between class instances and plain objects. ```typescript import { isPlainObject } from 'es-toolkit/compat'; class Person { name: string; constructor(name: string) { this.name = name; } } const person = new Person('John'); const plainObj = { name: 'John' }; isPlainObject(person); // false (class instance) isPlainObject(plainObj); // true (plain object) ``` It also correctly handles custom `Symbol.toStringTag` properties. ```typescript import { isPlainObject } from 'es-toolkit/compat'; // Writable Symbol.toStringTag const obj1 = {}; obj1[Symbol.toStringTag] = 'CustomObject'; isPlainObject(obj1); // true // Read-only Symbol.toStringTag (built-in objects) const date = new Date(); isPlainObject(date); // false ``` #### Parameters * `object` (`any`): The value to check if it's a plain object. #### Returns (`boolean`): Returns `true` if the value is a plain object, `false` otherwise. --- --- url: /reference/predicate/isPrimitive.md --- # isPrimitive Checks if a given value is a JavaScript primitive. ```typescript const result = isPrimitive(value); ``` ## Usage ### `isPrimitive(value)` Use `isPrimitive` when you want to check if a value is a JavaScript primitive. JavaScript primitives include `null`, `undefined`, strings, numbers, booleans, symbols, and `BigInt`. It's useful for distinguishing from reference types like objects or functions. ```typescript import { isPrimitive } from 'es-toolkit/predicate'; // Primitive values console.log(isPrimitive(null)); // true console.log(isPrimitive(undefined)); // true console.log(isPrimitive('hello')); // true console.log(isPrimitive(42)); // true console.log(isPrimitive(true)); // true console.log(isPrimitive(false)); // true console.log(isPrimitive(Symbol('test'))); // true console.log(isPrimitive(123n)); // true // Reference types (not primitives) console.log(isPrimitive({})); // false console.log(isPrimitive([])); // false console.log(isPrimitive(new Date())); // false console.log(isPrimitive(new Map())); // false console.log(isPrimitive(new Set())); // false console.log(isPrimitive(() => {})); // false console.log(isPrimitive(/regex/)); // false ``` It's useful when implementing deep copy logic. ```typescript // Handle primitives and objects differently function deepClone(value: any): any { if (isPrimitive(value)) { // Return primitives as-is return value; } // Perform cloning logic for objects if (Array.isArray(value)) { return value.map(deepClone); } const result: any = {}; for (const key in value) { result[key] = deepClone(value[key]); } return result; } // Use in value comparison function isEqual(a: unknown, b: unknown): boolean { if (isPrimitive(a) && isPrimitive(b)) { return a === b; } // Complex object comparison logic... return false; } // Safe string conversion for logging function safeLog(value: unknown) { if (isPrimitive(value)) { console.log('Primitive value:', value); } else { console.log('Object:', typeof value, Object.prototype.toString.call(value)); } } ``` You can use it as a type guard to write safe code. ```typescript function processValue(input: unknown) { if (isPrimitive(input)) { // TypeScript infers input as a primitive type console.log('Type of primitive:', typeof input); console.log('Primitive value:', input); return input; } // Here input is inferred as an object type console.log('It is an object type'); return null; } // API response validation function validateApiResponse(data: unknown) { if (isPrimitive(data)) { return { type: 'primitive', value: data, serializable: true, }; } return { type: 'object', value: data, serializable: false, // Needs additional validation }; } // Configuration value processing function normalizeConfigValue(value: unknown) { if (isPrimitive(value)) { // Primitives can be safely converted to strings return String(value); } // Serialize objects as JSON try { return JSON.stringify(value); } catch { return '[Complex Object]'; } } ``` You can distinguish wrapper objects like `String`, `Number`, `Boolean` from primitive values. ```typescript // Wrapper objects are not primitives console.log(isPrimitive(new String('hello'))); // false console.log(isPrimitive(new Number(42))); // false console.log(isPrimitive(new Boolean(true))); // false // But actual primitives are true console.log(isPrimitive('hello')); // true console.log(isPrimitive(42)); // true console.log(isPrimitive(true)); // true // You can extract primitive values with valueOf() const strObj = new String('hello'); console.log(isPrimitive(strObj.valueOf())); // true ``` #### Parameters * `value` (`unknown`): The value to check if it's a JavaScript primitive. #### Returns (`value is null | undefined | string | number | boolean | symbol | bigint`): Returns `true` if the value is a primitive, `false` otherwise. --- --- url: /reference/predicate/isPromise.md --- # isPromise Checks if a given value is a `Promise` instance. ```typescript const result = isPromise(value); ``` ## Usage ### `isPromise(value)` Use `isPromise` when you want to check if a value is a `Promise` instance. It's useful when you need to distinguish `Promise` objects from other values in asynchronous code, or when you need to conditionally use `await`. ```typescript import { isPromise } from 'es-toolkit/predicate'; // Promise instances const promise1 = new Promise(resolve => resolve('done')); const promise2 = Promise.resolve(42); const promise3 = Promise.reject(new Error('failed')); console.log(isPromise(promise1)); // true console.log(isPromise(promise2)); // true console.log(isPromise(promise3)); // true // Non-Promise values console.log(isPromise({})); // false console.log(isPromise('hello')); // false console.log(isPromise(42)); // false console.log(isPromise(null)); // false console.log(isPromise(undefined)); // false ``` It's useful when executing logic conditionally in asynchronous functions. ```typescript // Check if value is a Promise and handle appropriately async function processValue(input: unknown) { if (isPromise(input)) { // TypeScript infers input as Promise const result = await input; console.log('Promise result:', result); return result; } // Non-Promise values are returned immediately console.log('Regular value:', input); return input; } // Handle API responses function handleApiCall(response: unknown) { if (isPromise(response)) { return response.then(data => ({ success: true, data })).catch(error => ({ success: false, error: error.message })); } // Already resolved value return { success: true, data: response }; } // Use in utility function function toPromise(value: T | Promise): Promise { if (isPromise(value)) { return value; } return Promise.resolve(value); } ``` You can distinguish between Promise-like objects and actual Promises. ```typescript // thenable objects are not Promises const thenable = { then: (resolve: Function) => resolve('not a promise'), }; console.log(isPromise(thenable)); // false // async function results are Promises async function asyncFunction() { return 'async result'; } console.log(isPromise(asyncFunction())); // true // Regular functions are not Promises function normalFunction() { return 'normal result'; } console.log(isPromise(normalFunction())); // false ``` It can also be used for error handling. ```typescript function safeExecute(fn: () => any) { try { const result = fn(); if (isPromise(result)) { return result.catch(error => { console.error('Error in async function:', error); return null; }); } return result; } catch (error) { console.error('Error in sync function:', error); return null; } } // Timeout handling function withTimeout(valueOrPromise: T | Promise, timeoutMs: number) { if (!isPromise(valueOrPromise)) { return valueOrPromise; } const timeoutPromise = new Promise((_, reject) => { setTimeout(() => reject(new Error('Timeout')), timeoutMs); }); return Promise.race([valueOrPromise, timeoutPromise]); } ``` #### Parameters * `value` (`unknown`): The value to check if it's a Promise instance. #### Returns (`value is Promise`): Returns `true` if the value is a Promise instance, `false` otherwise. --- --- url: /reference/predicate/isRegExp.md --- # isRegExp Checks if a given value is a `RegExp` instance. ```typescript const result = isRegExp(value); ``` ## Usage ### `isRegExp(value)` Use `isRegExp` when you want to check if a value is a `RegExp` instance. It's useful for distinguishing regular expression objects from regular strings or other objects. ```typescript import { isRegExp } from 'es-toolkit/predicate'; // RegExp instances const regex1 = /abc/; const regex2 = new RegExp('abc'); const regex3 = new RegExp('\\d+', 'g'); console.log(isRegExp(regex1)); // true console.log(isRegExp(regex2)); // true console.log(isRegExp(regex3)); // true // Non-RegExp values console.log(isRegExp('/abc/')); // false (string) console.log(isRegExp('abc')); // false console.log(isRegExp({})); // false console.log(isRegExp(null)); // false console.log(isRegExp(undefined)); // false ``` Useful for regex pattern validation or string processing: ```typescript // Dynamic pattern validation function validatePattern(pattern: unknown, text: string) { if (isRegExp(pattern)) { // TypeScript infers pattern as RegExp return pattern.test(text); } // Convert string patterns to regex if (typeof pattern === 'string') { const regex = new RegExp(pattern); return regex.test(text); } return false; } // Usage examples console.log(validatePattern(/hello/, 'hello world')); // true console.log(validatePattern('\\d+', '123')); // true console.log(validatePattern('invalid', 'text')); // false // Use in form validation function createValidator(rule: unknown) { if (isRegExp(rule)) { return (value: string) => rule.test(value); } // Other rule types... return () => false; } // Create email validator const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; const emailValidator = createValidator(emailRegex); console.log(emailValidator('test@example.com')); // true console.log(emailValidator('invalid-email')); // false ``` Use in conditional string processing: ```typescript // Text processing utility function processText(input: string, processor: unknown) { if (isRegExp(processor)) { // Extract matching parts with regex const matches = input.match(processor); return matches ? matches : []; } // Other processor types... return [input]; } // Extract numbers const numberRegex = /\d+/g; const numbers = processText('Price: 1000 won, Discount: 200 won', numberRegex); console.log(numbers); // ['1000', '200'] // Extract URLs const urlRegex = /https?:\/\/[^\s]+/g; const urls = processText('Website: https://example.com reference', urlRegex); console.log(urls); // ['https://example.com'] // Configuration-based text validation class TextValidator { private rules: Array<{ name: string; rule: unknown }> = []; addRule(name: string, rule: unknown) { this.rules.push({ name, rule }); } validate(text: string) { const results: Array<{ rule: string; passed: boolean }> = []; for (const { name, rule } of this.rules) { if (isRegExp(rule)) { results.push({ rule: name, passed: rule.test(text), }); } else { results.push({ rule: name, passed: false, }); } } return results; } } // Usage example const validator = new TextValidator(); validator.addRule('Letters only', /^[a-zA-Z]+$/); validator.addRule('Contains number', /\d/); validator.addRule('No special chars', /^[^!@#$%^&*()]+$/); console.log(validator.validate('Hello123')); // [ // { rule: 'Letters only', passed: false }, // { rule: 'Contains number', passed: true }, // { rule: 'No special chars', passed: true } // ] ``` Distinguishing between strings and regular expressions: ```typescript // Use in search functionality function searchText(content: string, query: unknown) { if (isRegExp(query)) { // Regex search - advanced pattern matching const matches = content.match(query); return matches ? matches.length : 0; } if (typeof query === 'string') { // Regular string search const regex = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'); const matches = content.match(regex); return matches ? matches.length : 0; } return 0; } // Usage examples const text = 'Hello world! Hello everyone!'; console.log(searchText(text, /hello/gi)); // 2 (regex) console.log(searchText(text, 'Hello')); // 2 (string, escaped) console.log(searchText(text, /h.llo/i)); // 2 (pattern matching) // Dynamic filtering function createFilter(patterns: unknown[]) { const regexPatterns = patterns.filter(isRegExp); return (text: string) => { return regexPatterns.some(pattern => pattern.test(text)); }; } // Spam filter example const spamPatterns = [ /\b(ad|promo)\b/, /\d{3}-\d{4}-\d{4}/, // Phone number pattern 'invalid', // Not a RegExp, excluded from filter /\$\d+/, // Price pattern ]; const spamFilter = createFilter(spamPatterns); console.log(spamFilter('Urgent ad!')); // true console.log(spamFilter('Hello')); // false ``` Using regex flags and properties: ```typescript // Check RegExp properties function analyzeRegex(value: unknown) { if (isRegExp(value)) { return { source: value.source, flags: value.flags, global: value.global, ignoreCase: value.ignoreCase, multiline: value.multiline, unicode: value.unicode, sticky: value.sticky, }; } return null; } // Usage example const regex = /hello/gim; const analysis = analyzeRegex(regex); console.log(analysis); // { // source: 'hello', // flags: 'gim', // global: true, // ignoreCase: true, // multiline: true, // unicode: false, // sticky: false // } // Clone regex function cloneRegex(value: unknown) { if (isRegExp(value)) { return new RegExp(value.source, value.flags); } return null; } const originalRegex = /test/gi; const clonedRegex = cloneRegex(originalRegex); console.log(clonedRegex?.test('TEST')); // true ``` #### Parameters * `value` (`unknown`): The value to check if it's a RegExp instance. #### Returns (`value is RegExp`): Returns `true` if the value is a RegExp instance, `false` otherwise. --- --- url: /reference/compat/predicate/isRegExp.md --- # isRegExp (Lodash Compatibility) ::: warning Use `es-toolkit`'s [isRegExp](../../predicate/isRegExp.md) instead This `isRegExp` function is a Lodash compatibility function, but is a simple type check. Use the faster and more modern `es-toolkit`'s [isRegExp](../../predicate/isRegExp.md) instead. ::: Checks if a value is a regular expression. ```typescript const result = isRegExp(value); ``` ## Usage ### `isRegExp(value)` Use `isRegExp` when you want to type-safely check if a value is a regular expression. It also works as a type guard in TypeScript. ```typescript import { isRegExp } from 'es-toolkit/compat'; // Regular expressions isRegExp(/abc/); // true isRegExp(new RegExp('abc')); // true isRegExp(/[a-z]+/g); // true isRegExp(/pattern/gi); // true // Other types return false isRegExp('/abc/'); // false (string) isRegExp('pattern'); // false (string) isRegExp({}); // false (object) isRegExp([]); // false (array) isRegExp(null); // false isRegExp(undefined); // false isRegExp(123); // false (number) ``` It distinguishes between regex strings and actual regex objects. ```typescript import { isRegExp } from 'es-toolkit/compat'; // Regular expression vs regex string isRegExp(/test/); // true isRegExp('/test/'); // false isRegExp('\\d+'); // false isRegExp('/\\d+/g'); // false // Various regex flags isRegExp(/test/i); // true (case insensitive) isRegExp(/test/g); // true (global search) isRegExp(/test/m); // true (multiline) isRegExp(/test/gim); // true (all flags combined) ``` It also recognizes dynamically created regular expressions. ```typescript import { isRegExp } from 'es-toolkit/compat'; // Regex created with RegExp constructor const dynamicRegex = new RegExp('\\d{3}-\\d{4}', 'g'); isRegExp(dynamicRegex); // true // Regex created through strings const pattern = 'hello'; const flags = 'gi'; const regex = new RegExp(pattern, flags); isRegExp(regex); // true ``` #### Parameters * `value` (`any`): The value to check if it's a regular expression. #### Returns (`value is RegExp`): Returns `true` if the value is a regular expression, `false` otherwise. --- --- url: /reference/compat/predicate/isSafeInteger.md --- # isSafeInteger (Lodash Compatibility) ::: warning Use `Number.isSafeInteger` This `isSafeInteger` function operates slowly due to additional type checking overhead. Instead, use the faster and modern `Number.isSafeInteger`. ::: Checks if a value is a safe integer. ```typescript const result = isSafeInteger(value); ``` ## Usage ### `isSafeInteger(value)` Use `isSafeInteger` when you need to check if a given value is a safe integer. A safe integer is an integer between -(2^53 - 1) and (2^53 - 1), which can be accurately represented in JavaScript. ```typescript import { isSafeInteger } from 'es-toolkit/compat'; // Safe integers isSafeInteger(3); // true isSafeInteger(-42); // true isSafeInteger(0); // true isSafeInteger(Number.MAX_SAFE_INTEGER); // true (9007199254740991) isSafeInteger(Number.MIN_SAFE_INTEGER); // true (-9007199254740991) // Unsafe integers isSafeInteger(Number.MAX_SAFE_INTEGER + 1); // false isSafeInteger(Number.MIN_SAFE_INTEGER - 1); // false isSafeInteger(9007199254740992); // false // Non-integer values isSafeInteger(3.14); // false isSafeInteger('3'); // false isSafeInteger(1n); // false (BigInt) isSafeInteger([]); // false isSafeInteger({}); // false isSafeInteger(null); // false isSafeInteger(undefined); // false // Infinity and NaN isSafeInteger(Infinity); // false isSafeInteger(-Infinity); // false isSafeInteger(NaN); // false ``` #### Parameters * `value` (`any`): The value to check. #### Returns (`value is number`) Returns `true` if the value is a safe integer, otherwise `false`.\ When `true`, TypeScript narrows the type of `value` to `number`. --- --- url: /reference/predicate/isSet.md --- # isSet Checks if a given value is a `Set` instance. ```typescript const result = isSet(value); ``` ## Usage ### `isSet(value)` Use `isSet` when you want to check if a value is a `Set` instance. It's useful for distinguishing `Set` objects from other objects. ```typescript import { isSet } from 'es-toolkit/predicate'; // Set instances const set1 = new Set(); const set2 = new Set([1, 2, 3]); const set3 = new Set(['a', 'b', 'c']); console.log(isSet(set1)); // true console.log(isSet(set2)); // true console.log(isSet(set3)); // true // Non-Set values console.log(isSet(new Map())); // false console.log(isSet(new WeakSet())); // false console.log(isSet([])); // false console.log(isSet({})); // false console.log(isSet(null)); // false console.log(isSet(undefined)); // false ``` Useful when executing different logic for JavaScript built-in objects like `Set`, `Array`, and `Map`. ```typescript // Calculate collection size function getCollectionSize(collection: unknown): number { if (isSet(collection)) { // TypeScript infers collection as Set return collection.size; } if (Array.isArray(collection)) { return collection.length; } if (collection && typeof collection === 'object') { return Object.keys(collection).length; } return 0; } // Usage examples console.log(getCollectionSize(new Set([1, 2, 3]))); // 3 console.log(getCollectionSize([1, 2, 3])); // 3 console.log(getCollectionSize({ a: 1, b: 2 })); // 2 // Deduplication utility function removeDuplicates(data: unknown) { if (isSet(data)) { // Already a Set, return as is return data; } if (Array.isArray(data)) { return new Set(data); } // Don't convert other types return data; } const duplicatedArray = [1, 2, 2, 3, 3, 3]; const uniqueSet = removeDuplicates(duplicatedArray); console.log(uniqueSet); // Set { 1, 2, 3 } const existingSet = new Set(['a', 'b']); console.log(removeDuplicates(existingSet)); // Set { 'a', 'b' } (same Set returned) ``` Can also be used extensively in Set manipulation and data transformation. ```typescript // Universal collection merging function mergeCollections(...collections: unknown[]): Set { const result = new Set(); for (const collection of collections) { if (isSet(collection)) { // Add all values from Set to result for (const item of collection) { result.add(item); } } else if (Array.isArray(collection)) { // Add all values from array for (const item of collection) { result.add(item); } } } return result; } // Usage examples const set1 = new Set([1, 2, 3]); const array1 = [3, 4, 5]; const set2 = new Set(['a', 'b']); const merged = mergeCollections(set1, array1, set2); console.log(merged); // Set { 1, 2, 3, 4, 5, 'a', 'b' } // Calculate collection intersection function getIntersection(coll1: unknown, coll2: unknown): Set { const set1 = isSet(coll1) ? coll1 : new Set(Array.isArray(coll1) ? coll1 : []); const set2 = isSet(coll2) ? coll2 : new Set(Array.isArray(coll2) ? coll2 : []); const intersection = new Set(); for (const item of set1) { if (set2.has(item)) { intersection.add(item); } } return intersection; } // Usage examples const setA = new Set([1, 2, 3, 4]); const arrayB = [3, 4, 5, 6]; const intersection = getIntersection(setA, arrayB); console.log(intersection); // Set { 3, 4 } ``` #### Parameters * `value` (`unknown`): The value to check if it's a Set instance. #### Returns (`value is Set`): Returns `true` if the value is a Set instance, `false` otherwise. --- --- url: /reference/compat/predicate/isSet.md --- # isSet (Lodash Compatibility) ::: warning Use `es-toolkit`'s [isSet](../../predicate/isSet.md) instead This `isSet` function is a Lodash compatibility function, but has the same implementation as the main library. Use the faster and more modern `es-toolkit`'s [isSet](../../predicate/isSet.md) instead. ::: Checks if a value is a Set. ```typescript const result = isSet(value); ``` ## Usage ### `isSet(value)` Use `isSet` when you want to type-safely check if a value is a Set. It also works as a type guard in TypeScript. ```typescript import { isSet } from 'es-toolkit/compat'; // Set checking const set = new Set(); isSet(set); // true // Other types return false isSet(new Map()); // false isSet(new WeakSet()); // false isSet([]); // false isSet({}); // false isSet('set'); // false isSet(123); // false isSet(null); // false isSet(undefined); // false ``` It also distinguishes from other similar collections. ```typescript import { isSet } from 'es-toolkit/compat'; // Set vs Map vs WeakSet isSet(new Set([1, 2, 3])); // true isSet(new Map([['key', 'value']])); // false isSet(new WeakSet()); // false // Set vs array isSet(new Set([1, 2, 3])); // true isSet([1, 2, 3]); // false // Set vs regular objects isSet(new Set()); // true isSet({}); // false isSet(Object.create(null)); // false ``` #### Parameters * `value` (`unknown`): The value to check if it's a Set. #### Returns (`value is Set`): Returns `true` if the value is a Set, `false` otherwise. --- --- url: /reference/predicate/isString.md --- # isString Checks if a given value is a string. ```typescript const result = isString(value); ``` ## Usage ### `isString(value)` Use `isString` when you want to check if a value is a string. It's useful for distinguishing string types from other primitive types or objects. ```typescript import { isString } from 'es-toolkit/predicate'; // String values console.log(isString('hello')); // true console.log(isString('')); // true console.log(isString('123')); // true console.log(isString('true')); // true // Non-string values console.log(isString(123)); // false console.log(isString(true)); // false console.log(isString(null)); // false console.log(isString(undefined)); // false console.log(isString([])); // false console.log(isString({})); // false console.log(isString(new String('hello'))); // false (String object) ``` Useful for data validation and type-safe string processing: ```typescript // Safe string manipulation function processText(input: unknown): string { if (isString(input)) { // TypeScript infers input as string return input.trim().toLowerCase(); } // Convert other types to string return String(input); } // Usage examples console.log(processText(' HELLO ')); // 'hello' console.log(processText(123)); // '123' console.log(processText(true)); // 'true' console.log(processText(null)); // 'null' // Form data validation function validateForm(data: Record) { const errors: string[] = []; if (!isString(data.name) || data.name.length === 0) { errors.push('Name is required'); } if (!isString(data.email) || !data.email.includes('@')) { errors.push('Please enter a valid email'); } return { isValid: errors.length === 0, errors, }; } // Usage examples console.log(validateForm({ name: 'John', email: 'john@example.com' })); // { isValid: true, errors: [] } console.log(validateForm({ name: 123, email: 'invalid-email' })); // { isValid: false, errors: ['Name is required', 'Please enter a valid email'] } ``` #### Parameters * `value` (`unknown`): The value to check if it's a string. #### Returns (`value is string`): Returns `true` if the value is a string, `false` otherwise. --- --- url: /reference/compat/predicate/isString.md --- # isString (Lodash Compatibility) ::: warning Use `typeof` operator instead This `isString` function is complex due to String object wrapper handling. Use the simpler and more modern `typeof value === 'string'` instead. ::: Checks if a value is a string. ```typescript const result = isString(value); ``` ## Usage ### `isString(value)` Use `isString` when you want to type-safely check if a value is a string. It checks both primitive strings and String object wrappers. It also works as a type guard in TypeScript. ```typescript import { isString } from 'es-toolkit/compat'; // Primitive strings isString('hello'); // true isString(''); // true isString('123'); // true // String object wrappers isString(new String('hello')); // true isString(new String('')); // true // Other types return false isString(123); // false isString(true); // false isString(null); // false isString(undefined); // false isString({}); // false isString([]); // false isString(Symbol('test')); // false ``` It distinguishes from other types that may look like strings. ```typescript import { isString } from 'es-toolkit/compat'; // String vs number isString('123'); // true isString(123); // false // String vs boolean isString('true'); // true isString(true); // false // String vs null/undefined isString('null'); // true isString(null); // false isString('undefined'); // true isString(undefined); // false ``` #### Parameters * `value` (`unknown`): The value to check if it's a string. #### Returns (`value is string`): Returns `true` if the value is a string, `false` otherwise. --- --- url: /reference/array/isSubset.md --- # isSubset Checks if one array is a subset of another array. ```typescript const result = isSubset(superset, subset); ``` ## Usage ### `isSubset(superset, subset)` Use `isSubset` when you want to check if all elements of one array are contained in another array. This is useful for verifying subset relationships or checking if permissions, features, tags, etc., are within the allowed range. ```typescript import { isSubset } from 'es-toolkit/array'; // Check subset in number arrays const numbers = [1, 2, 3, 4, 5]; const subset = [2, 3, 4]; isSubset(numbers, subset); // Returns: true // Check subset in string arrays const permissions = ['read', 'write', 'delete', 'admin']; const userPermissions = ['read', 'write']; isSubset(permissions, userPermissions); // Returns: true // When it's not a subset const colors = ['red', 'blue', 'green']; const invalidColors = ['red', 'yellow']; isSubset(colors, invalidColors); // Returns: false ``` Special cases are also handled correctly. ```typescript import { isSubset } from 'es-toolkit/array'; // An empty array is always a subset const anyArray = [1, 2, 3]; const emptyArray: number[] = []; isSubset(anyArray, emptyArray); // Returns: true // The same array is a subset of itself const same = ['a', 'b', 'c']; isSubset(same, same); // Returns: true // Works correctly even with duplicate elements const withDuplicates = [1, 2, 2, 3]; const duplicateSubset = [2, 2]; isSubset(withDuplicates, duplicateSubset); // Returns: true ``` #### Parameters * `superset` (`readonly T[]`): The superset array that may contain all elements of the subset. * `subset` (`readonly T[]`): The subset array to check if it's contained in the superset. #### Returns (`boolean`): Returns `true` if all elements of the subset are contained in the superset, otherwise returns `false`. --- --- url: /reference/array/isSubsetWith.md --- # isSubsetWith Checks if one array is a subset of another array based on a custom comparison function. ```typescript const result = isSubsetWith(superset, subset, areItemsEqual); ``` ## Usage ### `isSubsetWith(superset, subset, areItemsEqual)` Use `isSubsetWith` when you want to verify a subset relationship using a user-defined comparison function. This is useful when comparing objects or when special comparison logic is needed. ```typescript import { isSubsetWith } from 'es-toolkit/array'; // Check subset by object's id const users = [ { id: 1, name: 'john' }, { id: 2, name: 'jane' }, { id: 3, name: 'bob' }, ]; const targetUsers = [ { id: 2, name: 'jane' }, { id: 1, name: 'john' }, ]; isSubsetWith(users, targetUsers, (a, b) => a.id === b.id); // Returns: true // When it's not a subset const allUsers = [ { id: 1, name: 'john' }, { id: 2, name: 'jane' }, ]; const someUsers = [{ id: 3, name: 'bob' }]; isSubsetWith(allUsers, someUsers, (a, b) => a.id === b.id); // Returns: false ``` Complex comparison logic can also be used. ```typescript import { isSubsetWith } from 'es-toolkit/array'; // Case-insensitive string comparison const validNames = ['Alice', 'Bob', 'Charlie']; const userNames = ['alice', 'BOB']; isSubsetWith(validNames, userNames, (a, b) => a.toLowerCase() === b.toLowerCase()); // Returns: true // Number comparison within a range const validRanges = [1, 2, 3, 4, 5]; const testNumbers = [1.1, 2.8]; isSubsetWith(validRanges, testNumbers, (a, b) => Math.abs(a - b) < 0.5); // Returns: true (1.1 is close enough to 1, 2.8 is close enough to 3) ``` #### Parameters * `superset` (`readonly T[]`): The superset array that may contain all elements of the subset. * `subset` (`readonly T[]`): The subset array to check if it's contained in the superset. * `areItemsEqual` (`(x: T, y: T) => boolean`): A function to determine if two elements are equal. Should return `true` if equal, `false` otherwise. #### Returns (`boolean`): Based on the custom comparison function, returns `true` if all elements of the subset are contained in the superset, otherwise returns `false`. --- --- url: /reference/predicate/isSymbol.md --- # isSymbol Checks if a given value is a `symbol`. ```typescript const result = isSymbol(value); ``` ## Usage ### `isSymbol(value)` Use `isSymbol` when you want to check if a value is a `symbol`. ```typescript import { isSymbol } from 'es-toolkit/predicate'; // symbol values const sym1 = Symbol('description'); const sym2 = Symbol.for('global'); const sym3 = Symbol.iterator; console.log(isSymbol(sym1)); // true console.log(isSymbol(sym2)); // true console.log(isSymbol(sym3)); // true // Non-symbol values console.log(isSymbol('symbol')); // false console.log(isSymbol(123)); // false console.log(isSymbol(true)); // false console.log(isSymbol(null)); // false console.log(isSymbol(undefined)); // false console.log(isSymbol({})); // false console.log(isSymbol([])); // false ``` Useful for safely accessing object properties or managing metadata. ```typescript // Safe property access function getPropertyValue(obj: object, key: unknown) { if (isSymbol(key)) { // TypeScript infers key as symbol return (obj as any)[key]; } if (typeof key === 'string') { return (obj as any)[key]; } return undefined; } // Usage examples const mySymbol = Symbol('myKey'); const obj = { name: 'John', [mySymbol]: 'secret value', }; console.log(getPropertyValue(obj, 'name')); // 'John' console.log(getPropertyValue(obj, mySymbol)); // 'secret value' console.log(getPropertyValue(obj, 123)); // undefined // Metadata storage class MetadataManager { private metadata = new Map(); setMetadata(key: unknown, value: any): boolean { if (isSymbol(key)) { this.metadata.set(key, value); return true; } return false; } getMetadata(key: unknown): any { if (isSymbol(key)) { return this.metadata.get(key); } return undefined; } hasMetadata(key: unknown): boolean { if (isSymbol(key)) { return this.metadata.has(key); } return false; } } // Usage examples const manager = new MetadataManager(); const typeSymbol = Symbol('type'); const versionSymbol = Symbol('version'); manager.setMetadata(typeSymbol, 'user'); manager.setMetadata(versionSymbol, '1.0'); manager.setMetadata('invalid', 'value'); // false, not a symbol console.log(manager.getMetadata(typeSymbol)); // 'user' console.log(manager.hasMetadata(versionSymbol)); // true ``` #### Parameters * `value` (`unknown`): The value to check if it's a symbol. #### Returns (`value is symbol`): Returns `true` if the value is a symbol, `false` otherwise. --- --- url: /reference/compat/predicate/isSymbol.md --- # isSymbol (Lodash Compatibility) ::: warning Use `typeof` operator instead This `isSymbol` function is complex due to Symbol object wrapper handling. Use the simpler and more modern `typeof value === 'symbol'` instead. ::: Checks if a value is a symbol. ```typescript const result = isSymbol(value); ``` ## Usage ### `isSymbol(value)` Use `isSymbol` when you want to type-safely check if a value is a symbol. It checks both primitive symbols and Symbol object wrappers. It also works as a type guard in TypeScript. ```typescript import { isSymbol } from 'es-toolkit/compat'; // Primitive symbols isSymbol(Symbol('test')); // true isSymbol(Symbol.for('global')); // true isSymbol(Symbol.iterator); // true // Symbol object wrappers isSymbol(Object(Symbol('test'))); // true // Other types return false isSymbol('symbol'); // false isSymbol(123); // false isSymbol(true); // false isSymbol(null); // false isSymbol(undefined); // false isSymbol({}); // false isSymbol([]); // false ``` It also correctly recognizes various built-in symbols. ```typescript import { isSymbol } from 'es-toolkit/compat'; // Well-known symbols isSymbol(Symbol.iterator); // true isSymbol(Symbol.asyncIterator); // true isSymbol(Symbol.toStringTag); // true isSymbol(Symbol.hasInstance); // true isSymbol(Symbol.toPrimitive); // true // Global symbols isSymbol(Symbol.for('myGlobalSymbol')); // true // Custom symbols const mySymbol = Symbol('mySymbol'); isSymbol(mySymbol); // true ``` #### Parameters * `value` (`unknown`): The value to check if it's a symbol. #### Returns (`value is symbol`): Returns `true` if the value is a symbol, `false` otherwise. --- --- url: /reference/predicate/isTypedArray.md --- # isTypedArray Checks if a given value is a `TypedArray` instance. ```typescript const result = isTypedArray(value); ``` ## Usage ### `isTypedArray(value)` Use `isTypedArray` when you want to check if a value is a [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. ```typescript import { isTypedArray } from 'es-toolkit/predicate'; // TypedArray instances const uint8 = new Uint8Array([1, 2, 3]); const int16 = new Int16Array([1000, 2000]); const float32 = new Float32Array([1.5, 2.5]); const bigUint64 = new BigUint64Array([1n, 2n]); console.log(isTypedArray(uint8)); // true console.log(isTypedArray(int16)); // true console.log(isTypedArray(float32)); // true console.log(isTypedArray(bigUint64)); // true // Non-TypedArray values console.log(isTypedArray([1, 2, 3])); // false (regular array) console.log(isTypedArray(new ArrayBuffer(8))); // false (ArrayBuffer) console.log(isTypedArray(new DataView(new ArrayBuffer(8)))); // false (DataView) console.log(isTypedArray({})); // false console.log(isTypedArray(null)); // false console.log(isTypedArray(undefined)); // false ``` #### Parameters * `value` (`unknown`): The value to check if it's a TypedArray instance. #### Returns (`value is Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | BigUint64Array | Int8Array | Int16Array | Int32Array | BigInt64Array | Float32Array | Float64Array`): Returns `true` if the value is a TypedArray instance, `false` otherwise. --- --- url: /reference/compat/predicate/isTypedArray.md --- # isTypedArray (Lodash Compatibility) ::: warning Use `ArrayBuffer.isView()` or `instanceof` operator instead This `isTypedArray` function is a Lodash compatibility function, but is a simple type check. Use the simpler and more modern `ArrayBuffer.isView(value)` or `value instanceof Int8Array` etc. instead. ::: Checks if a value is a TypedArray. ```typescript const result = isTypedArray(x); ``` ## Usage ### `isTypedArray(x)` Use `isTypedArray` when you want to check if a value is a TypedArray. TypedArrays are special array types for handling binary data. ```typescript import { isTypedArray } from 'es-toolkit/compat'; // TypedArrays isTypedArray(new Uint8Array([1, 2, 3])); // true isTypedArray(new Int16Array([1, 2, 3])); // true isTypedArray(new Float32Array([1.1, 2.2])); // true isTypedArray(new BigInt64Array([1n, 2n])); // true // Other types return false isTypedArray([1, 2, 3]); // false (regular array) isTypedArray(new ArrayBuffer(16)); // false (ArrayBuffer) isTypedArray(new DataView(new ArrayBuffer(16))); // false (DataView) isTypedArray('array'); // false (string) isTypedArray({}); // false (object) isTypedArray(null); // false isTypedArray(undefined); // false ``` It recognizes all kinds of TypedArrays. ```typescript import { isTypedArray } from 'es-toolkit/compat'; // Integer TypedArrays isTypedArray(new Int8Array()); // true isTypedArray(new Int16Array()); // true isTypedArray(new Int32Array()); // true isTypedArray(new Uint8Array()); // true isTypedArray(new Uint16Array()); // true isTypedArray(new Uint32Array()); // true isTypedArray(new Uint8ClampedArray()); // true // Floating-point TypedArrays isTypedArray(new Float32Array()); // true isTypedArray(new Float64Array()); // true // BigInt TypedArrays isTypedArray(new BigInt64Array()); // true isTypedArray(new BigUint64Array()); // true ``` It distinguishes from other similar objects. ```typescript import { isTypedArray } from 'es-toolkit/compat'; const buffer = new ArrayBuffer(16); const view = new DataView(buffer); const typedArray = new Uint8Array(buffer); const regularArray = [1, 2, 3, 4]; isTypedArray(buffer); // false (ArrayBuffer) isTypedArray(view); // false (DataView) isTypedArray(typedArray); // true (TypedArray) isTypedArray(regularArray); // false (regular array) ``` It's useful for type distinction when processing binary data. ```typescript import { isTypedArray } from 'es-toolkit/compat'; function processData(data: unknown) { if (isTypedArray(data)) { console.log(`TypedArray length: ${data.length}`); console.log(`Byte length: ${data.byteLength}`); console.log(`Byte offset: ${data.byteOffset}`); console.log(`Constructor: ${data.constructor.name}`); // Output first value if (data.length > 0) { console.log(`First value: ${data[0]}`); } } else if (Array.isArray(data)) { console.log('Regular array'); } else { console.log('Not an array'); } } processData(new Uint8Array([1, 2, 3])); // TypedArray information output processData([1, 2, 3]); // "Regular array" processData('not an array'); // "Not an array" ``` #### Parameters * `x` (`any`): The value to check if it's a TypedArray. #### Returns (`boolean`): Returns `true` if the value is a TypedArray, `false` otherwise. --- --- url: /reference/predicate/isUndefined.md --- # isUndefined Checks if a given value is `undefined`. ```typescript const result = isUndefined(value); ``` ## Usage ### `isUndefined(value)` Use `isUndefined` when you want to check if a value is `undefined`. It's useful for checking whether a variable is initialized or whether an optional property exists. ```typescript import { isUndefined } from 'es-toolkit/predicate'; // undefined values console.log(isUndefined(undefined)); // true console.log(isUndefined(void 0)); // true let uninitialized: string; console.log(isUndefined(uninitialized)); // true // Non-undefined values console.log(isUndefined(null)); // false console.log(isUndefined('')); // false console.log(isUndefined(0)); // false console.log(isUndefined(false)); // false console.log(isUndefined({})); // false console.log(isUndefined([])); // false ``` #### Parameters * `value` (`unknown`): The value to check if it's undefined. #### Returns (`value is undefined`): Returns `true` if the value is undefined, `false` otherwise. --- --- url: /reference/compat/predicate/isUndefined.md --- # isUndefined (Lodash Compatibility) ::: warning Use `es-toolkit`'s [isUndefined](../../predicate/isUndefined.md) instead This `isUndefined` function operates slowly due to complex handling for Lodash compatibility. Use the faster and more modern `es-toolkit`'s [isUndefined](../../predicate/isUndefined.md) instead. ::: Checks if a value is `undefined`. ```typescript const result = isUndefined(value); ``` ## Usage ### `isUndefined(x)` Use `isUndefined` when you want to type-safely check if a value is exactly `undefined`. It also works as a type guard in TypeScript. ```typescript import { isUndefined } from 'es-toolkit/compat'; // Only undefined returns true isUndefined(undefined); // true // null also returns false isUndefined(null); // false // All other values also return false isUndefined(0); // false isUndefined(''); // false isUndefined(false); // false isUndefined([]); // false isUndefined({}); // false isUndefined('undefined'); // false isUndefined(NaN); // false ``` You can distinguish between `undefined` and `null`. ```typescript import { isUndefined } from 'es-toolkit/compat'; function handleValue(value: string | null | undefined) { if (isUndefined(value)) { console.log('Value is undefined'); } else if (value === null) { console.log('Value is explicitly null'); } else { console.log(`Value exists: ${value}`); } } handleValue(undefined); // "Value is undefined" handleValue(null); // "Value is explicitly null" handleValue('hello'); // "Value exists: hello" ``` It's useful for checking undeclared variables or uninitialized properties. ```typescript import { isUndefined } from 'es-toolkit/compat'; const obj: { name?: string; age?: number } = { name: 'John' }; if (isUndefined(obj.age)) { console.log('Age is not set'); obj.age = 25; // Set default value } // Default value handling for function parameters function greet(name: string, title?: string) { if (isUndefined(title)) { title = 'Mr./Ms.'; } console.log(`Hello, ${title} ${name}!`); } greet('Kim'); // "Hello, Mr./Ms. Kim!" greet('Kim', 'Dr.'); // "Hello, Dr. Kim!" ``` #### Parameters * `x` (`any`): The value to check if it's `undefined`. #### Returns (`x is undefined`): Returns `true` if the value is `undefined`, `false` otherwise. --- --- url: /reference/predicate/isWeakMap.md --- # isWeakMap Checks if a given value is a `WeakMap` instance. ```typescript const result = isWeakMap(value); ``` ## Usage ### `isWeakMap(value)` Use `isWeakMap` when you want to check if a value is a `WeakMap` instance. `WeakMap` is a key-value store with weak references to objects as keys, useful for preventing memory leaks. ```typescript import { isWeakMap } from 'es-toolkit/predicate'; // WeakMap instances const weakMap1 = new WeakMap(); const weakMap2 = new WeakMap([[{}, 'value']]); console.log(isWeakMap(weakMap1)); // true console.log(isWeakMap(weakMap2)); // true // Non-WeakMap values console.log(isWeakMap(new Map())); // false console.log(isWeakMap(new Set())); // false console.log(isWeakMap(new WeakSet())); // false console.log(isWeakMap({})); // false console.log(isWeakMap([])); // false console.log(isWeakMap(null)); // false console.log(isWeakMap(undefined)); // false ``` #### Parameters * `value` (`unknown`): The value to check if it's a WeakMap instance. #### Returns (`value is WeakMap`): Returns `true` if the value is a WeakMap instance, `false` otherwise. --- --- url: /reference/compat/predicate/isWeakMap.md --- # isWeakMap (Lodash Compatibility) ::: warning Use `instanceof` operator instead This `isWeakMap` function is a Lodash compatibility function, but is a simple type check. Use the simpler and more modern `value instanceof WeakMap` instead. ::: Checks if a value is a WeakMap. ```typescript const result = isWeakMap(value); ``` ## Usage ### `isWeakMap(value)` Use `isWeakMap` when you want to type-safely check if a value is a WeakMap. It also works as a type guard in TypeScript. ```typescript import { isWeakMap } from 'es-toolkit/compat'; // WeakMap checking const weakMap = new WeakMap(); isWeakMap(weakMap); // true // Other types return false isWeakMap(new Map()); // false isWeakMap(new Set()); // false isWeakMap(new WeakSet()); // false isWeakMap({}); // false isWeakMap([]); // false isWeakMap('weakmap'); // false isWeakMap(123); // false isWeakMap(null); // false isWeakMap(undefined); // false ``` It also distinguishes from other similar collections. ```typescript import { isWeakMap } from 'es-toolkit/compat'; // WeakMap vs Map const obj = {}; const weakMap = new WeakMap([[obj, 'value']]); const map = new Map([[obj, 'value']]); isWeakMap(weakMap); // true isWeakMap(map); // false // WeakMap vs WeakSet isWeakMap(new WeakMap()); // true isWeakMap(new WeakSet()); // false // WeakMap vs regular objects isWeakMap(new WeakMap()); // true isWeakMap({}); // false ``` It's useful when utilizing WeakMap's special properties. ```typescript import { isWeakMap } from 'es-toolkit/compat'; function setupWeakReference(collection: unknown, key: object, value: any) { if (isWeakMap(collection)) { // WeakMap can only use objects as keys and maintains weak references collection.set(key, value); console.log('Stored with weak reference in WeakMap'); // WeakMap does not have size information console.log('WeakMap has no size information'); } else { console.log('Not a WeakMap'); } } const weakMap = new WeakMap(); const regularMap = new Map(); const obj = { id: 1 }; setupWeakReference(weakMap, obj, 'data'); // "Stored with weak reference in WeakMap" setupWeakReference(regularMap, obj, 'data'); // "Not a WeakMap" ``` #### Parameters * `value` (`unknown`): The value to check if it's a WeakMap. #### Returns (`value is WeakMap`): Returns `true` if the value is a WeakMap, `false` otherwise. --- --- url: /reference/predicate/isWeakSet.md --- # isWeakSet Checks if a given value is a `WeakSet` instance. ```typescript const result = isWeakSet(value); ``` ## Usage ### `isWeakSet(value)` Use `isWeakSet` when you want to check if a value is a WeakSet instance. ```typescript import { isWeakSet } from 'es-toolkit/predicate'; // WeakSet instances const weakSet1 = new WeakSet(); const weakSet2 = new WeakSet([{}, []]); console.log(isWeakSet(weakSet1)); // true console.log(isWeakSet(weakSet2)); // true // Non-WeakSet values console.log(isWeakSet(new Set())); // false console.log(isWeakSet(new Map())); // false console.log(isWeakSet(new WeakMap())); // false console.log(isWeakSet([])); // false console.log(isWeakSet({})); // false console.log(isWeakSet(null)); // false console.log(isWeakSet(undefined)); // false ``` #### Parameters * `value` (`unknown`): The value to check if it's a WeakSet instance. #### Returns (`value is WeakSet`): Returns `true` if the value is a WeakSet instance, `false` otherwise. --- --- url: /reference/compat/predicate/isWeakSet.md --- # isWeakSet (Lodash Compatibility) ::: warning Use `instanceof` operator instead This `isWeakSet` function is a Lodash compatibility function, but is a simple type check. Use the simpler and more modern `value instanceof WeakSet` instead. ::: Checks if a value is a WeakSet. ```typescript const result = isWeakSet(value); ``` ## Usage ### `isWeakSet(value)` Use `isWeakSet` when you want to type-safely check if a value is a WeakSet. It also works as a type guard in TypeScript. ```typescript import { isWeakSet } from 'es-toolkit/compat'; // WeakSet checking const weakSet = new WeakSet(); isWeakSet(weakSet); // true // Other types return false isWeakSet(new Set()); // false isWeakSet(new Map()); // false isWeakSet(new WeakMap()); // false isWeakSet([]); // false isWeakSet({}); // false isWeakSet('weakset'); // false isWeakSet(123); // false isWeakSet(null); // false isWeakSet(undefined); // false ``` It also distinguishes from other similar collections. ```typescript import { isWeakSet } from 'es-toolkit/compat'; // WeakSet vs Set const obj = {}; const weakSet = new WeakSet([obj]); const set = new Set([obj]); isWeakSet(weakSet); // true isWeakSet(set); // false // WeakSet vs WeakMap isWeakSet(new WeakSet()); // true isWeakSet(new WeakMap()); // false // WeakSet vs array isWeakSet(new WeakSet()); // true isWeakSet([]); // false ``` It's useful when utilizing WeakSet's special properties. ```typescript import { isWeakSet } from 'es-toolkit/compat'; function addWeakReference(collection: unknown, item: object) { if (isWeakSet(collection)) { // WeakSet can only store objects and maintains weak references collection.add(item); console.log('Stored with weak reference in WeakSet'); // WeakSet has no size information and cannot be iterated console.log('WeakSet has no size information and cannot be iterated'); } else { console.log('Not a WeakSet'); } } const weakSet = new WeakSet(); const regularSet = new Set(); const obj = { id: 1 }; addWeakReference(weakSet, obj); // "Stored with weak reference in WeakSet" addWeakReference(regularSet, obj); // "Not a WeakSet" ``` It's useful for object tracking to prevent memory leaks. ```typescript import { isWeakSet } from 'es-toolkit/compat'; // DOM element tracking example function trackDOMElement(tracker: unknown, element: Element) { if (isWeakSet(tracker)) { // When DOM elements are removed, they're automatically removed from WeakSet tracker.add(element); console.log('Started tracking DOM element'); // Check tracking status later if (tracker.has(element)) { console.log('This element is being tracked'); } } } ``` #### Parameters * `value` (`unknown`): The value to check if it's a WeakSet. #### Returns (`value is WeakSet`): Returns `true` if the value is a WeakSet, `false` otherwise. --- --- url: /reference/compat/util/iteratee.md --- # iteratee (Lodash Compatibility) ::: warning Use direct functions or property access instead This `iteratee` function performs slowly due to complex type conversions and handling of various cases. Instead, use faster and more modern direct functions or property access. ::: Creates a function that returns a value from an element. ```typescript const getter = iteratee(source); ``` ## Usage ### `iteratee(value?)` Use `iteratee` when you want to create a function that extracts values from collection elements or checks conditions. It performs different actions based on the type of argument provided. ```typescript import { iteratee } from 'es-toolkit/compat'; // Function: Returns the given function as-is const func = iteratee(object => object.a); [{ a: 1 }, { a: 2 }, { a: 3 }].map(func); // Returns: [1, 2, 3] // Property name: Function that returns the value of that property const getA = iteratee('a'); [{ a: 1 }, { a: 2 }, { a: 3 }].map(getA); // Returns: [1, 2, 3] // Object: Function that checks if it matches the given object const matchesObj = iteratee({ a: 1 }); [ { a: 1, b: 2 }, { a: 2, b: 3 }, { a: 1, c: 4 }, ].find(matchesObj); // Returns: { a: 1, b: 2 } // Property-value pair: Function that checks if the property matches a specific value const matchesProperty = iteratee(['a', 1]); [{ a: 1 }, { a: 2 }, { a: 3 }].find(matchesProperty); // Returns: { a: 1 } // null or no argument: Function that returns the element as-is const identity = iteratee(); [{ a: 1 }, { a: 2 }, { a: 3 }].map(identity); // Returns: [{ a: 1 }, { a: 2 }, { a: 3 }] ``` Actions based on argument type: * **Function**: Returns the given function as-is. * **Property name**: Returns the value of the given property from the element. * **Property-value pair**: Returns a boolean indicating whether the element's property matches the given value. * **Partial object**: Returns a boolean indicating whether the element matches the partial object's properties and values. * **null or no argument**: Returns a function that returns the element as-is. #### Parameters * `value` (`symbol | number | string | object | null | ((...args: any[]) => unknown)`, optional): The value to convert to an iteratee. Default is `null`. #### Returns (`(...args: any[]) => any`): Returns the new iteratee function. --- --- url: /reference/compat/array/join.md --- # join (Lodash Compatibility) ::: warning Use `Array.prototype.join()` This `join` function is slow due to handling ArrayLike objects, null/undefined, etc. Use the faster and more modern `Array.prototype.join()` instead. ::: Joins the elements of an array into a string. ```typescript const result = join(array, separator); ``` ## Usage ### `join(array, separator?)` Use `join` to combine all elements of an array into a single string. It connects each element with a separator. ```typescript import { join } from 'es-toolkit/compat'; // Join string array const arr = ['a', 'b', 'c']; join(arr, '~'); // => "a~b~c" // Join number array const numbers = [1, 2, 3]; join(numbers, '-'); // => "1-2-3" ``` If you omit the separator, comma (`,`) is used by default. ```typescript import { join } from 'es-toolkit/compat'; join(['a', 'b', 'c']); // => "a,b,c" ``` `null` or `undefined` are treated as empty arrays. ```typescript import { join } from 'es-toolkit/compat'; join(null, '-'); // => "" join(undefined, '-'); // => "" ``` #### Parameters * `array` (`T[]`) - The array to join. ::: info `array` can be `ArrayLike` or `null` or `undefined` To ensure full compatibility with lodash, the `join` function processes `array` as follows: * If `array` is `ArrayLike`, it converts it to an array using `Array.from(...)`. * If `array` is `null` or `undefined`, it is treated as an empty array. ::: * `separator` (`string`, optional) - The separator used to join the elements. Defaults to `,`. #### Returns (`string`): Returns a string containing all elements of the array joined by the specified separator. --- --- url: /reference/string/kebabCase.md --- # kebabCase Converts a string to kebab case. ```typescript const result = kebabCase(str); ``` ## Usage ### `kebabCase(str)` Use `kebabCase` when you want to convert a string to kebab case. Kebab case is a naming convention where each word is written in lowercase and connected with dashes (-). ```typescript import { kebabCase } from 'es-toolkit/string'; // Convert camel case to kebab case kebabCase('camelCase'); // Result: 'camel-case' // Convert a string with whitespace kebabCase('some whitespace'); // Result: 'some-whitespace' // Keep strings that are already in kebab case as is kebabCase('hyphen-text'); // Result: 'hyphen-text' // Convert strings with uppercase letters kebabCase('HTTPRequest'); // Result: 'http-request' ``` This function is useful when creating API endpoints, CSS class names, HTML attributes, etc. #### Parameters * `str` (`string`): The string to convert to kebab case. #### Returns (`string`): The string converted to kebab case. --- --- url: /reference/compat/string/kebabCase.md --- # kebabCase (Lodash compatibility) ::: warning Use `kebabCase` from `es-toolkit` This `kebabCase` function operates slower due to handling non-string input values and removing contracted apostrophes. Instead, use the faster and more modern [kebabCase](../../string/kebabCase.md) from `es-toolkit`. ::: Converts a string to kebab case. ```typescript const result = kebabCase(str); ``` ## Usage ### `kebabCase(str)` Converts a string to kebab case. Kebab case is a naming convention where each word is written in lowercase and connected with a dash (-) character. It's commonly used in URLs and CSS class names. ```typescript import { kebabCase } from 'es-toolkit/compat'; kebabCase('camelCase'); // 'camel-case' kebabCase('some whitespace'); // 'some-whitespace' kebabCase('hyphen-text'); // 'hyphen-text' kebabCase('HTTPRequest'); // 'http-request' ``` Non-string values are also converted to strings before processing. ```typescript import { kebabCase } from 'es-toolkit/compat'; kebabCase(123); // '123' kebabCase(null); // '' kebabCase(undefined); // '' ``` #### Parameters * `str` (`string | object`, optional): The value to convert to kebab case. #### Returns (`string`): Returns the string converted to kebab case. --- --- url: /reference/array/keyBy.md --- # keyBy Returns a new object with array elements converted to key-value pairs using a key-generating function. ```typescript const result = keyBy(arr, getKeyFromItem); ``` ## Usage ### `keyBy(arr, getKeyFromItem)` Use `keyBy` when you want to create a key-indexed object for quick lookup of each element in an array. By providing a function that generates a unique key from each element, it creates an object where you can access elements using that key. If multiple elements generate the same key, the last element is used. ```typescript import { keyBy } from 'es-toolkit/array'; // Use object's id property as key const users = [ { id: 1, name: 'john' }, { id: 2, name: 'jane' }, { id: 3, name: 'bob' }, ]; keyBy(users, user => user.id); // Returns: { // 1: { id: 1, name: 'john' }, // 2: { id: 2, name: 'jane' }, // 3: { id: 3, name: 'bob' } // } // Use string property as key const products = [ { category: 'fruit', name: 'apple' }, { category: 'fruit', name: 'banana' }, { category: 'vegetable', name: 'carrot' }, ]; keyBy(products, item => item.category); // Returns: { // fruit: { category: 'fruit', name: 'banana' }, // Last fruit element // vegetable: { category: 'vegetable', name: 'carrot' } // } ``` Complex key generation logic can also be used. ```typescript import { keyBy } from 'es-toolkit/array'; // Combine multiple properties to create a key const orders = [ { date: '2023-01-01', customerId: 1, amount: 100 }, { date: '2023-01-01', customerId: 2, amount: 200 }, { date: '2023-01-02', customerId: 1, amount: 150 }, ]; keyBy(orders, order => `${order.date}-${order.customerId}`); // Returns: { // '2023-01-01-1': { date: '2023-01-01', customerId: 1, amount: 100 }, // '2023-01-01-2': { date: '2023-01-01', customerId: 2, amount: 200 }, // '2023-01-02-1': { date: '2023-01-02', customerId: 1, amount: 150 } // } ``` #### Parameters * `arr` (`readonly T[]`): The array to convert to an object. * `getKeyFromItem` (`(item: T, index: number, array: T[]) => K`): A function that generates a key from each element, its index, and the array. #### Returns (`Record`): Returns an object with the generated keys as property names and the corresponding elements as values. If multiple elements generate the same key, the last element is used as the value. ## Examples ```typescript // Using index parameter const items = ['a', 'b', 'c']; const result = keyBy(items, (item, index) => index); // Returns: { 0: 'a', 1: 'b', 2: 'c' } // Using array parameter const numbers = [10, 20, 30]; const result2 = keyBy(numbers, (item, index, arr) => (item > arr[0] ? 'large' : 'small')); // Returns: { small: 10, large: 30 } ``` --- --- url: /reference/map/keyBy.md --- # keyBy (for `Map`s) Maps each entry of a Map based on a provided key-generating function. ```typescript const result = keyBy(map, getKeyFromEntry); ``` ::: info This function is available exclusively from `es-toolkit/map` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `keyBy(map, getKeyFromEntry)` Use `keyBy` when you want to reorganize a Map by generating new keys from the values. Provide a function that generates a key from each value-key pair, and it returns a new Map where the keys are generated by the key function and the values are the corresponding values from the original map. If multiple entries produce the same key, the last value encountered will be used. ```typescript import { keyBy } from 'es-toolkit/map'; const map = new Map([ ['x', { type: 'fruit', name: 'apple' }], ['y', { type: 'fruit', name: 'banana' }], ['z', { type: 'vegetable', name: 'carrot' }], ]); const result = keyBy(map, item => item.type); // Result: // Map(2) { // 'fruit' => { type: 'fruit', name: 'banana' }, // 'vegetable' => { type: 'vegetable', name: 'carrot' } // } // Note: 'banana' is kept because it was the last 'fruit' encountered ``` You can reorganize data based on various criteria. ```typescript import { keyBy } from 'es-toolkit/map'; // Index by ID property const users = new Map([ ['user1', { id: 101, name: 'Alice', role: 'admin' }], ['user2', { id: 102, name: 'Bob', role: 'user' }], ['user3', { id: 103, name: 'Charlie', role: 'user' }], ]); const byId = keyBy(users, user => user.id); // Result: Map with keys 101, 102, 103 // Index by role (last user per role wins) const byRole = keyBy(users, user => user.role); // Result: Map(2) { // 'admin' => { id: 101, name: 'Alice', role: 'admin' }, // 'user' => { id: 103, name: 'Charlie', role: 'user' } // } // Transform keys using both value and original key const inventory = new Map([ ['item_1', { category: 'electronics', price: 100 }], ['item_2', { category: 'electronics', price: 200 }], ]); const categorized = keyBy(inventory, (value, key) => `${value.category}_${key}`); // Result: Map with keys 'electronics_item_1', 'electronics_item_2' ``` #### Parameters * `map` (`Map`): The map of entries to be mapped. * `getKeyFromEntry` (`(value: V, key: K, object: Map) => K2`): A function that generates a key from a value-key pair. #### Returns (`Map`): A Map where the generated keys are mapped to each entry's value. --- --- url: /reference/set/keyBy.md --- # keyBy (for `Set`s) Maps each element of a Set based on a provided key-generating function. ```typescript const result = keyBy(set, getKeyFromValue); ``` ::: info This function is available exclusively from `es-toolkit/set` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `keyBy(set, getKeyFromValue)` Use `keyBy` when you want to convert a Set into a Map by generating keys from the values. Provide a function that generates a key from each value, and it returns a new Map where the keys are generated by the key function and the values are the corresponding values from the original set. If multiple elements produce the same key, the last value encountered will be used. ```typescript import { keyBy } from 'es-toolkit/set'; const set = new Set([ { type: 'fruit', name: 'apple' }, { type: 'fruit', name: 'banana' }, { type: 'vegetable', name: 'carrot' }, ]); const result = keyBy(set, item => item.type); // Result: // Map(2) { // 'fruit' => { type: 'fruit', name: 'banana' }, // 'vegetable' => { type: 'vegetable', name: 'carrot' } // } // Note: 'banana' is kept because it was the last 'fruit' encountered ``` You can create indexes based on various criteria. ```typescript import { keyBy } from 'es-toolkit/set'; // Index by ID const users = new Set([ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }, ]); const byId = keyBy(users, user => user.id); // Result: Map(3) { 1 => {...}, 2 => {...}, 3 => {...} } // Index by name const byName = keyBy(users, user => user.name); // Result: Map with keys 'Alice', 'Bob', 'Charlie' // Index by derived value const numbers = new Set([1, 2, 3, 4, 5]); const byParity = keyBy(numbers, num => (num % 2 === 0 ? 'even' : 'odd')); // Result: Map(2) { // 'odd' => 5, // 'even' => 4 // } // Note: Last even (4) and last odd (5) values are kept ``` #### Parameters * `set` (`Set`): The set of elements to be mapped. * `getKeyFromValue` (`(value: T, value2: T, set: Set) => K`): A function that generates a key from a value. #### Returns (`Map`): A Map where the generated keys are mapped to each element's value. --- --- url: /reference/compat/array/keyBy.md --- # keyBy (Lodash Compatibility) ::: warning Use `es-toolkit`'s [keyBy](../../array/keyBy.md) This `keyBy` function is slow due to handling `null` or `undefined`, various parameter types, etc. Use the faster and more modern `es-toolkit`'s [keyBy](../../array/keyBy.md) instead. ::: Organizes collection elements into an object based on the specified key. ```typescript const result = keyBy(collection, iteratee); ``` ## Usage ### `keyBy(collection, iteratee)` Organizes each element in an array or object into an object using the specified key generation function or property name. If multiple elements have the same key, the last element is used. ```typescript import { keyBy } from 'es-toolkit/compat'; // Generate keys by property name const array = [ { dir: 'left', code: 97 }, { dir: 'right', code: 100 }, ]; keyBy(array, 'dir'); // => { left: { dir: 'left', code: 97 }, right: { dir: 'right', code: 100 } } // Generate keys using a function keyBy(array, o => String.fromCharCode(o.code)); // => { a: { dir: 'left', code: 97 }, d: { dir: 'right', code: 100 } } // Can also be used with objects const obj = { a: { id: 1, name: 'john' }, b: { id: 2, name: 'jane' }, }; keyBy(obj, 'name'); // => { john: { id: 1, name: 'john' }, jane: { id: 2, name: 'jane' } } ``` `null` or `undefined` are treated as empty objects. ```typescript import { keyBy } from 'es-toolkit/compat'; keyBy(null, 'id'); // {} keyBy(undefined, 'id'); // {} ``` #### Parameters * `collection` (`ArrayLike | null | undefined`): The array or object to organize by key. * `iteratee` (`ValueIterateeCustom`, optional): The function or property name to generate keys. If omitted, the element itself is used as the key. #### Returns (`Record`): Returns a new object where each element is mapped to the generated key. --- --- url: /reference/compat/object/keys.md --- # keys (Lodash compatibility) ::: warning Use `Object.keys` This `keys` function operates slowly due to complex logic for handling array-like objects, prototype objects, etc. Instead, use the faster and more modern `Object.keys()`. ::: Returns an array of the object's own enumerable property names. ```typescript const keyArray = keys(object); ``` ## Usage ### `keys(object)` Use `keys` when you want to get the object's own property names. It returns only own properties, excluding inherited properties. ```typescript import { keys } from 'es-toolkit/compat'; // Keys of a basic object const object = { a: 1, b: 2, c: 3 }; keys(object); // => ['a', 'b', 'c'] // Indices of an array const array = [1, 2, 3]; keys(array); // => ['0', '1', '2'] // Indices of a string keys('hello'); // => ['0', '1', '2', '3', '4'] ``` Properties inherited from functions or constructors are excluded. ```typescript import { keys } from 'es-toolkit/compat'; function Foo() { this.a = 1; this.b = 2; } Foo.prototype.c = 3; keys(new Foo()); // => ['a', 'b'] ('c' is excluded as it's a prototype property) ``` Array-like objects are handled specially. ```typescript import { keys } from 'es-toolkit/compat'; // TypedArray const typedArray = new Uint8Array([1, 2, 3]); keys(typedArray); // => ['0', '1', '2'] // arguments object function example() { return keys(arguments); } example('a', 'b', 'c'); // => ['0', '1', '2'] ``` Handles `null` and `undefined` safely. ```typescript import { keys } from 'es-toolkit/compat'; keys(null); // => [] keys(undefined); // => [] ``` #### Parameters * `object` (`any`): The object to get keys from. #### Returns (`string[]`): Returns an array of the object's own enumerable property names. --- --- url: /reference/compat/object/keysIn.md --- # keysIn (Lodash compatibility) ::: warning Use `for...in` loop or `Object.keys` This `keysIn` function operates slowly due to complex logic such as handling array-like objects and traversing the prototype chain. Use the faster and more modern `for...in` loop or `Object.keys()` as needed instead. ::: Returns an array of all enumerable property names of an object, including inherited properties. ```typescript const allKeys = keysIn(object); ``` ## Usage ### `keysIn(object)` Use `keysIn` when you want to get all property names of an object including inherited properties. Unlike `keys`, it also returns properties from the prototype chain. ```typescript import { keysIn } from 'es-toolkit/compat'; // Keys of a basic object const object = { a: 1, b: 2 }; keysIn(object); // => ['a', 'b'] // Indices of an array const array = [1, 2, 3]; keysIn(array); // => ['0', '1', '2'] // Indices of a string keysIn('hello'); // => ['0', '1', '2', '3', '4'] ``` It also includes inherited properties. ```typescript import { keysIn } from 'es-toolkit/compat'; function Foo() { this.a = 1; this.b = 2; } Foo.prototype.c = 3; keysIn(new Foo()); // => ['a', 'b', 'c'] (includes prototype property 'c') // constructor is excluded class MyClass { constructor() { this.prop = 1; } method() {} } MyClass.prototype.inherited = 2; keysIn(new MyClass()); // => ['prop', 'method', 'inherited'] (constructor is excluded) ``` It specially handles array-like objects. ```typescript import { keysIn } from 'es-toolkit/compat'; // TypedArray const typedArray = new Uint8Array([1, 2, 3]); keysIn(typedArray); // => ['0', '1', '2'] (excludes buffer, byteLength, etc.) // arguments object function example() { return keysIn(arguments); } example('a', 'b', 'c'); // => ['0', '1', '2'] ``` It safely handles `null` or `undefined`. ```typescript import { keysIn } from 'es-toolkit/compat'; keysIn(null); // => [] keysIn(undefined); // => [] ``` #### Parameters * `object` (`any`): The object to get keys from. #### Returns (`string[]`): Returns an array of all enumerable property names (including both own and inherited properties) of the object. --- --- url: /reference/array/last.md --- # last Returns the last element of an array. ```typescript const lastElement = last(arr); ``` ## Usage ### `last(arr)` Use `last` when you want to get the last element of an array. If the array is empty, it returns `undefined`. This is useful when accessing data at the end of an array. ```typescript import { last } from 'es-toolkit/array'; // Get the last element of a number array const numbers = [1, 2, 3, 4, 5]; last(numbers); // Returns: 5 // Get the last element of a string array const strings = ['a', 'b', 'c']; last(strings); // Returns: 'c' // Empty array returns undefined const emptyArray: number[] = []; last(emptyArray); // Returns: undefined ``` Type handling is safe. ```typescript import { last } from 'es-toolkit/array'; // For non-empty arrays, the type is certain const nonEmptyArray = [1, 2, 3] as const; last(nonEmptyArray); // Returns: 3 (type: 3) // For regular arrays, undefined is possible const maybeEmptyArray = [1, 2, 3]; last(maybeEmptyArray); // Returns: 3 | undefined (type: number | undefined) ``` It works efficiently even with large arrays. ```typescript import { last } from 'es-toolkit/array'; // Performance optimized const largeArray = Array(1000000) .fill(0) .map((_, i) => i); last(largeArray); // Returns: 999999 (fast access) // It can also handle nested arrays const nested = [ [1, 2], [3, 4], [5, 6], ]; last(nested); // Returns: [5, 6] ``` #### Parameters * `arr` (`readonly T[]`): The array from which to get the last element. #### Returns (`T | undefined`): The last element of the array. Returns `undefined` if the array is empty. --- --- url: /reference/compat/array/last.md --- # last (Lodash compatibility) ::: warning Use `es-toolkit`'s [last](../../array/last.md) This `last` function behaves complexly due to handling `null` or `undefined`. Instead, use the faster and more modern `es-toolkit`'s [last](../../array/last.md). ::: Returns the last element of an array. ```typescript const lastElement = last(array); ``` ## Usage ### `last(array)` Use `last` when you want to get the last element of an array. Returns `undefined` if the array is empty. ```typescript import { last } from 'es-toolkit/compat'; // Last element of a number array last([1, 2, 3, 4, 5]); // Returns: 5 // Last element of a string array last(['a', 'b', 'c']); // Returns: 'c' // Last element of an object array const users = [{ name: 'Alice' }, { name: 'Bob' }]; last(users); // Returns: { name: 'Bob' } ``` Empty arrays or `null`, `undefined` return `undefined`. ```typescript import { last } from 'es-toolkit/compat'; // Empty array last([]); // Returns: undefined // null array last(null); // Returns: undefined // undefined array last(undefined); // Returns: undefined ``` Array-like objects are also supported. ```typescript import { last } from 'es-toolkit/compat'; // Array-like object const arrayLike = { 0: 'first', 1: 'second', length: 2 }; last(arrayLike); // Returns: 'second' // Strings are also array-like objects last('hello'); // Returns: 'o' ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to get the last element from. #### Returns (`T | undefined`): Returns the last element of the array, or `undefined` if the array is empty, `null`, or `undefined`. --- --- url: /reference/compat/array/lastIndexOf.md --- # lastIndexOf (Lodash compatibility) ::: warning Use `Array.lastIndexOf` This `lastIndexOf` function operates slowly due to handling `null` or `undefined`, searching for `NaN` values, etc. Instead, use the faster and more modern `Array.lastIndexOf`. ::: Finds the last index at which a given element appears in an array. ```typescript const index = lastIndexOf(array, searchElement, fromIndex); ``` ## Usage ### `lastIndexOf(array, searchElement, fromIndex)` Returns the last index at which a given element appears in an array. Similar to native `Array.lastIndexOf` but can also find `NaN` values. ```typescript import { lastIndexOf } from 'es-toolkit/compat'; // Basic usage lastIndexOf([1, 2, 1, 2], 2); // => 3 // Specifying a start index lastIndexOf([1, 2, 1, 2], 2, 2); // => 1 // Finding NaN values (native lastIndexOf cannot find NaN) lastIndexOf([1, 2, NaN, 4, NaN], NaN); // => 4 // Using negative index lastIndexOf([1, 2, 3, 4], 3, -2); // => 2 ``` `null` or `undefined` are treated as empty arrays. ```typescript import { lastIndexOf } from 'es-toolkit/compat'; lastIndexOf(null, 1); // -1 lastIndexOf(undefined, 1); // -1 ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to search. * `searchElement` (`T`): The element to find. * `fromIndex` (`true | number`, optional): The index to start searching from. Passing `true` searches from the end of the array. Defaults to `array.length - 1`. #### Returns (`number`): Returns the index of the last matching element. Returns `-1` if not found. --- --- url: /reference/array/limitAsync.md --- # limitAsync Creates a new function that limits the maximum number of concurrent executions of an async function. ```typescript const limitedFunc = limitAsync(asyncFunc, concurrency); ``` ## Reference ### `limitAsync(callback, concurrency)` Use `limitAsync` when you want to limit the number of concurrent executions of an async function that gets called multiple times. Only the specified number of executions run concurrently, and additional calls wait until running operations complete. ```typescript import { limitAsync } from 'es-toolkit/array'; // Limit to at most 3 concurrent requests. const limitedFetch = limitAsync(async url => { return await fetch(url); }, 3); const urls = ['url1', 'url2', 'url3', 'url4', 'url5']; await Promise.all(urls.map(url => limitedFetch(url))); // The first 3 execute first, then the rest execute as they complete. ``` It's useful for controlling load on resource-intensive operations like external API calls or database queries. It's especially effective when working with rate-limited APIs or managing server load. ```typescript import { limitAsync } from 'es-toolkit/array'; // Process heavy computations at most 2 at a time. const processItem = async item => { return await heavyComputation(item); }; const limitedProcess = limitAsync(processItem, 2); const items = [1, 2, 3, 4, 5]; await Promise.all(items.map(item => limitedProcess(item))); // Only 2 items are processed concurrently at most. ``` #### Parameters * `callback` (`F extends (...args: any[]) => Promise`): The async function to limit concurrent executions for. * `concurrency` (`number`): Maximum number of concurrent operations. #### Returns (`F`): A new function with concurrency limiting applied. It has the same interface as the original function. --- --- url: /reference/string/lowerCase.md --- # lowerCase Converts a string to lower case format. ```typescript const result = lowerCase(str); ``` ## Usage ### `lowerCase(str)` Use `lowerCase` when you want to convert a string to lower case format. Lower case format is a naming convention where all words are written in lowercase and separated by spaces. ```typescript import { lowerCase } from 'es-toolkit/string'; // Convert various string formats to lower case lowerCase('Hello World'); // returns 'hello world' lowerCase('camelCase'); // returns 'camel case' lowerCase('some-kebab-case'); // returns 'some kebab case' lowerCase('PascalCase'); // returns 'pascal case' lowerCase('SCREAMING_SNAKE_CASE'); // returns 'screaming snake case' ``` It's useful when creating user-facing text or titles. ```typescript import { lowerCase } from 'es-toolkit/string'; // Generate user interface text const fieldName = 'firstName'; const label = lowerCase(fieldName); // 'first name' // Convert API keys to user-friendly text const apiKeys = ['userEmail', 'phoneNumber', 'birthDate']; const labels = apiKeys.map(key => lowerCase(key)); // returns ['user email', 'phone number', 'birth date'] ``` It can also be used when displaying configuration or option names. ```typescript import { lowerCase } from 'es-toolkit/string'; // Display settings menu const settings = { enableNotifications: true, darkModeEnabled: false, autoSaveInterval: 300, }; for (const [key, value] of Object.entries(settings)) { const displayName = lowerCase(key); console.log(`${displayName}: ${value}`); } // Output: // enable notifications: true // dark mode enabled: false // auto save interval: 300 ``` It properly handles strings with special characters or spaces. ```typescript import { lowerCase } from 'es-toolkit/string'; lowerCase('HTTPSConnection'); // returns 'https connection' lowerCase('user_profile-settings'); // returns 'user profile settings' lowerCase(' mixed CASE text '); // returns 'mixed case text' ``` #### Parameters * `str` (`string`): The string to convert to lower case format. #### Returns (`string`): Returns a new string converted to lower case format. --- --- url: /reference/compat/string/lowerCase.md --- # lowerCase (Lodash compatibility) ::: warning Use `lowerCase` from `es-toolkit` This `lowerCase` function operates slower due to handling non-string input values and removing contracted apostrophes. Instead, use the faster and more modern [lowerCase](../../string/lowerCase.md) from `es-toolkit`. ::: Converts a string to lowercase words separated by spaces. ```typescript const result = lowerCase(str); ``` ## Usage ### `lowerCase(str)` Converts a string to lowercase words separated by spaces. Each word is converted to lowercase and connected with space characters. This is useful for creating human-readable text. ```typescript import { lowerCase } from 'es-toolkit/compat'; lowerCase('camelCase'); // 'camel case' lowerCase('some whitespace'); // 'some whitespace' lowerCase('hyphen-text'); // 'hyphen text' lowerCase('HTTPRequest'); // 'http request' ``` Non-string values are also converted to strings before processing. ```typescript import { lowerCase } from 'es-toolkit/compat'; lowerCase(123); // '123' lowerCase(null); // '' lowerCase(undefined); // '' ``` #### Parameters * `str` (`string | object`, optional): The value to convert to lowercase format. #### Returns (`string`): Returns the string with lowercase words separated by spaces. --- --- url: /reference/string/lowerFirst.md --- # lowerFirst Converts the first character of a string to lowercase. ```typescript const result = lowerFirst(str); ``` ## Usage ### `lowerFirst(str)` Use `lowerFirst` when you want to make only the first letter of a string lowercase. The remaining characters are kept as-is. It's useful for creating camelCase variable names or property names. ```typescript import { lowerFirst } from 'es-toolkit/string'; // Basic usage lowerFirst('Hello'); // returns 'hello' lowerFirst('WORLD'); // returns 'wORLD' lowerFirst('JavaScript'); // returns 'javaScript' ``` It correctly handles empty strings and single-character strings. ```typescript import { lowerFirst } from 'es-toolkit/string'; lowerFirst(''); // returns '' lowerFirst('A'); // returns 'a' lowerFirst('a'); // returns 'a' ``` You can use it for camelCase conversion. ```typescript import { lowerFirst } from 'es-toolkit/string'; // Convert class name to instance variable name const className = 'UserService'; const instanceName = lowerFirst(className); // 'userService' // Convert constant name to camelCase const constantName = 'API_BASE_URL'; const camelCase = lowerFirst(constantName.toLowerCase().replace(/_(.)/g, (_, letter) => letter.toUpperCase())); // results in 'apiBaseUrl' ``` It can also be used for API responses or data transformation. ```typescript import { lowerFirst } from 'es-toolkit/string'; // Convert database column names to JavaScript property names const dbColumns = ['UserId', 'FirstName', 'LastName', 'EmailAddress']; const jsProperties = dbColumns.map(column => lowerFirst(column)); // returns ['userId', 'firstName', 'lastName', 'emailAddress'] // Generate function names function createGetter(propertyName: string): string { return `get${propertyName}`; } function createSetter(propertyName: string): string { return `set${propertyName}`; } const property = lowerFirst('UserName'); // 'userName' const getter = createGetter(property.charAt(0).toUpperCase() + property.slice(1)); // 'getUserName' const setter = createSetter(property.charAt(0).toUpperCase() + property.slice(1)); // 'setUserName' ``` #### Parameters * `str` (`string`): The string to convert the first character to lowercase. #### Returns (`string`): Returns a new string with the first character converted to lowercase. --- --- url: /reference/compat/string/lowerFirst.md --- # lowerFirst (Lodash compatibility) ::: warning Use `lowerFirst` from `es-toolkit` This `lowerFirst` function operates slower due to handling non-string input values. Instead, use the faster and more modern [lowerFirst](../../string/lowerFirst.md) from `es-toolkit`. ::: Converts the first character of a string to lowercase. ```typescript const result = lowerFirst(str); ``` ## Usage ### `lowerFirst(str)` Converts the first character of a string to lowercase. The remaining characters are kept as is. This is useful for creating camelCase variable names or when you only want to lowercase the first character. ```typescript import { lowerFirst } from 'es-toolkit/compat'; lowerFirst('fred'); // 'fred' lowerFirst('Fred'); // 'fred' lowerFirst('FRED'); // 'fRED' lowerFirst(''); // '' ``` Non-string values are also converted to strings before processing. ```typescript import { lowerFirst } from 'es-toolkit/compat'; lowerFirst(123); // '123' lowerFirst(null); // '' lowerFirst(undefined); // '' ``` #### Parameters * `str` (`string`, optional): The string to convert the first character to lowercase. #### Returns (`string`): Returns the string with the first character converted to lowercase. --- --- url: /reference/compat/util/lt.md --- # lt (Lodash Compatibility) ::: warning Use the `<` operator instead This `lt` function performs slower due to additional processing like `toNumber` function calls and string type checking. Instead, use the faster and more modern `<` operator. ::: Checks if value is less than other. ```typescript const result = lt(value, other); ``` ## Usage ### `lt(value, other)` Use `lt` when you want to compare two values to check if the first value is less than the second. Strings are compared lexicographically, and other types are converted to numbers for comparison. ```typescript import { lt } from 'es-toolkit/compat'; lt(1, 3); // Returns: true lt(3, 3); // Returns: false lt(3, 1); // Returns: false // String comparison (lexicographical) lt('abc', 'def'); // Returns: true lt('def', 'abc'); // Returns: false // Other types are converted to numbers for comparison lt('5', 10); // Returns: true (5 < 10) lt(null, 1); // Returns: true (0 < 1) ``` #### Parameters * `value` (`unknown`): The first value to compare. * `other` (`unknown`): The second value to compare. #### Returns (`boolean`): Returns `true` if the first value is less than the second, `false` otherwise. --- --- url: /reference/compat/util/lte.md --- # lte (Lodash Compatibility) ::: warning Use the `<=` operator instead This `lte` function performs slower due to additional processing like `toNumber` function calls and string type checking. Instead, use the faster and more modern `<=` operator. ::: Checks if value is less than or equal to other. ```typescript const result = lte(value, other); ``` ## Usage ### `lte(value, other)` Use `lte` when you want to compare two values to check if the first value is less than or equal to the second. Strings are compared lexicographically, and other types are converted to numbers for comparison. ```typescript import { lte } from 'es-toolkit/compat'; lte(1, 3); // Returns: true lte(3, 3); // Returns: true lte(3, 1); // Returns: false // String comparison (lexicographical) lte('abc', 'def'); // Returns: true lte('def', 'abc'); // Returns: false // Other types are converted to numbers for comparison lte('10', 5); // Returns: false (10 <= 5) lte(null, 0); // Returns: true (0 <= 0) ``` #### Parameters * `value` (`unknown`): The first value to compare. * `other` (`unknown`): The second value to compare. #### Returns (`boolean`): Returns `true` if the first value is less than or equal to the second, `false` otherwise. --- --- url: /reference/set/map.md --- # map (for `Set`s) Creates a new Set with elements transformed by the provided function. ```typescript const transformed = map(set, getNewValue); ``` ::: info This function is available exclusively from `es-toolkit/set` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `map(set, getNewValue)` Use `map` when you want to transform the elements of a Set. Provide a function that generates a new value from each element, and it returns a new Set with the transformed elements. ```typescript import { map } from 'es-toolkit/set'; const set = new Set([1, 2, 3]); const result = map(set, value => value * 2); // Result: Set(3) { 2, 4, 6 } ``` You can transform elements in various ways. ```typescript import { map } from 'es-toolkit/set'; // Transform strings const names = new Set(['alice', 'bob', 'charlie']); const uppercased = map(names, name => name.toUpperCase()); // Result: Set(3) { 'ALICE', 'BOB', 'CHARLIE' } // Transform objects const prices = new Set([10, 20, 30]); const products = map(prices, price => ({ price, currency: 'USD' })); // Result: Set with objects { price: 10, currency: 'USD' }, etc. // Extract properties const users = new Set([ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, ]); const ids = map(users, user => user.id); // Result: Set(2) { 1, 2 } ``` #### Parameters * `set` (`Set`): The Set to transform. * `getNewValue` (`(value: T, value2: T, set: Set) => U`): A function that generates a new value from an element. #### Returns (`Set`): A new Set with transformed elements. --- --- url: /reference/compat/array/map.md --- # map (Lodash compatibility) ::: warning Use `Array.prototype.map` This `map` function operates slowly due to additional features such as handling `null` or `undefined`, object iteration, and property extraction. When transforming arrays, JavaScript's built-in `Array.prototype.map` method is faster and simpler. Instead, use the faster and more modern `Array.prototype.map`. ::: Transforms each element of an array or object to create a new array. ```typescript const mapped = map(collection, iteratee); ``` ## Usage ### `map(collection, iteratee)` Use `map` when you want to transform each element of an array, object, or array-like object. It executes an iteratee function on each element and returns the results as a new array. ```typescript import { map } from 'es-toolkit/compat'; // Double each element of an array map([1, 2, 3], x => x * 2); // Returns: [2, 4, 6] // Transform object values const obj = { a: 1, b: 2 }; map(obj, (value, key) => `${key}:${value}`); // Returns: ['a:1', 'b:2'] // Extract properties const users = [ { name: 'John', age: 30 }, { name: 'Jane', age: 25 }, ]; map(users, 'name'); // Returns: ['John', 'Jane'] ``` `null` or `undefined` are treated as empty arrays. ```typescript import { map } from 'es-toolkit/compat'; map(null, x => x); // [] map(undefined, x => x); // [] ``` You can extract nested properties by specifying a property path as a string. ```typescript import { map } from 'es-toolkit/compat'; const users = [{ info: { name: 'John' } }, { info: { name: 'Jane' } }]; map(users, 'info.name'); // Returns: ['John', 'Jane'] ``` When passing an object, it checks if each element matches that object. ```typescript import { map } from 'es-toolkit/compat'; const users = [ { name: 'John', age: 30 }, { name: 'Jane', age: 25 }, ]; map(users, { age: 30 }); // Returns: [true, false] ``` #### Parameters * `collection` (`T[] | ArrayLike | Record | null | undefined`): The array or object to iterate over. * `iteratee` (`function | string | object`, optional): The function to execute on each element, a property path, or an object to match. If not provided, returns each element as is. * When it's a function, it's called in the form `(value, key, collection)`. * When it's a string, it extracts that property. * When it's an object, it checks if each element matches the object. #### Returns (`U[]`): Returns a new array of transformed values. --- --- url: /reference/array/mapAsync.md --- # mapAsync Transforms each element in an array using an async function and returns a new array. ```typescript const transformed = await mapAsync(array, callback); ``` ## Reference ### `mapAsync(array, callback, options?)` Use `mapAsync` to perform async transformation operations for each element in an array. It's useful when you need to process each element asynchronously, such as API calls or database queries. ```typescript import { mapAsync } from 'es-toolkit/array'; // Fetch detailed information for each user. const users = [{ id: 1 }, { id: 2 }, { id: 3 }]; const userDetails = await mapAsync(users, async user => { return await fetchUserDetails(user.id); }); // Returns: [{ id: 1, name: '...' }, { id: 2, name: '...' }, { id: 3, name: '...' }] // Limit concurrency. const numbers = [1, 2, 3, 4, 5]; const results = await mapAsync(numbers, async n => await slowOperation(n), { concurrency: 2 }); // Only 2 operations run concurrently at most. ``` The `concurrency` option allows you to limit concurrent executions to control server load or respect API rate limits. If not specified, all operations run concurrently. ```typescript import { mapAsync } from 'es-toolkit/array'; // Transform a large number of images, limiting concurrent processing to consider server load. const imageUrls = [...]; // Many image URLs const processedImages = await mapAsync( imageUrls, async (url) => await processImage(url), { concurrency: 5 } ); // Only 5 images are processed at a time at most. ``` #### Parameters * `array` (`readonly T[]`): The array to transform. * `callback` (`(item: T, index: number, array: readonly T[]) => Promise`): An async function that transforms each element. * `options` (`MapAsyncOptions`, optional): Options to control concurrency. * `concurrency` (`number`, optional): Maximum number of concurrent operations. If not specified, all operations run concurrently. #### Returns (`Promise`): A promise that resolves to a new array of transformed values. --- --- url: /reference/object/mapKeys.md --- # mapKeys Returns a new object with keys transformed through a function. ```typescript const newObj = mapKeys(object, getNewKey); ``` ## Usage ### `mapKeys(object, getNewKey)` Use `mapKeys` when you want to create a new object by transforming each key. Values remain the same, and only the keys are changed to the results of the `getNewKey` function. ```typescript import { mapKeys } from 'es-toolkit/object'; // Add prefix to keys const obj = { a: 1, b: 2 }; const prefixed = mapKeys(obj, (value, key) => `prefix_${key}`); // prefixed becomes { prefix_a: 1, prefix_b: 2 } // Combine key and value to create new keys const combined = mapKeys(obj, (value, key) => `${key}${value}`); // combined becomes { a1: 1, b2: 2 } // Convert keys to uppercase const uppercased = mapKeys(obj, (value, key) => key.toString().toUpperCase()); // uppercased becomes { A: 1, B: 2 } ``` #### Parameters * `object` (`T extends Record`): The object to transform keys from. * `getNewKey` (`(value: T[keyof T], key: keyof T, object: T) => K`): A function that generates new keys. Receives value, key, and the entire object as parameters. #### Returns (`Record`): Returns a new object with transformed keys. --- --- url: /reference/map/mapKeys.md --- # mapKeys (for `Map`s) Creates a new Map with the same values but with keys transformed by the provided function. ```typescript const transformed = mapKeys(map, getNewKey); ``` ::: info This function is available exclusively from `es-toolkit/map` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `mapKeys(map, getNewKey)` Use `mapKeys` when you want to transform the keys of a Map while keeping the values unchanged. Provide a function that generates a new key from each entry, and it returns a new Map with the transformed keys. ```typescript import { mapKeys } from 'es-toolkit/map'; const map = new Map([ ['a', 1], ['b', 2], ['c', 3], ]); const result = mapKeys(map, (value, key) => key.toUpperCase()); // Result: // Map(3) { // 'A' => 1, // 'B' => 2, // 'C' => 3 // } ``` You can transform keys in various ways. ```typescript import { mapKeys } from 'es-toolkit/map'; // Add prefix to keys const categories = new Map([ ['fruit', ['apple', 'banana']], ['vegetable', ['carrot', 'potato']], ]); const prefixed = mapKeys(categories, (value, key) => `category_${key}`); // Result: Map with keys 'category_fruit', 'category_vegetable' // Transform based on value const scores = new Map([ ['alice', 95], ['bob', 87], ['charlie', 92], ]); const ranked = mapKeys(scores, (value, key) => (value >= 90 ? `top_${key}` : key)); // Result: Map with keys 'top_alice', 'bob', 'top_charlie' ``` #### Parameters * `map` (`Map`): The Map to transform. * `getNewKey` (`(value: V, key: K, object: Map) => K`): A function that generates a new key from a value-key pair. #### Returns (`Map`): A new Map with transformed keys and the same values. --- --- url: /reference/compat/object/mapKeys.md --- # mapKeys (Lodash compatibility) ::: warning Use `mapKeys` from `es-toolkit` This `mapKeys` function is relatively slow due to handling `null` or `undefined` and the `iteratee` conversion process. Use the faster and more modern [`mapKeys`](../../object/mapKeys.md) from `es-toolkit` instead. ::: Creates a new object by transforming keys while keeping values the same. ```typescript const result = mapKeys(obj, iteratee); ``` ## Usage ### `mapKeys(object, iteratee)` Transforms each key in an object using the `iteratee` function to create a new object. Values remain unchanged while only keys are modified. Useful for transforming or normalizing object keys. ```typescript import { mapKeys } from 'es-toolkit/compat'; // Add prefix to keys const obj = { a: 1, b: 2, c: 3 }; const result = mapKeys(obj, (value, key) => 'prefix_' + key); // Result: { prefix_a: 1, prefix_b: 2, prefix_c: 3 } // Convert keys to uppercase const data = { name: 'John', age: 30 }; const uppercased = mapKeys(data, (value, key) => key.toUpperCase()); // Result: { NAME: 'John', AGE: 30 } // Convert array indices to keys const arr = ['apple', 'banana', 'orange']; const indexed = mapKeys(arr, (value, index) => `item_${index}`); // Result: { item_0: 'apple', item_1: 'banana', item_2: 'orange' } // Create new keys by combining key and value const scores = { math: 90, science: 85, english: 92 }; const detailed = mapKeys(scores, (value, key) => `${key}_score_${value}`); // Result: { math_score_90: 90, science_score_85: 85, english_score_92: 92 } ``` `null` or `undefined` are treated as empty objects. ```typescript import { mapKeys } from 'es-toolkit/compat'; mapKeys(null, iteratee); // {} mapKeys(undefined, iteratee); // {} ``` #### Parameters * `object` (`ArrayLike | T | null | undefined`): The object or array to transform keys from. * `iteratee` (`ListIteratee | ObjectIteratee`, optional): The function to transform each key. Defaults to the `identity` function. #### Returns (`Record | Record`): Returns a new object with transformed keys. --- --- url: /reference/object/mapValues.md --- # mapValues Returns a new object with values transformed through a function. ```typescript const newObj = mapValues(object, getNewValue); ``` ## Usage ### `mapValues(object, getNewValue)` Use `mapValues` when you want to create a new object by transforming each value. Keys remain the same, and only the values are changed to the results of the `getNewValue` function. ```typescript import { mapValues } from 'es-toolkit/object'; // Double all values const numbers = { a: 1, b: 2, c: 3 }; const doubled = mapValues(numbers, value => value * 2); // doubled becomes { a: 2, b: 4, c: 6 } // Convert string values to uppercase const strings = { first: 'hello', second: 'world' }; const uppercased = mapValues(strings, value => value.toUpperCase()); // uppercased becomes { first: 'HELLO', second: 'WORLD' } // Use both key and value const scores = { alice: 85, bob: 90, charlie: 95 }; const grades = mapValues(scores, (value, key) => `${key}: ${value >= 90 ? 'A' : 'B'}`); // grades becomes { alice: 'alice: B', bob: 'bob: A', charlie: 'charlie: A' } ``` #### Parameters * `object` (`T extends object`): The object to transform values from. * `getNewValue` (`(value: T[K], key: K, object: T) => V`): A function that generates new values. Receives value, key, and the entire object as parameters. #### Returns (`Record`): Returns a new object with transformed values. --- --- url: /reference/map/mapValues.md --- # mapValues (for `Map`s) Creates a new Map with the same keys but with values transformed by the provided function. ```typescript const transformed = mapValues(map, getNewValue); ``` ::: info This function is available exclusively from `es-toolkit/map` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `mapValues(map, getNewValue)` Use `mapValues` when you want to transform the values of a Map while keeping the keys unchanged. Provide a function that generates a new value from each entry, and it returns a new Map with the transformed values. ```typescript import { mapValues } from 'es-toolkit/map'; const map = new Map([ ['a', 1], ['b', 2], ['c', 3], ]); const result = mapValues(map, value => value * 2); // Result: // Map(3) { // 'a' => 2, // 'b' => 4, // 'c' => 6 // } ``` You can transform values in various ways. ```typescript import { mapValues } from 'es-toolkit/map'; // Format values const prices = new Map([ ['apple', 1.5], ['banana', 0.75], ['orange', 2.0], ]); const formatted = mapValues(prices, value => `$${value.toFixed(2)}`); // Result: Map with values '$1.50', '$0.75', '$2.00' // Transform based on key const inventory = new Map([ ['premium_item', 10], ['standard_item', 20], ['basic_item', 30], ]); const adjusted = mapValues(inventory, (value, key) => (key.startsWith('premium_') ? value * 1.5 : value)); // Result: Map with values 15, 20, 30 ``` #### Parameters * `map` (`Map`): The Map to transform. * `getNewValue` (`(value: V, key: K, object: Map) => V`): A function that generates a new value from a value-key pair. #### Returns (`Map`): A new Map with the same keys and transformed values. --- --- url: /reference/compat/object/mapValues.md --- # mapValues (Lodash compatibility) ::: warning Use `mapValues` from `es-toolkit` This `mapValues` function is relatively slow due to handling `null` or `undefined` and the `iteratee` conversion process. Use the faster and more modern [`mapValues`](../../object/mapValues.md) from `es-toolkit` instead. ::: Creates a new object by transforming values while keeping keys the same. ```typescript const result = mapValues(obj, iteratee); ``` ## Usage ### `mapValues(object, iteratee)` Transforms each value in an object using the `iteratee` function to create a new object. Keys remain unchanged while only values are modified. Can handle strings, arrays, and objects. Useful for transforming or calculating data. ```typescript import { mapValues } from 'es-toolkit/compat'; // Transform object values const obj = { a: 1, b: 2, c: 3 }; const doubled = mapValues(obj, value => value * 2); // Result: { a: 2, b: 4, c: 6 } // Convert strings to uppercase const names = { first: 'john', last: 'doe' }; const uppercased = mapValues(names, value => value.toUpperCase()); // Result: { first: 'JOHN', last: 'DOE' } // Transform each character in a string const str = 'abc'; const charMap = mapValues(str, char => char.toUpperCase()); // Result: { '0': 'A', '1': 'B', '2': 'C' } // Convert array to object const arr = [10, 20, 30]; const arrMap = mapValues(arr, (value, index) => value + index); // Result: { '0': 10, '1': 21, '2': 32 } // Extract values using property path const users = { user1: { profile: { name: 'Alice' } }, user2: { profile: { name: 'Bob' } }, }; const userNames = mapValues(users, 'profile.name'); // Result: { user1: 'Alice', user2: 'Bob' } ``` `null` or `undefined` are treated as empty objects. ```typescript import { mapValues } from 'es-toolkit/compat'; mapValues(null, iteratee); // {} mapValues(undefined, iteratee); // {} ``` #### Parameters * `object` (`string | T[] | T | null | undefined`): The object, array, or string to transform values from. * `iteratee` (`ValueIteratee`, optional): The function, property path, or matching object to transform each value. Defaults to the `identity` function. #### Returns (`Record | { [P in keyof T]: U } | Record | Record | Partial`): Returns a new object with transformed values. --- --- url: /reference/compat/predicate/matches.md --- # matches (Lodash Compatibility) Creates a function that checks for partial matching with a given pattern. ```typescript const matcher = matches(pattern); ``` ## Usage ### `matches(source)` Use `matches` when you need to create a function that checks if objects or arrays match a specific pattern in structure and values. Useful for array filtering or object searching. ```typescript import { matches } from 'es-toolkit/compat'; // Object pattern matching const userMatcher = matches({ age: 25, department: 'Engineering' }); const users = [ { name: 'Alice', age: 25, department: 'Engineering' }, { name: 'Bob', age: 30, department: 'Marketing' }, { name: 'Charlie', age: 25, department: 'Engineering' }, ]; const engineeringUsers = users.filter(userMatcher); // [{ name: 'Alice', age: 25, department: 'Engineering' }, // { name: 'Charlie', age: 25, department: 'Engineering' }] // Nested object pattern const profileMatcher = matches({ profile: { city: 'Seoul', verified: true }, }); const profiles = [ { name: 'Kim', profile: { city: 'Seoul', verified: true, score: 100 } }, { name: 'Lee', profile: { city: 'Busan', verified: true } }, { name: 'Park', profile: { city: 'Seoul', verified: false } }, ]; const seoulVerifiedUsers = profiles.filter(profileMatcher); // [{ name: 'Kim', profile: { city: 'Seoul', verified: true, score: 100 } }] // Array pattern matching const arrayMatcher = matches([2, 4]); const arrays = [ [1, 2, 3, 4, 5], [2, 4, 6], [1, 3, 5], ]; const matchingArrays = arrays.filter(arrayMatcher); // [[1, 2, 3, 4, 5], [2, 4, 6]] // Empty pattern matches all values const emptyMatcher = matches({}); emptyMatcher({ anything: 'value' }); // true emptyMatcher([]); // true emptyMatcher(null); // true ``` #### Parameters * `source` (`unknown`): The object or value that serves as the match pattern. #### Returns (`(target: unknown) => boolean`): Returns a function that checks if the given value partially matches the pattern. --- --- url: /reference/compat/predicate/matchesProperty.md --- # matchesProperty (Lodash Compatibility) Creates a function that checks if a specific property matches a given value. ```typescript const checker = matchesProperty(path, value); ``` ## Usage ### `matchesProperty(property, source)` Use `matchesProperty` when you need to create a function that checks if an object's specific property matches a given value. Useful for array filtering or object searching. ```typescript import { matchesProperty } from 'es-toolkit/compat'; // Simple property check const checkName = matchesProperty('name', 'Alice'); const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Alice', age: 35 }, ]; const aliceUsers = users.filter(checkName); // [{ name: 'Alice', age: 25 }, { name: 'Alice', age: 35 }] // Nested property check (array path) const checkCity = matchesProperty(['address', 'city'], 'Seoul'); const profiles = [ { name: 'Kim', address: { city: 'Seoul', district: 'Gangnam' } }, { name: 'Lee', address: { city: 'Busan', district: 'Haeundae' } }, { name: 'Park', address: { city: 'Seoul', district: 'Mapo' } }, ]; const seoulUsers = profiles.filter(checkCity); // [{ name: 'Kim', address: { city: 'Seoul', district: 'Gangnam' } }, // { name: 'Park', address: { city: 'Seoul', district: 'Mapo' } }] // Deep path as string const checkScore = matchesProperty('stats.game.score', 100); const players = [ { name: 'Player1', stats: { game: { score: 100, level: 5 } } }, { name: 'Player2', stats: { game: { score: 95, level: 4 } } }, { name: 'Player3', stats: { game: { score: 100, level: 6 } } }, ]; const perfectScorers = players.filter(checkScore); // [{ name: 'Player1', stats: { game: { score: 100, level: 5 } } }, // { name: 'Player3', stats: { game: { score: 100, level: 6 } } }] // Matching with complex objects const checkRole = matchesProperty('role', { type: 'admin', permissions: ['read', 'write'] }); const accounts = [ { user: 'Alice', role: { type: 'admin', permissions: ['read', 'write'] } }, { user: 'Bob', role: { type: 'user', permissions: ['read'] } }, { user: 'Charlie', role: { type: 'admin', permissions: ['read', 'write'] } }, ]; const admins = accounts.filter(checkRole); // [{ user: 'Alice', role: { type: 'admin', permissions: ['read', 'write'] } }, // { user: 'Charlie', role: { type: 'admin', permissions: ['read', 'write'] } }] ``` #### Parameters * `property` (`PropertyKey | PropertyKey[]`): The property path to check. Can be a string, array, or dot-separated path. * `source` (`unknown`): The value to compare against the property value. #### Returns (`(target: unknown) => boolean`): Returns a function that checks if the given object's property matches the value. --- --- url: /reference/compat/math/max.md --- # max (Lodash Compatibility) ::: warning Use `Math.max` This `max` function works slowly due to additional function calls and `null`/`undefined` handling. Use the faster and more modern `Math.max(...array)` instead. ::: Finds the maximum value in an array. ```typescript const result = max(items); ``` ## Usage ### `max(items?)` Use `max` when you want to find the largest value in an array. ```typescript import { max } from 'es-toolkit/compat'; // Maximum value in number array max([1, 2, 3]); // Returns: 3 max([10, 5, 8, 20]); // Returns: 20 // Maximum value in string array (lexicographical order) max(['a', 'b', 'c']); // Returns: 'c' max(['apple', 'banana', 'cherry']); // Returns: 'cherry' // Empty array or null/undefined max([]); // Returns: undefined max(null); // Returns: undefined max(undefined); // Returns: undefined ``` Negative numbers are also handled correctly. ```typescript import { max } from 'es-toolkit/compat'; max([-1, -5, -3]); // Returns: -1 max([0, -2, 5, -10]); // Returns: 5 ``` #### Parameters * `items` (`ArrayLike | null | undefined`, optional): The array to find the maximum value from. #### Returns (`T | undefined`): Returns the largest value in the array. If the array is empty or null/undefined, returns undefined. --- --- url: /reference/array/maxBy.md --- # maxBy Returns the element with the maximum value from the array based on the value returned by the transformation function. ```typescript const max = maxBy(items, getValue); ``` ## Usage ### `maxBy(items, getValue)` Use `maxBy` when you want to transform elements in an array to numeric values using a transformation function and find the original element with the largest value. It returns `undefined` for an empty array. ```typescript import { maxBy } from 'es-toolkit/array'; // Find the element with the maximum value for a specific property in an object array. const people = [ { name: 'john', age: 30 }, { name: 'jane', age: 28 }, { name: 'joe', age: 26 }, ]; maxBy(people, person => person.age); // Returns: { name: 'john', age: 30 } // Find the element with the largest absolute value in a number array. const numbers = [-10, -5, 0, 5, 15]; maxBy(numbers, x => Math.abs(x)); // Returns: 15 ``` It returns `undefined` for an empty array. ```typescript import { maxBy } from 'es-toolkit/array'; maxBy([], x => x.value); // undefined ``` #### Parameters * `items` (`T[]`): The array to find the element with the maximum value. * `getValue` (`(element: T, index: number, array: readonly T[]) => number`): A function that transforms each element into a number. It receives the element, its index, and the array. #### Returns (`T | undefined`): The element with the largest value returned by the transformation function. Returns `undefined` if the array is empty. ## Examples ```typescript // Using index parameter const items = [{ value: 10 }, { value: 20 }, { value: 15 }]; maxBy(items, (item, index) => item.value + index); // Returns: { value: 20 } // Using array parameter maxBy(items, (item, _index, array) => item.value * array.length); // Returns: { value: 20 } ``` --- --- url: /reference/compat/math/maxBy.md --- # maxBy (Lodash Compatibility) ::: warning Use [maxBy](../../array/maxBy.md) from es-toolkit This `maxBy` function works slowly due to iteratee function processing and type conversion. Use the faster and more modern [maxBy](../../array/maxBy.md) from `es-toolkit` instead. ::: Finds the element with the maximum value based on a condition. ```typescript const maxItem = maxBy(array, iteratee); ``` ## Usage ### `maxBy(array, iteratee)` Finds the element in an array that has the largest value when computed by a function. ```typescript import { maxBy } from 'es-toolkit/compat'; // Find element with maximum property in object array const people = [ { name: 'John', age: 25 }, { name: 'Jane', age: 30 }, { name: 'Bob', age: 35 }, ]; maxBy(people, person => person.age); // Returns: { name: 'Bob', age: 35 } // Can also use property name maxBy(people, 'age'); // Returns: { name: 'Bob', age: 35 } ``` Transform values with a function to find the maximum. ```typescript import { maxBy } from 'es-toolkit/compat'; const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; maxBy(items, x => x.a); // Returns: { a: 3 } const numbers = [-1, -2, -3]; maxBy(numbers, x => Math.abs(x)); // Returns: -3 (element with largest absolute value) ``` Access array elements by index. ```typescript import { maxBy } from 'es-toolkit/compat'; const arrays = [ [1, 2], [3, 4], [0, 5], ]; maxBy(arrays, 0); // Array with maximum first element // Returns: [3, 4] maxBy(arrays, 1); // Array with maximum second element // Returns: [0, 5] ``` Find elements matching specific property values. ```typescript import { maxBy } from 'es-toolkit/compat'; const users = [ { name: 'John', age: 25, active: true }, { name: 'Jane', age: 30, active: false }, { name: 'Bob', age: 35, active: true }, ]; // First element among those with active: true maxBy(users, ['active', true]); // Returns: { name: 'John', age: 25, active: true } // Specify condition as object maxBy(users, { active: true }); // Returns: { name: 'John', age: 25, active: true } ``` Empty arrays return undefined. ```typescript import { maxBy } from 'es-toolkit/compat'; maxBy([], x => x.a); // Returns: undefined maxBy(null); // Returns: undefined maxBy(undefined); // Returns: undefined ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to search. * `iteratee` (`ValueIteratee`, optional): The function, property name, or condition to apply to each element. #### Returns (`T | undefined`): Returns the element with the largest value based on the condition. Returns `undefined` if the array is empty. --- --- url: /reference/math/mean.md --- # mean Calculates the average of an array of numbers. ```typescript const average = mean(nums); ``` ## Usage ### `mean(nums)` Use `mean` when you want to find the average value of an array of numbers. It calculates the average by adding all numbers together and dividing by the length of the array. If given an empty array, it returns `NaN`. ```typescript import { mean } from 'es-toolkit/math'; // Calculate the average of an array of numbers const numbers = [1, 2, 3, 4, 5]; const result = mean(numbers); // result is 3 ((1 + 2 + 3 + 4 + 5) / 5 = 15 / 5 = 3) // Calculate the average of decimal numbers const decimals = [1.5, 2.5, 3.5]; const decimalResult = mean(decimals); // decimalResult is 2.5 // Returns NaN for an empty array const emptyResult = mean([]); // emptyResult is NaN ``` #### Parameters * `nums` (`readonly number[]`): An array of numbers to calculate the average. #### Returns (`number`): Returns the average of all numbers in the array. Returns `NaN` if the array is empty. --- --- url: /reference/compat/math/mean.md --- # mean (Lodash Compatibility) ::: warning Use [mean](../../math/mean.md) from es-toolkit This `mean` function works slowly due to type conversion and null/undefined handling. Use the faster and more modern [mean](../../math/mean.md) from `es-toolkit` instead. ::: Calculates the average value of an array. ```typescript const average = mean(array); ``` ## Usage ### `mean(array)` Calculates the average value of a number array. ```typescript import { mean } from 'es-toolkit/compat'; // Number array mean([1, 2, 3, 4, 5]); // Returns: 3 mean([10, 20, 30]); // Returns: 20 mean([1.5, 2.5, 3.5]); // Returns: 2.5 ``` Empty arrays return NaN. ```typescript import { mean } from 'es-toolkit/compat'; mean([]); // Returns: NaN mean(null); // Returns: NaN mean(undefined); // Returns: NaN ``` Invalid values are treated as 0 and included in the calculation. ```typescript import { mean } from 'es-toolkit/compat'; mean([1, undefined, 2, null, 3]); // Returns: 1.2 (1 + 2 + 3) / 5 = 1.2 ``` Strings will be concatenated. ```typescript import { mean } from 'es-toolkit/compat'; mean(['1', '2', '3']); // Returns: 41 (123 / 3 = 41) ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array containing numbers to calculate the average from. #### Returns (`number`): Returns the average value of the array. Returns `NaN` if the array is empty. --- --- url: /reference/math/meanBy.md --- # meanBy Calculates the average of an array by applying the `getValue` function to each element. ```typescript const average = meanBy(items, getValue); ``` ## Usage ### `meanBy(items, getValue)` Use `meanBy` when you want to find the average of the results of applying a function to each element of an array. It's useful for calculating the average of a specific property from an array of objects or for finding the average after transforming each element. If given an empty array, it returns `NaN`. ```typescript import { meanBy } from 'es-toolkit/math'; // Calculate the average of a specific property from an array of objects const people = [{ age: 23 }, { age: 25 }, { age: 27 }]; const averageAge = meanBy(people, person => person.age); // averageAge is 25 ((23 + 25 + 27) / 3 = 75 / 3 = 25) // Calculate the average of string lengths const words = ['apple', 'banana', 'cherry']; const averageLength = meanBy(words, word => word.length); // averageLength is approximately 5.67 ((5 + 6 + 6) / 3 ≈ 5.67) // Returns NaN for an empty array const emptyResult = meanBy([], x => x); // emptyResult is NaN ``` #### Parameters * `items` (`readonly T[]`): An array to calculate the average. * `getValue` (`(element: T) => number`): A function that selects a numeric value from each element. #### Returns (`number`): Returns the average of all values as determined by the `getValue` function. Returns `NaN` if the array is empty. --- --- url: /reference/compat/math/meanBy.md --- # meanBy (Lodash Compatibility) ::: warning Use [meanBy](../../math/meanBy.md) from es-toolkit This `meanBy` function works slowly due to iteratee function processing and type conversion. Use the faster and more modern [meanBy](../../math/meanBy.md) from `es-toolkit` instead. ::: Calculates the average of values that meet a condition. ```typescript const average = meanBy(array, iteratee); ``` ## Usage ### `meanBy(array, iteratee)` Calculates the average of the results of applying a function to each element in an array. ```typescript import { meanBy } from 'es-toolkit/compat'; // Average of specific property in object array const people = [ { name: 'John', age: 25 }, { name: 'Jane', age: 30 }, { name: 'Bob', age: 35 }, ]; meanBy(people, person => person.age); // Returns: 30 // Can also use property name meanBy(people, 'age'); // Returns: 30 ``` Transform values with a function to calculate the average. ```typescript import { meanBy } from 'es-toolkit/compat'; const numbers = [1.5, 2.7, 3.2, 4.8]; meanBy(numbers, x => Math.floor(x)); // Returns: 2.5 (1 + 2 + 3 + 4) / 4 const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; meanBy(items, x => x.a); // Returns: 2 ``` Access array elements by index. ```typescript import { meanBy } from 'es-toolkit/compat'; const arrays = [[2], [3], [1]]; meanBy(arrays, 0); // Average of first elements // Returns: 2 ``` Calculate only for elements matching specific property values. ```typescript import { meanBy } from 'es-toolkit/compat'; const users = [ { name: 'John', age: 25, active: true }, { name: 'Jane', age: 30, active: false }, { name: 'Bob', age: 35, active: true }, ]; // Only active users meanBy(users, { active: true }); // Returns: 0.6666666 (2 out of 3 users are active) ``` Empty arrays return NaN. ```typescript import { meanBy } from 'es-toolkit/compat'; meanBy([], x => x.a); // Returns: NaN meanBy(null); // Returns: NaN meanBy(undefined); // Returns: NaN ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to process. * `iteratee` (`ValueIteratee`, optional): The function, property name, or condition to apply to each element. #### Returns (`number`): Returns the average of values that meet the condition. Returns `NaN` if the array is empty. --- --- url: /reference/math/median.md --- # median Calculates the median of an array of numbers. ```typescript const middle = median(nums); ``` ## Usage ### `median(nums)` Use `median` when you want to find the median value of an array of numbers. After sorting the array in ascending order, it finds the value located in the middle. For an array with an odd number of elements, it returns the exact middle value, and for an array with an even number of elements, it returns the average of the two middle values. If given an empty array, it returns `NaN`. ```typescript import { median } from 'es-toolkit/math'; // Calculate the median of an array with an odd number of elements const oddNumbers = [1, 2, 3, 4, 5]; const oddResult = median(oddNumbers); // oddResult is 3 (the middle value in the sorted array [1, 2, 3, 4, 5]) // Calculate the median of an array with an even number of elements const evenNumbers = [1, 2, 3, 4]; const evenResult = median(evenNumbers); // evenResult is 2.5 ((2 + 3) / 2 = 2.5) // Unsorted arrays are automatically sorted const unordered = [3, 1, 4, 1, 5]; const unorderedResult = median(unordered); // unorderedResult is 3 (the middle value after sorting to [1, 1, 3, 4, 5]) // Returns NaN for an empty array const emptyResult = median([]); // emptyResult is NaN ``` #### Parameters * `nums` (`readonly number[]`): An array of numbers to calculate the median. #### Returns (`number`): Returns the median of all numbers in the array. Returns `NaN` if the array is empty. --- --- url: /reference/math/medianBy.md --- # medianBy Calculates the median of an array by applying the `getValue` function to each element. ```typescript const middle = medianBy(items, getValue); ``` ## Usage ### `medianBy(items, getValue)` Use `medianBy` when you want to find the median of the results of applying a function to each element of an array. It's useful for calculating the median of a specific property from an array of objects or for finding the median after transforming each element. For an array with an odd number of elements, it returns the exact middle value, and for an array with an even number of elements, it returns the average of the two middle values. If given an empty array, it returns `NaN`. ```typescript import { medianBy } from 'es-toolkit/math'; // Calculate the median of a specific property from an array of objects (odd number) const people = [{ age: 23 }, { age: 25 }, { age: 27 }, { age: 29 }, { age: 31 }]; const medianAge = medianBy(people, person => person.age); // medianAge is 27 (the middle value in the sorted ages [23, 25, 27, 29, 31]) // Calculate the median of a specific property from an array of objects (even number) const scores = [{ score: 80 }, { score: 90 }, { score: 85 }, { score: 95 }]; const medianScore = medianBy(scores, item => item.score); // medianScore is 87.5 ((85 + 90) / 2 in the sorted scores [80, 85, 90, 95]) // Calculate the median of string lengths const words = ['cat', 'elephant', 'dog', 'butterfly', 'ant']; const medianLength = medianBy(words, word => word.length); // medianLength is 3 (the middle value when lengths [3, 8, 3, 9, 3] are sorted to [3, 3, 3, 8, 9]) // Returns NaN for an empty array const emptyResult = medianBy([], x => x); // emptyResult is NaN ``` #### Parameters * `items` (`readonly T[]`): An array to calculate the median. * `getValue` (`(element: T) => number`): A function that selects a numeric value from each element. #### Returns (`number`): Returns the median of all values as determined by the `getValue` function. Returns `NaN` if the array is empty. --- --- url: /reference/function/memoize.md --- # memoize Caches function results so it runs faster when called again with the same arguments. ```typescript const memoizedFunc = memoize(func, options); ``` ## Usage ### `memoize(func, options?)` Use `memoize` when you want to optimize performance by caching a function's execution results. When called again with the same arguments, it returns the cached result to avoid duplicate computations. Use this with functions that take a single parameter. If your function takes multiple arguments, combine them into a single object or array. If the argument is compared by reference, such as arrays or objects, you should provide a `getCacheKey` function to generate an appropriate cache key. ```typescript import { memoize } from 'es-toolkit/function'; // Basic usage const add = (x: number) => x + 10; const memoizedAdd = memoize(add); console.log(memoizedAdd(5)); // 15 (computed) console.log(memoizedAdd(5)); // 15 (cached result) console.log(memoizedAdd.cache.size); // 1 // Providing a cache key for array arguments const sum = (arr: number[]) => arr.reduce((sum, n) => sum + n, 0); const memoizedSum = memoize(sum, { getCacheKey: (arr: number[]) => arr.join(','), }); console.log(memoizedSum([1, 2, 3])); // 6 (computed) console.log(memoizedSum([1, 2, 3])); // 6 (cached result) ``` You can also use a custom cache. ```typescript import { memoize, MemoizeCache } from 'es-toolkit/function'; class LRUCache implements MemoizeCache { private cache = new Map(); private maxSize = 100; set(key: K, value: V): void { if (this.cache.size >= this.maxSize) { const firstKey = this.cache.keys().next().value; this.cache.delete(firstKey); } this.cache.set(key, value); } get(key: K): V | undefined { return this.cache.get(key); } has(key: K): boolean { return this.cache.has(key); } delete(key: K): boolean { return this.cache.delete(key); } clear(): void { this.cache.clear(); } get size(): number { return this.cache.size; } } const customCache = new LRUCache(); const memoizedWithCustomCache = memoize(expensiveFunction, { cache: customCache, }); ``` #### Parameters * `func` (`F`): The function to memoize. It must accept only one argument. * `options` (object, optional): Memoization configuration options. * `cache` (`MemoizeCache>`, optional): The cache object to store results. Defaults to a new `Map`. * `getCacheKey` (`(arg: Parameters[0]) => unknown`, optional): A function to generate cache keys. Required when using non-primitive values as arguments. #### Returns (`F & { cache: MemoizeCache> }`): Returns the memoized function. It includes a `cache` property to access the internal cache. --- --- url: /reference/compat/function/memoize.md --- # memoize (Lodash Compatibility) ::: warning Use `es-toolkit`'s `memoize` This `memoize` function operates slowly due to `null` checks in the `resolver` function, complex type handling for the `MapCache` interface, and additional overhead for Lodash compatibility. Instead, use the faster and more modern `es-toolkit`'s [memoize](../../function/memoize.md). ::: Caches function results to improve performance when called with the same arguments. ```typescript const memoizedFunc = memoize(func, resolver); ``` ## Usage ### `memoize(func, resolver)` Use `memoize` when you want to memoize function results to reuse previous results when called with the same arguments. It's useful for expensive calculations or API calls. ```typescript import { memoize } from 'es-toolkit/compat'; // Basic usage function expensiveCalculation(n) { console.log('Calculating...', n); return n * n; } const memoizedCalc = memoize(expensiveCalculation); console.log(memoizedCalc(5)); // 'Calculating... 5', 25 console.log(memoizedCalc(5)); // 25 (cached result, no calculation) console.log(memoizedCalc(10)); // 'Calculating... 10', 100 // Using custom resolver function fetchUserData(userId, includeProfile) { console.log('Fetching user data...', userId, includeProfile); return { id: userId, profile: includeProfile ? 'Profile data' : null }; } // Generate cache key considering all arguments const memoizedFetch = memoize(fetchUserData, (userId, includeProfile) => { return `${userId}_${includeProfile}`; }); memoizedFetch(1, true); // 'Fetching user data... 1 true' memoizedFetch(1, true); // Uses cached result memoizedFetch(1, false); // 'Fetching user data... 1 false' (different cache key) // Accessing and modifying cache console.log(memoizedCalc.cache.get(5)); // 25 memoizedCalc.cache.set(7, 49); // Manually set cache console.log(memoizedCalc(7)); // 49 (uses cached value without calculation) ``` In most cases, it uses a basic hash map, but you can also use custom cache implementations as needed. #### Parameters * `func` (`Function`): The function to memoize. * `resolver` (`Function`, optional): The function to determine the cache key. If not provided, uses the first argument as the key. #### Returns (`Function & { cache: MapCache }`): Returns the memoized function. The returned function has a `cache` property for direct cache access. --- --- url: /reference/object/merge.md --- # merge Deeply merges the source object into the target object, modifying the target object. ```typescript const result = merge(target, source); ``` ## Usage ### `merge(target, source)` Use `merge` when you want to deeply merge two objects. Nested objects and arrays are also merged recursively. Unlike [toMerged](./toMerged.md), this function modifies the original `target` object. ```typescript import { merge } from 'es-toolkit/object'; // Basic object merging const target = { a: 1, b: { x: 1, y: 2 } }; const source = { b: { y: 3, z: 4 }, c: 5 }; const result = merge(target, source); // Both result and target become { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } // Arrays are also merged const arrayTarget = { a: [1, 2], b: { x: 1 } }; const arraySource = { a: [3], b: { y: 2 } }; merge(arrayTarget, arraySource); // arrayTarget becomes { a: [3, 2], b: { x: 1, y: 2 } } // null values are handled appropriately const nullTarget = { a: null }; const nullSource = { a: [1, 2, 3] }; merge(nullTarget, nullSource); // nullTarget becomes { a: [1, 2, 3] } ``` `undefined` values do not overwrite existing values. ```typescript const target = { a: 1, b: 2 }; const source = { b: undefined, c: 3 }; merge(target, source); // target becomes { a: 1, b: 2, c: 3 } (b is not overwritten) ``` #### Parameters * `target` (`T extends Record`): The target object to merge the source object into. This object is modified. * `source` (`S extends Record`): The source object to merge into the target object. #### Returns (`T & S`): Returns the target object with the source object merged in. ## Examples ```typescript const target = { a: 1, b: { x: 1, y: 2 } }; const source = { b: { y: 3, z: 4 }, c: 5 }; const result = merge(target, source); console.log(result); // Output: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } const target = { a: [1, 2], b: { x: 1 } }; const source = { a: [3], b: { y: 2 } }; const result = merge(target, source); console.log(result); // Output: { a: [3, 2], b: { x: 1, y: 2 } } const target = { a: null }; const source = { a: [1, 2, 3] }; const result = merge(target, source); console.log(result); // Output: { a: [1, 2, 3] } ``` ## Demo ::: sandpack ```ts index.ts import { merge } from 'es-toolkit'; const target = { a: 1, b: { x: 1, y: 2 } }; const source = { b: { y: 3, z: 4 }, c: 5 }; const result = merge(target, source); console.log(result); ``` ::: ## Performance Comparison | | [Bundle Size](../../bundle-size.md) | [Performance](../../performance.md) | | ----------------- | ----------------------------------- | ----------------------------------- | | es-toolkit | 271 bytes (97.8% smaller) | 1,952,436 times (3.65× faster) | | es-toolkit/compat | 4,381 bytes (64.9% smaller) | 706,558 times (1.32× faster) | | lodash-es | 12,483 bytes | 533,484 times | --- --- url: /reference/compat/object/merge.md --- # merge (Lodash compatibility) ::: warning Use `merge` from `es-toolkit` This `merge` function is relatively slow as it internally calls the complex `mergeWith` function. Use the faster and more modern [`merge`](../../object/merge.ts) from `es-toolkit` instead. ::: Deeply merges multiple objects into a single object. ```typescript const result = merge(target, ...sources); ``` ## Usage ### `merge(object, ...sources)` Deeply merges one or more source objects into the target object. Nested objects and arrays are recursively merged. If a source object property is `undefined`, it won't overwrite the existing value in the target object. Useful for merging object configurations or applying defaults. ```typescript import { merge } from 'es-toolkit/compat'; // Basic object merge const target = { a: 1, b: { x: 1, y: 2 } }; const source = { b: { y: 3, z: 4 }, c: 5 }; const result = merge(target, source); // Result: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } // Array merge const obj1 = { arr: [1, 2] }; const obj2 = { arr: [3, 4] }; const merged = merge(obj1, obj2); // Result: { arr: [3, 4] } (arrays are replaced) // Multiple object merge const base = { a: 1 }; const ext1 = { b: 2 }; const ext2 = { c: 3 }; const ext3 = { d: 4 }; const combined = merge(base, ext1, ext2, ext3); // Result: { a: 1, b: 2, c: 3, d: 4 } // Nested object merge const config = { api: { url: 'https://api.example.com', timeout: 5000 }, features: { auth: true }, }; const overrides = { api: { timeout: 10000, retries: 3 }, features: { analytics: true }, }; const finalConfig = merge(config, overrides); // Result: { // api: { url: 'https://api.example.com', timeout: 10000, retries: 3 }, // features: { auth: true, analytics: true } // } ``` The target object is modified, so use an empty object to preserve the original. ```typescript import { merge } from 'es-toolkit/compat'; const original = { a: 1, b: { x: 1 } }; const source = { b: { y: 2 } }; // Preserve original const result = merge({}, original, source); // original is not modified ``` #### Parameters * `object` (`any`): The target object to merge into. This object is modified. * `...sources` (`any[]`): The source objects to merge from. #### Returns (`any`): Returns the merged target object. --- --- url: /reference/object/mergeWith.md --- # mergeWith Deeply merges the source object into the target object using a custom merge function, modifying the target object. ```typescript const result = mergeWith(target, source, mergeFunction); ``` ## Usage ### `mergeWith(target, source, merge)` Use `mergeWith` when you want to apply custom merge logic for each property when merging two objects. If the merge function returns `undefined`, the default deep merge logic is used. ```typescript import { mergeWith } from 'es-toolkit/object'; // Add number values during merge const target = { a: 1, b: 2, c: { x: 10 } }; const source = { b: 3, c: { x: 20, y: 30 }, d: 4 }; const result = mergeWith(target, source, (targetValue, sourceValue, key) => { if (typeof targetValue === 'number' && typeof sourceValue === 'number') { return targetValue + sourceValue; // Add numbers } // Returning undefined uses default merge logic }); // Both result and target become { a: 1, b: 5, c: { x: 30, y: 30 }, d: 4 } // Concatenate arrays during merge const arrayTarget = { items: [1, 2], metadata: { count: 2 } }; const arraySource = { items: [3, 4], metadata: { count: 2 } }; mergeWith(arrayTarget, arraySource, (targetValue, sourceValue) => { if (Array.isArray(targetValue) && Array.isArray(sourceValue)) { return targetValue.concat(sourceValue); } }); // arrayTarget becomes { items: [1, 2, 3, 4], metadata: { count: 2 } } // Apply different merge logic based on key const config = { timeout: 1000, retries: 3, features: { featureA: true } }; const updates = { timeout: 2000, retries: 5, features: { featureB: false } }; mergeWith(config, updates, (targetValue, sourceValue, key) => { if (key === 'timeout') { return Math.max(targetValue, sourceValue); // Use larger value for timeout } if (key === 'retries') { return Math.min(targetValue, sourceValue); // Use smaller value for retries } // Use default merge logic for other properties }); // config becomes { timeout: 2000, retries: 3, features: { featureA: true, featureB: false } } ``` #### Parameters * `target` (`T extends Record`): The target object to merge the source object into. This object is modified. * `source` (`S extends Record`): The source object to merge into the target object. * `merge` (`(targetValue: any, sourceValue: any, key: string, target: T, source: S) => any`): A custom merge function. * `targetValue`: The current value in the target object * `sourceValue`: The value in the source object * `key`: The key of the property being merged * `target`: The target object * `source`: The source object #### Returns (`T & S`): Returns the target object with the source object merged in. ## Examples ```typescript const target = { a: 1, b: 2 }; const source = { b: 3, c: 4 }; mergeWith(target, source, (targetValue, sourceValue) => { if (typeof targetValue === 'number' && typeof sourceValue === 'number') { return targetValue + sourceValue; } }); // Output: { a: 1, b: 5, c: 4 } const target = { a: [1], b: [2] }; const source = { a: [3], b: [4] }; const result = mergeWith(target, source, (objValue, srcValue) => { if (Array.isArray(objValue)) { return objValue.concat(srcValue); } }); // Output: { a: [1, 3], b: [2, 4] }) ``` ## Demo ::: sandpack ```ts index.ts import { mergeWith } from 'es-toolkit'; const target = { a: 1, b: 2 }; const source = { b: 3, c: 4 }; const result = mergeWith(target, source, (targetValue, sourceValue) => { if (typeof targetValue === 'number' && typeof sourceValue === 'number') { return targetValue + sourceValue; } }); console.log(result); ``` ::: --- --- url: /reference/compat/object/mergeWith.md --- # mergeWith (Lodash compatibility) ::: warning Use `mergeWith` from `es-toolkit` This `mergeWith` function is relatively slow due to complex type checking, circular reference handling, and special object processing. Use the faster and more modern [`mergeWith`](../../object/mergeWith.md) from `es-toolkit` instead. ::: Deeply merges multiple objects while controlling the merge behavior with a custom function. ```typescript const result = mergeWith(target, ...sources, customizer); ``` ## Usage ### `mergeWith(object, ...sources, customizer)` Deeply merges one or more source objects into the target object, controlling the merge behavior with a customizer function. If the customizer function returns `undefined`, the default merge logic is used. Useful for concatenating arrays or applying special merge rules. ```typescript import { mergeWith } from 'es-toolkit/compat'; // Add numbers const obj1 = { a: 1, b: 2 }; const obj2 = { b: 3, c: 4 }; const result = mergeWith(obj1, obj2, (objValue, srcValue) => { if (typeof objValue === 'number' && typeof srcValue === 'number') { return objValue + srcValue; } }); // Result: { a: 1, b: 5, c: 4 } // Concatenate arrays const arr1 = { items: [1, 2] }; const arr2 = { items: [3, 4] }; const merged = mergeWith(arr1, arr2, (objValue, srcValue) => { if (Array.isArray(objValue)) { return objValue.concat(srcValue); } }); // Result: { items: [1, 2, 3, 4] } // Concatenate strings const str1 = { message: 'Hello' }; const str2 = { message: 'World' }; const combined = mergeWith(str1, str2, (objValue, srcValue, key) => { if (key === 'message' && typeof objValue === 'string') { return objValue + ' ' + srcValue; } }); // Result: { message: 'Hello World' } // Multiple source objects with customizer const base = { scores: [80] }; const quiz1 = { scores: [90] }; const quiz2 = { scores: [85] }; const final = mergeWith(base, quiz1, quiz2, (objValue, srcValue) => { if (Array.isArray(objValue)) { return objValue.concat(srcValue); } }); // Result: { scores: [80, 90, 85] } ``` The customizer function receives various parameters. ```typescript import { mergeWith } from 'es-toolkit/compat'; const customizer = (objValue, srcValue, key, object, source, stack) => { console.log('Merging:', key, objValue, '->', srcValue); // Customize only for specific keys if (key === 'specialField') { return `${objValue}_${srcValue}`; } // Return undefined to use default merge logic return undefined; }; ``` #### Parameters * `object` (`any`): The target object to merge into. This object is modified. * `...sources` (`any[]`): The source objects to merge from. * `customizer` (`MergeWithCustomizer`): The function to customize value assignment. Format: `(objValue, srcValue, key, object, source, stack) => any`. #### Returns (`any`): Returns the merged target object. --- --- url: /reference/compat/util/method.md --- # method (Lodash Compatibility) Creates a function that invokes a method at the specified path with the given arguments. ```typescript const methodFunc = method(path, ...args); ``` ## Usage ### `method(path, ...args)` Creates a function that calls a method at a specific path on an object with predefined arguments. This is useful for reusing method calls in functional programming or with array methods like `map`. ```typescript import { method } from 'es-toolkit/compat'; const object = { a: { b: function (x, y) { return x + y; }, }, }; // Create a method calling function const add = method('a.b', 1, 2); console.log(add(object)); // => 3 // Call methods on each object in an array const objects = [{ calc: { sum: (a, b) => a + b } }, { calc: { sum: (a, b) => a * b } }]; const calculate = method('calc.sum', 5, 3); objects.map(calculate); // => [8, 15] ``` It can handle nested paths as well. ```typescript import { method } from 'es-toolkit/compat'; const obj = { users: { getName: function (prefix) { return prefix + this.name; }, name: 'John', }, }; const getUserName = method('users.getName', 'Mr. '); getUserName(obj); // => 'Mr. John' ``` #### Parameters * `path` (`PropertyKey | PropertyKey[]`): The path of the method to invoke. * `...args` (`any[]`): The arguments to pass to the method. #### Returns (`(object: any) => any`): Returns a function that takes an object and calls the method at the specified path with the given arguments. --- --- url: /reference/compat/util/methodOf.md --- # methodOf (Lodash Compatibility) Creates a function that takes a path and invokes a method on the given object with predefined arguments. ```typescript const pathInvoker = methodOf(object, ...args); ``` ## Usage ### `methodOf(object, ...args)` Creates a function that calls a method on a specific object with predefined arguments. Unlike `method`, this fixes the object and allows you to specify the path later. This is useful when you want to call different methods on the same object with the same arguments. ```typescript import { methodOf } from 'es-toolkit/compat'; const object = { a: { b: function (x, y) { return x + y; }, }, }; // Pre-bind the object and arguments const callMethod = methodOf(object, 1, 2); console.log(callMethod('a.b')); // => 3 // Call multiple paths with the same object and arguments const calculator = { add: (a, b) => a + b, multiply: (a, b) => a * b, subtract: (a, b) => a - b, }; const compute = methodOf(calculator, 10, 5); console.log(compute('add')); // => 15 console.log(compute('multiply')); // => 50 console.log(compute('subtract')); // => 5 ``` It can also be used with nested objects. ```typescript import { methodOf } from 'es-toolkit/compat'; const data = { users: { findById: function (id) { return `User ${id}`; }, findByName: function (name) { return `Found ${name}`; }, }, }; const userFinder = methodOf(data, 'john'); userFinder('users.findById'); // => 'User john' userFinder('users.findByName'); // => 'Found john' ``` #### Parameters * `object` (`object`): The object to invoke methods on. * `...args` (`any[]`): The arguments to pass to the methods. #### Returns (`(path: PropertyKey | PropertyKey[]) => any`): Returns a function that takes a path and calls the method at the specified path on the object with the given arguments. --- --- url: /reference/compat/math/min.md --- # min (Lodash Compatibility) ::: warning Use `Math.min` This `min` function works slowly due to additional function calls and null/undefined handling. Use the faster and more modern `Math.min(...array)` instead. ::: Finds the minimum value in an array. ```typescript const result = min(items); ``` ## Usage ### `min(items?)` Use `min` when you want to find the smallest value in an array. ```typescript import { min } from 'es-toolkit/compat'; // Minimum value in number array min([3, 1, 4, 1, 5, 9]); // Returns: 1 min([10, 5, 8, 20]); // Returns: 5 // Minimum value in string array (lexicographical order) min(['c', 'a', 'b']); // Returns: 'a' min(['cherry', 'apple', 'banana']); // Returns: 'apple' // Empty array or null/undefined min([]); // Returns: undefined min(null); // Returns: undefined min(undefined); // Returns: undefined ``` Negative numbers are also handled correctly. ```typescript import { min } from 'es-toolkit/compat'; min([0, -3, 2, 8, 7]); // Returns: -3 min([-1, -5, -3]); // Returns: -5 ``` #### Parameters * `items` (`ArrayLike | null | undefined`, optional): The array to find the minimum value from. #### Returns (`T | undefined`): Returns the smallest value in the array. If the array is empty or null/undefined, returns undefined. --- --- url: /reference/array/minBy.md --- # minBy Returns the element with the minimum value from the array based on the value returned by the transformation function. ```typescript const min = minBy(items, getValue); ``` ## Usage ### `minBy(items, getValue)` Use `minBy` when you want to transform elements in an array to numeric values using a transformation function and find the original element with the smallest value. It returns `undefined` for an empty array. ```typescript import { minBy } from 'es-toolkit/array'; // Find the element with the minimum value for a specific property in an object array. const people = [ { name: 'john', age: 30 }, { name: 'jane', age: 28 }, { name: 'joe', age: 26 }, ]; minBy(people, person => person.age); // Returns: { name: 'joe', age: 26 } // Find the element with the smallest absolute value in a number array. const numbers = [-10, -5, 0, 5, 15]; minBy(numbers, x => Math.abs(x)); // Returns: 0 ``` It returns `undefined` for an empty array. ```typescript import { minBy } from 'es-toolkit/array'; minBy([], x => x.value); // undefined ``` #### Parameters * `items` (`T[]`): The array to find the element with the minimum value. * `getValue` (`(element: T, index: number, array: readonly T[]) => number`): A function that transforms each element into a number. It receives the element, its index, and the array. #### Returns (`T | undefined`): The element with the smallest value returned by the transformation function. Returns `undefined` if the array is empty. ## Examples ```typescript // Using index parameter const items = [{ value: 10 }, { value: 20 }, { value: 15 }]; minBy(items, (item, index) => item.value + index); // Returns: { value: 10 } // Using array parameter minBy(items, (item, _index, array) => item.value * array.length); // Returns: { value: 10 } ``` --- --- url: /reference/compat/math/minBy.md --- # minBy (Lodash Compatibility) ::: warning Use [minBy](../../array/minBy.md) from es-toolkit This `minBy` function works slowly due to iteratee function processing and type conversion. Use the faster and more modern [minBy](../../array/minBy.md) from `es-toolkit` instead. ::: Finds the element with the minimum value based on a condition. ```typescript const minItem = minBy(array, iteratee); ``` ## Usage ### `minBy(array, iteratee)` Finds the element in an array that has the smallest value when computed by a function. ```typescript import { minBy } from 'es-toolkit/compat'; // Find element with minimum property in object array const people = [ { name: 'John', age: 25 }, { name: 'Jane', age: 30 }, { name: 'Bob', age: 35 }, ]; minBy(people, person => person.age); // Returns: { name: 'John', age: 25 } // Can also use property name minBy(people, 'age'); // Returns: { name: 'John', age: 25 } ``` Transform values with a function to find the minimum. ```typescript import { minBy } from 'es-toolkit/compat'; const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; minBy(items, x => x.a); // Returns: { a: 1 } const numbers = [-1, -2, -3]; minBy(numbers, x => Math.abs(x)); // Returns: -1 (element with smallest absolute value) ``` Access array elements by index. ```typescript import { minBy } from 'es-toolkit/compat'; const arrays = [ [1, 2], [3, 4], [0, 5], ]; minBy(arrays, 0); // Array with minimum first element // Returns: [0, 5] minBy(arrays, 1); // Array with minimum second element // Returns: [1, 2] ``` Find elements matching specific property values. ```typescript import { minBy } from 'es-toolkit/compat'; const users = [ { name: 'John', age: 25, active: true }, { name: 'Jane', age: 30, active: false }, { name: 'Bob', age: 35, active: true }, ]; // First element among those with active: true minBy(users, ['active', true]); // Returns: { name: 'Jane', age: 30, active: false } // Specify condition as object minBy(users, { active: true }); // Returns: { name: 'Jane', age: 30, active: false } ``` Empty arrays return undefined. ```typescript import { minBy } from 'es-toolkit/compat'; minBy([], x => x.a); // Returns: undefined minBy(null); // Returns: undefined minBy(undefined); // Returns: undefined ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to search. * `iteratee` (`ValueIteratee`, optional): The function, property name, or condition to apply to each element. #### Returns (`T | undefined`): Returns the element with the smallest value based on the condition. Returns `undefined` if the array is empty. --- --- url: /reference/compat/math/multiply.md --- # multiply (Lodash Compatibility) ::: warning Use `*` operator This `multiply` function works slowly due to additional function calls. Use the faster and simpler `*` operator instead. ::: Multiplies two numbers. ```typescript const result = multiply(value, other); ``` ## Usage ### `multiply(value, other)` Use `multiply` when you want to multiply two numbers. ```typescript import { multiply } from 'es-toolkit/compat'; // Basic multiplication multiply(2, 3); // Returns: 6 multiply(4, 5); // Returns: 20 // Negative number handling multiply(2, -3); // Returns: -6 multiply(-4, -5); // Returns: 20 // Decimal number handling multiply(2.5, 4); // Returns: 10 // NaN handling multiply(NaN, 3); // Returns: NaN multiply(2, NaN); // Returns: NaN multiply(NaN, NaN); // Returns: NaN ``` #### Parameters * `value` (`number`): The first number in the multiplication. * `other` (`number`): The second number in the multiplication. #### Returns (`number`): Returns the result of multiplying the two numbers. If either is NaN, returns NaN. --- --- url: /reference/promise/Mutex.md --- # Mutex Ensures that multiple asynchronous tasks do not execute simultaneously. ```typescript const mutex = new Mutex(); ``` ## Usage ### `Mutex()` Use `Mutex` when you want to prevent multiple asynchronous tasks from running concurrently. It's useful in situations where you need to control concurrency, such as database connections, file system access, or API call rate limiting. ```typescript import { Mutex } from 'es-toolkit'; const mutex = new Mutex(); // API call rate limiting example async function callAPI() { await mutex.acquire(); try { // Prevents multiple API calls from happening simultaneously const response = await fetch('/api/data'); return response.json(); } finally { mutex.release(); } } // File system access example async function writeToFile(data: string) { await mutex.acquire(); try { // Prevents concurrent writes to the same file await fs.writeFile('data.txt', data); console.log('File write completed'); } finally { mutex.release(); } } // Even if multiple tasks are called simultaneously, they execute sequentially callAPI(); callAPI(); // Waits until the first task completes writeToFile(); // Waits until all previous tasks complete ``` #### Properties * `isLocked` (`boolean`): Whether the mutex is currently in use. If `true`, it means there's already an asynchronous task running. #### Methods * `acquire` (`() => Promise`): Acquires permission to execute an asynchronous task, or waits until permission is granted. * `release` (`() => void`): Allows the next waiting task to execute. --- --- url: /reference/function/negate.md --- # negate Creates a new function that inverts the return value of a function that returns true or false. ```typescript const negatedFunc = negate(booleanFunc); ``` ## Usage ### `negate(func)` Use `negate` when you want to invert the result of a function that returns true or false. This is useful for inverting conditional functions or filtering logic. For example, you can turn a function that finds even numbers into a function that finds odd numbers. ```typescript import { negate } from 'es-toolkit/function'; // Basic usage const isEven = (n: number) => n % 2 === 0; const isOdd = negate(isEven); console.log(isEven(2)); // true console.log(isOdd(2)); // false console.log(isEven(3)); // false console.log(isOdd(3)); // true // Using in array filtering const numbers = [1, 2, 3, 4, 5, 6]; const evenNumbers = numbers.filter(isEven); console.log(evenNumbers); // [2, 4, 6] const oddNumbers = numbers.filter(negate(isEven)); console.log(oddNumbers); // [1, 3, 5] ``` You can also invert complex conditional functions. ```typescript import { negate } from 'es-toolkit/function'; const isLongString = (str: string) => str.length > 5; const isShortString = negate(isLongString); const words = ['hi', 'hello', 'world', 'javascript']; const longWords = words.filter(isLongString); console.log(longWords); // ['hello', 'javascript'] const shortWords = words.filter(isShortString); console.log(shortWords); // ['hi', 'world'] ``` #### Parameters * `func` (`F`): A function that returns a boolean value. #### Returns (`F`): Returns a new function that accepts the same arguments as the original function but returns the opposite boolean value. --- --- url: /reference/compat/function/negate.md --- # negate (Lodash Compatibility) ::: warning Use the logical NOT operator This `negate` function simply negates the result of a function. In most cases, it's simpler and faster to use the logical NOT operator (`!`) directly. Instead, use the faster and more modern `!predicate(...args)` or `(...args) => !predicate(...args)`. ::: Creates a new function that negates the result of the given function. ```typescript const negatedFunc = negate(predicate); ``` ## Usage ### `negate(predicate)` Use `negate` when you want to create a new function that negates the result of a function. It's useful for checking opposite conditions in filtering or conditional statements. ```typescript import { negate } from 'es-toolkit/compat'; // Basic usage function isEven(n) { return n % 2 === 0; } const isOdd = negate(isEven); console.log(isOdd(3)); // true console.log(isOdd(4)); // false // Using in array filtering const numbers = [1, 2, 3, 4, 5, 6]; const oddNumbers = numbers.filter(negate(isEven)); console.log(oddNumbers); // [1, 3, 5] // Modern alternative (recommended) const modernOddNumbers = numbers.filter(n => !isEven(n)); // or const isOddModern = n => !isEven(n); const modernOddNumbers2 = numbers.filter(isOddModern); // Complex example function isEmpty(str) { return str.trim().length === 0; } const hasContent = negate(isEmpty); const messages = ['', ' ', 'hello', ' ', 'world']; const validMessages = messages.filter(hasContent); console.log(validMessages); // ['hello', 'world'] ``` It's primarily used in array filtering or conditional logic, but in most cases, using the logical NOT operator directly is more intuitive. #### Parameters * `predicate` (`Function`): The function whose result should be negated. It must return a boolean value. #### Returns (`Function`): Returns a new function that returns the negated result of the original function. --- --- url: /reference/function/noop.md --- # noop An empty function that does nothing. ```typescript noop(); ``` ::: info [`asyncNoop`](./asyncNoop.md) function If you need a function that asynchronously does nothing, use the `asyncNoop` function which immediately returns a `Promise`. ::: ## Usage ### `noop()` Use `noop` when you need a function that performs no operation. This is useful as a default value where a function is required or when you want to disable a callback function. It's frequently used as a placeholder or during initialization. ```typescript import { noop } from 'es-toolkit/function'; // Using as a default value for optional callbacks interface EventHandlers { onSuccess?: () => void; onError?: () => void; } function processData({ onSuccess = noop, onError = noop }: EventHandlers = {}) { try { // Data processing logic console.log('Data processing complete'); onSuccess(); // Safe to call } catch (error) { onError(); // Safe to call } } // Safe to use without undefined checks processData({ onSuccess: () => console.log('Success!'), // onError is handled as noop by default }); ``` It can also be used with array methods. ```typescript import { noop } from 'es-toolkit/function'; // Conditionally execute functions const operations = [ () => console.log('First task'), shouldRunSecond ? () => console.log('Second task') : noop, () => console.log('Third task'), ]; operations.forEach(op => op()); // Execute all operations safely ``` #### Returns (`void`): Returns nothing. --- --- url: /reference/compat/function/noop.md --- # noop (Lodash Compatibility) ::: warning Use `es-toolkit`'s `noop` `es-toolkit` also has a [noop](../../function/noop.md) function that behaves the same. ::: An empty function that does nothing. ```typescript noop(); ``` ## Usage ### `noop(...args)` Use `noop` when you need a placeholder function that does nothing. It's often used as a default value or callback function. ```typescript import { noop } from 'es-toolkit/compat'; // Basic usage noop(); // Does nothing noop(1, 2, 3); // Accepts arguments but does nothing // Use as default callback function processData(data, callback = noop) { // Process data console.log('Processing data...', data); // Call callback (noop if not provided) callback(data); } processData('test'); // Works without errors even if callback not provided // Modern alternative (recommended) function modernProcessData(data, callback = () => {}) { console.log('Processing data...', data); callback(data); } // Or use optional callback function processDataOptional(data, callback) { console.log('Processing data...', data); callback?.(data); // Only call if callback is provided } ``` Useful in situations where a default value or placeholder is needed, but in modern JavaScript, it's more common to use optional chaining (`?.`) or default parameters. #### Parameters * `...args` (`any[]`): Can accept any arguments, but all are ignored. #### Returns (`void`): Returns nothing. --- --- url: /reference/compat/util/now.md --- # now (Lodash Compatibility) ::: warning Use `Date.now()` instead This `now` function is a simple wrapper that calls `Date.now()` and represents unnecessary abstraction. Use the faster and more direct `Date.now()` instead. ::: Returns the current time in milliseconds. ```typescript const currentTime = now(); ``` ## Usage ### `now()` Returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC. This is useful for time measurement and timestamp generation. ```typescript import { now } from 'es-toolkit/compat'; // Get the current time const currentTime = now(); console.log(currentTime); // => 1703925600000 (example) // Measure execution time const startTime = now(); // Some time-consuming operation const endTime = now(); console.log(`Operation time: ${endTime - startTime}ms`); // Use as timestamp const timestamp = now(); const logMessage = `[${timestamp}] Operation completed`; ``` Returns the same result as `Date.now()`. ```typescript import { now } from 'es-toolkit/compat'; console.log(now() === Date.now()); // => true (when called at the same time) ``` #### Parameters None. #### Returns (`number`): Returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC to the present. --- --- url: /reference/compat/array/nth.md --- # nth (Lodash Compatibility) ::: warning Use array index access This `nth` function operates slowly due to handling `null` or `undefined` and integer conversion. Use the faster and more modern array index access (`array[index]` or `array.at(index)`) instead. ::: Gets the element at the specified index of an array. ```typescript const element = nth(array, index); ``` ## Usage ### `nth(array, index)` Returns the element at the specified index of an array. If the index is negative, it counts from the end of the array. If the index is out of range, it returns `undefined`. ```typescript import { nth } from 'es-toolkit/compat'; const array = [1, 2, 3, 4, 5]; // Positive index nth(array, 1); // => 2 // Negative index (from end) nth(array, -1); // => 5 nth(array, -2); // => 4 // Out of range index nth(array, 10); // => undefined nth(array, -10); // => undefined ``` `null` or `undefined` are treated as `undefined`. ```typescript import { nth } from 'es-toolkit/compat'; nth(null, 0); // undefined nth(undefined, 0); // undefined ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to query. * `index` (`number`, optional): The index of the element to get. If negative, it counts from the end. Defaults to `0`. #### Returns (`T | undefined`): Returns the element at the specified index. If the index is out of range, it returns `undefined`. --- --- url: /reference/compat/function/nthArg.md --- # nthArg (Lodash Compatibility) ::: warning Use arrow functions This `nthArg` function simply creates a wrapper function that returns the argument at a specific index. You can implement the same functionality more concisely and clearly using arrow functions. Instead, use the faster and more modern arrow functions. ::: Creates a function that returns the argument at the specified index. ```typescript const getNthArg = nthArg(n); ``` ## Usage ### `nthArg(n)` Use `nthArg` when you need only the argument at a specific position of a function. If you use a negative index, it counts from the end. ```typescript import { nthArg } from 'es-toolkit/compat'; // Create a function to get the second argument const getSecondArg = nthArg(1); getSecondArg('a', 'b', 'c', 'd'); // Returns: 'b' // Create a function to get the penultimate argument const getPenultimateArg = nthArg(-2); getPenultimateArg('a', 'b', 'c', 'd'); // Returns: 'c' // Create a function to get the first argument (default) const getFirstArg = nthArg(); getFirstArg('a', 'b', 'c'); // Returns: 'a' ``` It's useful when used with array methods. ```typescript import { nthArg } from 'es-toolkit/compat'; // Extract only the second element from each array const arrays = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; arrays.map(nthArg(1)); // Returns: [2, 5, 8] ``` Negative indices count from the end. ```typescript import { nthArg } from 'es-toolkit/compat'; // Function to get the last argument const getLastArg = nthArg(-1); getLastArg('first', 'middle', 'last'); // Returns: 'last' ``` #### Parameters * `n` (`number`, optional): The index of the argument to return. Negative values count from the end. Default is `0`. #### Returns (`(...args: any[]) => any`): Returns a new function that returns the argument at the specified index. --- --- url: /reference/object/omit.md --- # omit Returns a new object excluding the specified keys. ```typescript const result = omit(obj, keys); ``` ## Usage ### `omit(obj, keys)` Use `omit` when you want to exclude specific keys from an object. It returns a new object with the properties corresponding to the specified keys removed. ```typescript import { omit } from 'es-toolkit/object'; // Exclude specific keys const obj = { a: 1, b: 2, c: 3, d: 4 }; const result = omit(obj, ['b', 'c']); // result is { a: 1, d: 4 } // Specifying non-existent keys doesn't cause an error const safe = omit(obj, ['b', 'nonexistent']); // safe is { a: 1, c: 3, d: 4 } ``` #### Parameters * `obj` (`T extends Record`): The object to exclude keys from. * `keys` (`readonly K[]`): An array of keys to exclude from the object. #### Returns (`Omit`): A new object with the specified keys excluded. --- --- url: /reference/compat/object/omit.md --- # omit (Lodash compatibility) ::: warning Use `omit` from `es-toolkit` This `omit` function is relatively slow due to deep copying and calling the `unset` function. Use the faster and more modern [`omit`](../../object/omit.md) from `es-toolkit` instead. ::: Creates a new object excluding specified keys from an object. ```typescript const result = omit(obj, ...keys); ``` ## Usage ### `omit(object, ...paths)` Creates a new object excluding specified keys from an object. Supports deep key paths and can specify multiple keys at once using arrays. Useful for removing sensitive information from objects or selecting only needed properties. ```typescript import { omit } from 'es-toolkit/compat'; // Remove basic keys const user = { id: 1, name: 'John', email: 'john@example.com', password: 'secret' }; const publicUser = omit(user, 'password', 'email'); // Result: { id: 1, name: 'John' } // Remove multiple keys with array const data = { a: 1, b: 2, c: 3, d: 4 }; const filtered = omit(data, ['a', 'c']); // Result: { b: 2, d: 4 } // Remove deep key paths const nested = { user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, admin: true, }; const result = omit(nested, 'user.profile.age', 'admin'); // Result: { user: { profile: { name: 'John' }, settings: { theme: 'dark' } } } // Combine nested arrays and keys const complex = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; const simplified = omit(complex, 'a', ['b', 'c'], 'd.f'); // Result: { d: { e: 4 } } ``` You can freely combine arrays, strings, and key paths. ```typescript import { omit } from 'es-toolkit/compat'; const config = { api: { url: 'https://api.example.com', key: 'secret', timeout: 5000 }, ui: { theme: 'dark', language: 'en' }, debug: true, }; // Specify keys in multiple ways const cleaned = omit(config, 'api.key', ['debug'], 'ui.language'); // Result: { api: { url: 'https://api.example.com', timeout: 5000 }, ui: { theme: 'dark' } } ``` `null` or `undefined` are treated as empty objects. ```typescript import { omit } from 'es-toolkit/compat'; omit(null, 'key'); // {} omit(undefined, 'key'); // {} ``` #### Parameters * `object` (`T | null | undefined`): The source object to remove keys from. * `...paths` (`Array>`): The keys to remove. Can specify single keys, arrays of keys, or deep key paths. #### Returns (`Partial`): Returns a new object with specified keys removed. --- --- url: /reference/object/omitBy.md --- # omitBy Returns a new object containing only the properties that do not satisfy the condition function. ```typescript const result = omitBy(obj, shouldOmit); ``` ## Usage ### `omitBy(obj, shouldOmit)` Use `omitBy` when you want to selectively exclude properties from an object based on a condition function. Properties for which the condition function returns `true` are excluded, and only properties that return `false` are included in the new object. ```typescript import { omitBy } from 'es-toolkit/object'; // Exclude properties with string values const obj = { a: 1, b: 'remove', c: 3, d: 'also remove' }; const result = omitBy(obj, value => typeof value === 'string'); // result is { a: 1, c: 3 } // Exclude only even values const numbers = { a: 1, b: 2, c: 3, d: 4 }; const odds = omitBy(numbers, value => value % 2 === 0); // odds is { a: 1, c: 3 } // Use both key and value const data = { user1: 25, user2: 17, admin1: 30, admin2: 28 }; const nonAdmins = omitBy(data, (value, key) => key.startsWith('admin')); // nonAdmins is { user1: 25, user2: 17 } ``` #### Parameters * `obj` (`T extends Record`): The object to filter properties from. * `shouldOmit` (`(value: T[keyof T], key: keyof T) => boolean`): A condition function that determines whether to exclude a property. Receives the value and key, and returns `true` to exclude, `false` to keep. #### Returns (`Partial`): A new object consisting of properties that do not satisfy the condition function. --- --- url: /reference/compat/object/omitBy.md --- # omitBy (Lodash compatibility) ::: warning Use `omitBy` from `es-toolkit` This `omitBy` function is relatively slow due to array-like object checking, `iteratee` conversion, and key transformation processes. Use the faster and more modern [`omitBy`](../../object/omitBy.md) from `es-toolkit` instead. ::: Creates a new object excluding properties for which the predicate function returns true. ```typescript const result = omitBy(obj, predicate); ``` ## Usage ### `omitBy(object, predicate)` Executes a predicate function for each property of the object and creates a new object excluding properties for which the predicate returns true. Useful for dynamically filtering properties based on conditions. ```typescript import { omitBy } from 'es-toolkit/compat'; // Remove values of specific type const data = { a: 1, b: 'remove', c: 3, d: 'keep' }; const numbers = omitBy(data, value => typeof value === 'string'); // Result: { a: 1, c: 3 } // Remove properties based on condition const user = { id: 1, name: 'John', age: 0, active: false, email: '' }; const validData = omitBy(user, value => !value); // Result: { id: 1, name: 'John' } (removes falsy values) // Filter by key name const settings = { userSetting: true, adminSetting: false, debugMode: true }; const userOnly = omitBy(settings, (value, key) => key.startsWith('admin')); // Result: { userSetting: true, debugMode: true } // Remove only number properties const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; const noNumbers = omitBy(mixed, value => typeof value === 'number'); // Result: { str: 'hello', bool: true, obj: {} } // Can also be used with arrays const arr = [1, 2, 3, 4, 5]; const filtered = omitBy(arr, value => value % 2 === 0); // Result: { '0': 1, '2': 3, '4': 5 } (odd values at even indices) // Utilize value, key, and original object const scores = { math: 90, science: 75, english: 85, art: 60 }; const passingGrades = omitBy(scores, (value, key, obj) => { console.log(`${key}: ${value} (average: ${Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length})`); return value < 80; }); // Result: { math: 90, english: 85 } ``` `null` or `undefined` are treated as empty objects. ```typescript import { omitBy } from 'es-toolkit/compat'; omitBy(null, () => true); // {} omitBy(undefined, () => true); // {} ``` #### Parameters * `object` (`Record | Record | object | null | undefined`): The source object to filter. * `predicate` (`ValueKeyIteratee | ValueKeyIteratee`, optional): The predicate function to execute for each property. Properties for which this returns true are removed. Defaults to the `identity` function. #### Returns (`Record | Record | Partial`): Returns a new object consisting of properties that don't match the condition. --- --- url: /reference/function/once.md --- # once Creates a new function that limits a function to be executed only once. ```typescript const onceFunc = once(func); ``` ## Usage ### `once(func)` Use `once` when you want to limit a function to be executed only once. Subsequent calls will return the result from the first call. This is useful for logic that should only be executed once, such as initialization functions or event handlers. It prevents duplicate execution and ensures consistent results. ```typescript import { once } from 'es-toolkit/function'; // Example of an initialization function const initialize = once(() => { console.log('Initializing app'); return { status: 'initialized' }; }); console.log(initialize()); // Logs 'Initializing app', returns { status: 'initialized' } console.log(initialize()); // Returns { status: 'initialized' } without logging console.log(initialize()); // Returns { status: 'initialized' } without logging // Example of an API call const fetchConfig = once(async () => { console.log('Fetching configuration'); const response = await fetch('/api/config'); return response.json(); }); // Only the first call makes the actual API request const config1 = await fetchConfig(); const config2 = await fetchConfig(); // Returns cached result ``` You can also use it with functions that take arguments. ```typescript import { once } from 'es-toolkit/function'; const logOnce = once((message: string) => { console.log(`Important message: ${message}`); }); logOnce('Hello'); // Logs 'Important message: Hello' logOnce('Hello again'); // Not logged (already called) logOnce('Hello once more'); // Not logged (already called) ``` #### Parameters * `func` (`F`): The function to restrict to a single execution. #### Returns (`F`): Returns a new function that caches the result after the first call and returns the same result for subsequent calls. --- --- url: /reference/compat/function/once.md --- # once (Lodash Compatibility) ::: warning Use `es-toolkit`'s `once` This `once` function has the same functionality as the main library [once](../../function/once.md) function in `es-toolkit`. ::: Restricts a function to be called only once. ```typescript const limitedFunc = once(func); ``` ## Usage ### `once(func)` Use `once` when you want to restrict a function to be called only once. After the first call, the result is cached and the same value is returned. ```typescript import { once } from 'es-toolkit/compat'; // Basic usage let count = 0; const increment = once(() => { count++; console.log('Counter incremented:', count); return count; }); increment(); // Outputs 'Counter incremented: 1', returns 1 increment(); // Outputs nothing, returns 1 increment(); // Outputs nothing, returns 1 // Practical example - initialization function const initialize = once(() => { console.log('Initializing application...'); // Expensive initialization operations return 'Initialization complete'; }); // Even if called multiple times, initialization runs only once initialize(); // Outputs 'Initializing application...' initialize(); // Outputs nothing ``` It's useful when creating expensive initialization operations or setup functions. For example, it can be used for database connections, API token initialization, etc. #### Parameters * `func` (`Function`): The function to restrict to only one call. #### Returns (`Function`): Returns a new function that is called only once. From the second call onwards, it returns the result of the first call. --- --- url: /reference/array/orderBy.md --- # orderBy Returns a new array sorted by multiple criteria and sort directions. ```typescript const sorted = orderBy(arr, criteria, orders); ``` ## Usage ### `orderBy(arr, criteria, orders)` Use `orderBy` when you want to perform compound sorting on an array of objects with multiple conditions. You can specify ascending or descending order for each criterion, and if values are the same for the first criterion, it sorts by the next criterion. ```typescript import { orderBy } from 'es-toolkit/array'; // Sort a user array by multiple criteria. const users = [ { user: 'fred', age: 48 }, { user: 'barney', age: 34 }, { user: 'fred', age: 40 }, { user: 'barney', age: 36 }, ]; orderBy(users, [obj => obj.user, 'age'], ['asc', 'desc']); // Returns: // [ // { user: 'barney', age: 36 }, // { user: 'barney', age: 34 }, // { user: 'fred', age: 48 }, // { user: 'fred', age: 40 } // ] // You can mix property names and functions. const products = [ { name: 'Apple', category: 'fruit', price: 1.5 }, { name: 'Banana', category: 'fruit', price: 0.8 }, { name: 'Broccoli', category: 'vegetable', price: 2.0 }, ]; orderBy(products, ['category', product => product.name.length], ['asc', 'desc']); // Returns: Sort by category first, then by name length in descending order within the same category ``` If the number of sort directions is less than the number of criteria, the last direction is repeated. ```typescript import { orderBy } from 'es-toolkit/array'; const data = [ { a: 1, b: 1, c: 1 }, { a: 1, b: 2, c: 2 }, { a: 2, b: 1, c: 1 }, ]; orderBy(data, ['a', 'b', 'c'], ['asc', 'desc']); // 'a' is sorted in ascending order, 'b' and 'c' are sorted in descending order. ``` #### Parameters * `arr` (`T[]`): The array of objects to sort. * `criteria` (`Array<((item: T) => unknown) | keyof T>`): The criteria to sort by. You can use property names of objects or functions that return values. * `orders` (`Array<'asc' | 'desc'>`): An array of sort directions for each criterion. `'asc'` means ascending order, `'desc'` means descending order. #### Returns (`T[]`): A new array sorted by the specified criteria and directions. --- --- url: /reference/compat/array/orderBy.md --- # orderBy (Lodash Compatibility) ::: warning Use [orderBy](../../array/orderBy.md) from `es-toolkit` instead This `orderBy` function operates slowly due to handling `null` or `undefined`, complex path navigation, and various sorting criteria. Use the faster and more modern [orderBy](../../array/orderBy.md) from `es-toolkit` instead. ::: Sorts the elements of a collection by multiple criteria. ```typescript const result = orderBy(collection, criteria, orders); ``` ## Usage ### `orderBy(collection, criteria, orders)` Sorts the elements of an array or object according to specified criteria and sort orders. You can use multiple criteria, and specify ascending (`'asc'`) or descending (`'desc'`) order for each criterion. ```typescript import { orderBy } from 'es-toolkit/compat'; const users = [ { name: 'fred', age: 48 }, { name: 'barney', age: 34 }, { name: 'fred', age: 40 }, { name: 'barney', age: 36 }, ]; // Sort by name ascending, age descending orderBy(users, ['name', 'age'], ['asc', 'desc']); // => [ // { name: 'barney', age: 36 }, // { name: 'barney', age: 34 }, // { name: 'fred', age: 48 }, // { name: 'fred', age: 40 } // ] // Specify sort criteria with functions orderBy(users, [user => user.name, user => user.age], ['asc', 'desc']); // => Same result as above // Sort by single criterion orderBy(users, 'age', 'desc'); // => [{ name: 'fred', age: 48 }, { name: 'fred', age: 40 }, ...] ``` For objects, sorts the values. ```typescript import { orderBy } from 'es-toolkit/compat'; const obj = { a: { name: 'fred', age: 48 }, b: { name: 'barney', age: 34 }, }; orderBy(obj, 'age', 'desc'); // => [{ name: 'fred', age: 48 }, { name: 'barney', age: 34 }] ``` `null` or `undefined` are treated as empty arrays. ```typescript import { orderBy } from 'es-toolkit/compat'; orderBy(null, 'name'); // [] orderBy(undefined, 'age'); // [] ``` #### Parameters * `collection` (`ArrayLike | object | null | undefined`): The array or object to sort. * `criteria` (`Criterion | Array>`, optional): The sort criteria. Can use property names, property paths, functions, etc. Defaults to `[null]`. * `orders` (`unknown | unknown[]`, optional): The sort order for each criterion. Can use `'asc'` (ascending), `'desc'` (descending), `true` (ascending), `false` (descending). Defaults to `[]`. #### Returns (`T[]`): Returns a new sorted array. --- --- url: /reference/compat/util/over.md --- # over (Lodash Compatibility) ::: warning Use array methods directly instead This `over` function incurs additional overhead in the process of mapping functions to arrays. Use the faster and more modern array `map` method instead. ::: Creates a function that passes the same arguments to given functions and returns the results as an array. ```typescript const multiCall = over(funcs); ``` ## Usage ### `over(...iteratees)` Takes multiple functions and creates a function that calls each with the same arguments and returns the results as an array. This is useful for performing multiple calculations on the same data. ```typescript import { over } from 'es-toolkit/compat'; // Use math functions together const mathOperations = over([Math.max, Math.min]); mathOperations(1, 2, 3, 4); // => [4, 1] // Can also pass individual functions const operations = over(Math.max, Math.min); operations(1, 2, 3, 4); // => [4, 1] // Extract object properties const getProperties = over(['name', 'age']); getProperties({ name: 'John', age: 30 }); // => ['John', 30] // Check conditions const validators = over([ { name: 'John' }, // Object matching { age: 30 }, ]); validators({ name: 'John', age: 30 }); // => [true, true] ``` It can also handle nested paths. ```typescript import { over } from 'es-toolkit/compat'; const data = { user: { name: 'John', profile: { age: 30 } }, settings: { theme: 'dark' }, }; const getInfo = over(['user.name', 'user.profile.age', 'settings.theme']); getInfo(data); // => ['John', 30, 'dark'] ``` #### Parameters * `...iteratees` (`Array`): The functions to call or property paths. Can be passed as an array or individual arguments. #### Returns (`(...args: any[]) => any[]`): Returns a function that takes arguments and returns an array of results from each function. --- --- url: /reference/compat/function/overArgs.md --- # overArgs (Lodash Compatibility) ::: warning Use arrow functions and direct transformation This `overArgs` function creates a complex wrapper that transforms each argument, resulting in slow performance. Using arrow functions to transform arguments directly results in clearer and faster code. Instead, use the faster and more modern arrow functions and direct transformation. ::: Creates a new function that transforms each argument of a function with the corresponding transform function and then executes it. ```typescript const wrapped = overArgs(func, transforms); ``` ## Usage ### `overArgs(func, ...transforms)` Use `overArgs` when you want to transform each argument before calling a function. Each argument is processed by the corresponding transform function. ```typescript import { overArgs } from 'es-toolkit/compat'; function doubled(n) { return n * 2; } function square(n) { return n * n; } // First argument is doubled, second argument is squared const func = overArgs((x, y) => [x, y], [doubled, square]); func(5, 3); // Returns: [10, 9] ``` You can also extract properties using strings. ```typescript import { overArgs } from 'es-toolkit/compat'; const user1 = { name: 'John', age: 30 }; const user2 = { name: 'Jane', age: 25 }; // Extract properties from each object const getUserInfo = overArgs((name, age) => `${name} is ${age} years old`, ['name', 'age']); getUserInfo(user1, user2); // Returns: "John is 25 years old" ``` If a transform function is not provided or is `null`/`undefined`, the argument is passed as is. ```typescript import { overArgs } from 'es-toolkit/compat'; const func = overArgs((a, b, c) => [a, b, c], [n => n * 2, null, n => n * 3]); func(5, 10, 15); // Returns: [10, 10, 45] ``` Arguments that exceed the number of transform functions are passed as is. ```typescript import { overArgs } from 'es-toolkit/compat'; const func = overArgs((a, b, c) => [a, b, c], [n => n * 2]); func(5, 10, 15); // Returns: [10, 10, 15] ``` You can also check if arguments match objects. ```typescript import { overArgs } from 'es-toolkit/compat'; const func = overArgs((match1, match2) => [match1, match2], [{ age: 30 }, { active: true }]); func({ name: 'John', age: 30 }, { active: true, status: 'online' }); // Returns: [true, true] ``` #### Parameters * `func` (`(...args: any[]) => any`): The function to wrap. * `...transforms` (`Array<(...args: any[]) => any | string | object | array>`): The functions to transform arguments. Each transform can be one of the following: * A function that accepts and returns a value * A string to get a property value (e.g., 'name' gets the name property) * An object to check if the argument matches the properties * A \[property, value] array to check property matching #### Returns (`(...args: any[]) => any`): Returns a new function that transforms the arguments and then calls the original function. --- --- url: /reference/compat/util/overEvery.md --- # overEvery (Lodash Compatibility) ::: warning Use `Array.every` instead This `overEvery` function incurs additional overhead in the process of converting and checking predicate functions. Use the faster and more modern `Array.every` method instead. ::: Creates a function that checks if all predicate functions return truthy for the given value. ```typescript const allValidator = overEvery(predicates); ``` ## Usage ### `overEvery(...predicates)` Takes multiple predicate functions and creates a function that checks if the given value satisfies all conditions. This is useful for compound condition checking or data validation. ```typescript import { overEvery } from 'es-toolkit/compat'; // Check string conditions const isValidString = overEvery([ value => typeof value === 'string', value => value.length > 3, value => value.includes('o'), ]); isValidString('hello'); // => true isValidString('hi'); // => false (length is 3 or less) isValidString('test'); // => false (no 'o') // Check number range const isInRange = overEvery([ num => num >= 0, num => num <= 100, num => num % 1 === 0, // Check if integer ]); isInRange(50); // => true isInRange(-5); // => false (less than 0) isInRange(150); // => false (greater than 100) isInRange(50.5); // => false (not an integer) ``` You can also check object properties. ```typescript import { overEvery } from 'es-toolkit/compat'; // Check object properties const isValidUser = overEvery([ 'name', // Check if name property is truthy { age: 30 }, // Check if age is 30 ['active', true], // Check if active is true ]); isValidUser({ name: 'John', age: 30, active: true }); // => true isValidUser({ name: '', age: 30, active: true }); // => false (name is empty string) isValidUser({ name: 'John', age: 25, active: true }); // => false (age is different) ``` #### Parameters * `...predicates` (`Array`): The predicate functions to check. Can be functions, property names, objects, or property-value pairs. #### Returns (`(...args: any[]) => boolean`): Returns a function that returns `true` if all conditions are satisfied, `false` if any condition is not satisfied. --- --- url: /reference/compat/util/overSome.md --- # overSome (Lodash Compatibility) ::: warning Use `Array.some` instead This `overSome` function incurs additional overhead in the process of converting and checking predicate functions. Use the faster and more modern `Array.some` method instead. ::: Creates a function that checks if any of the predicate functions return truthy for the given value. ```typescript const anyValidator = overSome(predicates); ``` ## Usage ### `overSome(...predicates)` Takes multiple predicate functions and creates a function that checks if the given value satisfies any of the conditions. This is useful for flexible condition checking or alternative validation. ```typescript import { overSome } from 'es-toolkit/compat'; // Check if value is string or number const isStringOrNumber = overSome([value => typeof value === 'string', value => typeof value === 'number']); isStringOrNumber('hello'); // => true isStringOrNumber(42); // => true isStringOrNumber(true); // => false // Check if any of multiple conditions are satisfied const hasValidProperty = overSome([ obj => obj.name && obj.name.length > 0, obj => obj.email && obj.email.includes('@'), obj => obj.phone && obj.phone.length >= 10, ]); hasValidProperty({ name: 'John' }); // => true hasValidProperty({ email: 'john@example.com' }); // => true hasValidProperty({ phone: '1234567890' }); // => true hasValidProperty({ age: 30 }); // => false ``` You can also check object properties. ```typescript import { overSome } from 'es-toolkit/compat'; // Check if any condition matches const matchesAnyCondition = overSome([ 'isActive', // Check if isActive property is truthy { role: 'admin' }, // Check if role is 'admin' ['status', 'vip'], // Check if status is 'vip' ]); matchesAnyCondition({ isActive: true }); // => true matchesAnyCondition({ role: 'admin' }); // => true matchesAnyCondition({ status: 'vip' }); // => true matchesAnyCondition({ role: 'user', status: 'normal' }); // => false ``` #### Parameters * `...predicates` (`Array`): The predicate functions to check. Can be functions, property names, objects, or property-value pairs. #### Returns (`(...args: any[]) => boolean`): Returns a function that returns `true` if any condition is satisfied, `false` if none are satisfied. --- --- url: /reference/string/pad.md --- # pad Pads a string on both sides to reach a specified length. ```typescript const padded = pad(str, length, chars); ``` ## Usage ### `pad(str, length, chars?)` Use `pad` when you want to pad both sides of a string with characters to match a specified length when the string is shorter than the target length. If the padding cannot be evenly distributed on both sides, the right side will have one more character. ```typescript import { pad } from 'es-toolkit/string'; // Padding with default whitespace pad('abc', 8); // => ' abc ' // Padding with custom characters pad('abc', 8, '_-'); // => '_-abc_-_' // When the string is already longer than or equal to the target length pad('abc', 3); // => 'abc' pad('abcdef', 3); // => 'abcdef' ``` When padding characters cannot be evenly distributed to the target length, the right side will be longer. ```typescript import { pad } from 'es-toolkit/string'; pad('abc', 9, '123'); // => '123abc123' (left 3 characters, right 3 characters) pad('abc', 10, '123'); // => '123abc1231' (left 3 characters, right 4 characters) ``` #### Parameters * `str` (`string`): The string to pad. * `length` (`number`): The target length. * `chars` (`string`, optional): The characters to use for padding. Defaults to `' '`. #### Returns (`string`): Returns the padded string. --- --- url: /reference/compat/string/pad.md --- # pad (Lodash compatibility) ::: warning Use `pad` from `es-toolkit` This `pad` function operates slower due to handling `null` or `undefined`. Instead, use the faster and more modern [pad](../../string/pad.md) from `es-toolkit`. ::: Pads a string on both sides with padding characters to reach the specified length. ```typescript const padded = pad(str, length, chars); ``` ## Usage ### `pad(str, length, chars)` Use `pad` when you want to pad a string on both sides to match a desired length. If the padding characters don't divide evenly, extra characters are placed on the right. ```typescript import { pad } from 'es-toolkit/compat'; // Pad with default spaces pad('abc', 8); // Returns: ' abc ' // Pad with specified characters pad('abc', 8, '_-'); // Returns: '_-abc_-_' // Return as is if already long enough pad('abc', 3); // Returns: 'abc' // Return as is if length is shorter pad('abc', 2); // Returns: 'abc' ``` `null` or `undefined` are treated as empty strings. ```typescript import { pad } from 'es-toolkit/compat'; pad(null, 5); // ' ' pad(undefined, 3, '*'); // '***' ``` #### Parameters * `str` (`string`, optional): The string to pad. * `length` (`number`, optional): The target length. Defaults to `0`. * `chars` (`string`, optional): The characters to use for padding. Defaults to space `' '`. #### Returns (`string`): Returns the string padded to the specified length. --- --- url: /reference/compat/string/padEnd.md --- # padEnd (Lodash compatibility) ::: warning Use JavaScript's `String.prototype.padEnd` This `padEnd` function operates slower due to handling non-string values. Instead, use the faster and more modern JavaScript's `String.prototype.padEnd`. ::: Pads the end of a string to extend it to the specified length. ```typescript const padded = padEnd(str, length, chars); ``` ## Usage ### `padEnd(str, length?, chars?)` Use `padEnd` when you want to pad the end of a string to match a desired length. ```typescript import { padEnd } from 'es-toolkit/compat'; // Pad with spaces padEnd('abc', 6); // Returns: 'abc ' // Pad with specific characters padEnd('abc', 6, '_-'); // Returns: 'abc_-_' // Return as is if original length is longer padEnd('abc', 3); // Returns: 'abc' ``` `null` or `undefined` are treated as empty strings. ```typescript import { padEnd } from 'es-toolkit/compat'; padEnd(null, 5, '*'); // Returns: '*****' padEnd(undefined, 3); // Returns: ' ' ``` #### Parameters * `str` (`string`, optional): The string to add padding to. * `length` (`number`, optional): The desired final string length. Defaults to `0`. * `chars` (`string`, optional): The character to use for padding. Defaults to `' '` (space). #### Returns (`string`): Returns the string with padding added to the end. --- --- url: /reference/compat/string/padStart.md --- # padStart (Lodash compatibility) ::: warning Use JavaScript's `String.prototype.padStart` This `padStart` function operates slower due to handling non-string values. Instead, use the faster and more modern JavaScript's `String.prototype.padStart`. ::: Pads the start of a string to extend it to the specified length. ```typescript const padded = padStart(str, length, chars); ``` ## Usage ### `padStart(str, length?, chars?)` Use `padStart` when you want to pad the start of a string to match a desired length. ```typescript import { padStart } from 'es-toolkit/compat'; // Pad with spaces padStart('abc', 6); // Returns: ' abc' // Pad with specific characters padStart('abc', 6, '_-'); // Returns: '_-_abc' // Return as is if original length is longer padStart('abc', 3); // Returns: 'abc' ``` `null` or `undefined` are treated as empty strings. ```typescript import { padStart } from 'es-toolkit/compat'; padStart(null, 5, '*'); // Returns: '*****' padStart(undefined, 3); // Returns: ' ' ``` #### Parameters * `str` (`string`, optional): The string to add padding to. * `length` (`number`, optional): The desired final string length. Defaults to `0`. * `chars` (`string`, optional): The character to use for padding. Defaults to `' '` (space). #### Returns (`string`): Returns the string with padding added to the start. --- --- url: /reference/compat/math/parseInt.md --- # parseInt (Lodash Compatibility) ::: warning Use `parseInt` This `parseInt` function works slowly due to additional function calls. Use the faster and more modern native `parseInt` instead. ::: Converts a string to an integer. ```typescript const result = parseInt(string, radix); ``` ## Usage ### `parseInt(string, radix?)` Use `parseInt` when you want to convert a string to an integer. You can specify a radix to interpret it in a different base. ```typescript import { parseInt } from 'es-toolkit/compat'; // Basic decimal parsing parseInt('123'); // Returns: 123 parseInt('08'); // Returns: 8 // Automatic hexadecimal recognition parseInt('0x20'); // Returns: 32 // Explicit radix specification parseInt('08', 10); // Returns: 8 parseInt('0x20', 16); // Returns: 32 parseInt('1010', 2); // Returns: 10 // Use in arrays ['6', '08', '10'].map(parseInt); // Returns: [6, 8, 10] ``` Invalid format strings return NaN. ```typescript import { parseInt } from 'es-toolkit/compat'; parseInt('abc'); // Returns: NaN parseInt(''); // Returns: NaN parseInt('123abc'); // Returns: 123 (parses only the beginning) ``` #### Parameters * `string` (`string`): The string to convert to an integer. * `radix` (`number`, optional): The radix to use for conversion. Default is `0`, which automatically determines based on string format. #### Returns (`number`): Returns the converted integer. Returns NaN if conversion is not possible. --- --- url: /reference/function/partial.md --- # partial Creates a new function with some arguments pre-applied. ```typescript const partialFunc = partial(func, arg1, arg2); ``` ## Usage ### `partial(func, ...args)` Use `partial` when you want to fix some arguments of a function in advance. Pre-provided arguments are placed at the front of the function, and arguments passed later are added to the back. This is similar to the concept of currying, which is frequently used in functional programming. Unlike `bind`, it doesn't fix the `this` context. You can use `partial.placeholder` to pass specific arguments later. ```typescript import { partial } from 'es-toolkit/function'; // Basic usage function greet(greeting: string, name: string) { return `${greeting}, ${name}!`; } const sayHello = partial(greet, 'Hello'); console.log(sayHello('John')); // 'Hello, John!' console.log(sayHello('Jane')); // 'Hello, Jane!' // Applying multiple arguments function multiply(a: number, b: number, c: number) { return a * b * c; } const double = partial(multiply, 2); console.log(double(3, 4)); // 24 const doubleAndTriple = partial(multiply, 2, 3); console.log(doubleAndTriple(4)); // 24 ``` You can adjust the argument order using placeholders. ```typescript import { partial } from 'es-toolkit/function'; function subtract(a: number, b: number, c: number) { return a - b - c; } // Fix only the second argument, pass the first and third later const subtractFrom5 = partial(subtract, partial.placeholder, 5, partial.placeholder); console.log(subtractFrom5(10, 2)); // 10 - 5 - 2 = 3 // Using with array methods const numbers = [1, 2, 3, 4, 5]; const addTen = partial((x: number, y: number) => x + y, 10); const result = numbers.map(addTen); console.log(result); // [11, 12, 13, 14, 15] ``` #### Parameters * `func` (`F`): The function to partially apply arguments to. * `args` (`any[]`, optional): The arguments to pre-apply. #### Returns (`(...args: any[]) => ReturnType`): Returns a new function with some arguments pre-applied. --- --- url: /reference/compat/function/partial.md --- # partial (Lodash Compatibility) ::: warning Use `es-toolkit`'s `partial` This `partial` function is inefficient due to many overloads and union type handling. In most cases, it can be replaced with a simpler arrow function. Instead, use the faster and more modern [`partial`](../../function/partial.md) from `es-toolkit`. ::: Creates a partially applied function by pre-filling some arguments. ```typescript const partialFunc = partial(func, ...args); ``` ## Usage ### `partial(func, ...args)` Use `partial` when you want to create a partially applied function by pre-filling some arguments. It's mainly useful for fixing the first arguments when argument order matters. ```typescript import { partial } from 'es-toolkit/compat'; // Basic usage function greet(greeting, name, punctuation) { return `${greeting} ${name}${punctuation}`; } // Pre-set the first argument const sayHello = partial(greet, 'Hello'); sayHello('Alice', '!'); // 'Hello Alice!' // Pre-set multiple arguments const greetAlice = partial(greet, 'Hello', 'Alice'); greetAlice('!'); // 'Hello Alice!' // Use placeholder to control argument order const greetWithExclamation = partial(greet, partial.placeholder, 'Alice', '!'); greetWithExclamation('Hi'); // 'Hi Alice!' ``` In most cases, it can be replaced with arrow functions: ```typescript // Use arrow functions instead of partial (recommended) const sayHello = (name, punctuation) => greet('Hello', name, punctuation); const greetAlice = punctuation => greet('Hello', 'Alice', punctuation); ``` #### Parameters * `func` (`Function`): The function to partially apply. * `...args` (`any[]`): The arguments to pre-fill. Use `partial.placeholder` to control argument order. #### Returns (`Function`): Returns a new function with pre-filled arguments. --- --- url: /reference/function/partialRight.md --- # partialRight Creates a new function with some parameters pre-applied from the right. ```typescript const partialRightFunc = partialRight(func, arg1, arg2); ``` ## Usage ### `partialRight(func, ...args)` Use `partialRight` when you want to fix some parameters of a function from the right. Opposite to `partial`, pre-provided parameters are placed at the back of the function, and parameters passed later are added to the front. This is useful when you want to fix the last parameters and dynamically change only the front parameters. You can use `partialRight.placeholder` to pass specific parameters later. ```typescript import { partialRight } from 'es-toolkit/function'; // Basic usage function greet(greeting: string, name: string) { return `${greeting}, ${name}!`; } const greetJohn = partialRight(greet, 'John'); console.log(greetJohn('Hello')); // 'Hello, John!' console.log(greetJohn('Hi')); // 'Hi, John!' // Applying multiple parameters function subtract(a: number, b: number, c: number) { return a - b - c; } const subtractFrom10And5 = partialRight(subtract, 5, 2); console.log(subtractFrom10And5(10)); // 10 - 5 - 2 = 3 // Applying constants in mathematical operations function divide(dividend: number, divisor: number) { return dividend / divisor; } const divideBy2 = partialRight(divide, 2); console.log(divideBy2(10)); // 10 / 2 = 5 console.log(divideBy2(20)); // 20 / 2 = 10 ``` You can adjust the parameter order using placeholders. ```typescript import { partialRight } from 'es-toolkit/function'; function formatMessage(level: string, message: string, timestamp: string) { return `[${level}] ${message} at ${timestamp}`; } // Fix only the last parameter and pass the others later const logWithTime = partialRight(formatMessage, partialRight.placeholder, '2023-01-01'); console.log(logWithTime('INFO', 'Application started')); // '[INFO] Application started at 2023-01-01' // Using with arrays const numbers = [1, 2, 3, 4, 5]; const appendSuffix = partialRight((num: number, suffix: string) => `${num}${suffix}`, 'th'); const result = numbers.map(appendSuffix); console.log(result); // ['1th', '2th', '3th', '4th', '5th'] ``` #### Parameters * `func` (`F`): The function to partially apply parameters to. * `args` (`any[]`, optional): The parameters to pre-apply from the right. #### Returns (`(...args: any[]) => ReturnType`): Returns a new function with some parameters pre-applied from the right. --- --- url: /reference/compat/function/partialRight.md --- # partialRight (Lodash Compatibility) ::: warning Use `es-toolkit`'s `partialRight` This `partialRight` function is inefficient due to many overloads and union type handling. In most cases, it can be replaced with a simpler arrow function. Instead, use the faster and more modern [`partialRight`](../../function/partialRight.md) from `es-toolkit`. ::: Creates a partially applied function by pre-filling arguments from the right. ```typescript const partialFunc = partialRight(func, ...args); ``` ## Usage ### `partialRight(func, ...args)` Use `partialRight` when you want to create a partially applied function by pre-filling arguments from the right. It's mainly useful for fixing the last arguments when argument order matters. ```typescript import { partialRight } from 'es-toolkit/compat'; // Basic usage function greet(greeting, name, punctuation) { return `${greeting} ${name}${punctuation}`; } // Pre-set the last argument const greetWithExclamation = partialRight(greet, '!'); greetWithExclamation('Hello', 'Alice'); // 'Hello Alice!' // Pre-set multiple arguments const sayHiToAlice = partialRight(greet, 'Alice', '!'); sayHiToAlice('Hi'); // 'Hi Alice!' // Use placeholder to control argument order const greetAliceWithCustom = partialRight(greet, 'Alice', partialRight.placeholder); greetAliceWithCustom('Hello', '?'); // 'Hello Alice?' ``` In most cases, it can be replaced with arrow functions: ```typescript // Use arrow functions instead of partialRight (recommended) const greetWithExclamation = (greeting, name) => greet(greeting, name, '!'); const sayHiToAlice = greeting => greet(greeting, 'Alice', '!'); ``` #### Parameters * `func` (`Function`): The function to partially apply. * `...args` (`any[]`): The arguments to pre-fill. Use `partialRight.placeholder` to control argument order. #### Returns (`Function`): Returns a new function with arguments pre-filled from the right. --- --- url: /reference/array/partition.md --- # partition Returns a tuple that splits an array into two groups based on a condition. ```typescript const [truthy, falsy] = partition(arr, isInTruthy); ``` ## Usage ### `partition(arr, isInTruthy)` Use `partition` when you want to separate elements in an array into two groups based on a specific condition. It separates elements for which the condition function returns `true` and elements for which it returns `false` into different arrays. ```typescript import { partition } from 'es-toolkit/array'; // Split a number array into even and odd numbers. const numbers = [1, 2, 3, 4, 5, 6]; const [evens, odds] = partition(numbers, x => x % 2 === 0); // evens: [2, 4, 6] // odds: [1, 3, 5] // Split an object array by a specific condition. const users = [ { name: 'Alice', active: true }, { name: 'Bob', active: false }, { name: 'Charlie', active: true }, ]; const [activeUsers, inactiveUsers] = partition(users, user => user.active); // activeUsers: [{ name: 'Alice', active: true }, { name: 'Charlie', active: true }] // inactiveUsers: [{ name: 'Bob', active: false }] ``` It returns two empty arrays for an empty array. ```typescript import { partition } from 'es-toolkit/array'; const [truthy, falsy] = partition([], x => x > 0); // truthy: [] // falsy: [] ``` #### Parameters * `arr` (`T[]`): The array to split into two groups. * `isInTruthy` (`(value: T, index: number, array: readonly T[]) => boolean`): A condition function that determines whether each element should be included in the first array (truthy) or the second array (falsy). The function is called with the value, its index, and the entire array. #### Returns (`[truthy: T[], falsy: T[]]`): A tuple consisting of two arrays. The first array contains elements for which the condition is `true`, and the second array contains elements for which the condition is `false`. --- --- url: /reference/compat/array/partition.md --- # partition (Lodash Compatibility) ::: warning Use [partition](../../array/partition.md) from `es-toolkit` instead This `partition` function operates slowly due to handling `null` or `undefined` and various predicate types. Use the faster and more modern [partition](../../array/partition.md) from `es-toolkit` instead. ::: Splits the elements of a collection into two groups based on a condition. ```typescript const [truthy, falsy] = partition(collection, predicate); ``` ## Usage ### `partition(collection, predicate)` Splits the elements of an array or object into two groups based on a given predicate function. The first group contains elements where the predicate is true, and the second group contains elements where the predicate is false. ```typescript import { partition } from 'es-toolkit/compat'; // Split number array into even and odd partition([1, 2, 3, 4, 5, 6], n => n % 2 === 0); // => [[2, 4, 6], [1, 3, 5]] // Specify condition with property name const users = [ { name: 'john', active: true }, { name: 'jane', active: false }, { name: 'bob', active: true }, ]; partition(users, 'active'); // => [ // [{ name: 'john', active: true }, { name: 'bob', active: true }], // [{ name: 'jane', active: false }] // ] // Filter with object condition partition(users, { active: true }); // => [ // [{ name: 'john', active: true }, { name: 'bob', active: true }], // [{ name: 'jane', active: false }] // ] // Filter with array condition partition(users, ['name', 'john']); // => [ // [{ name: 'john', active: true }], // [{ name: 'jane', active: false }, { name: 'bob', active: true }] // ] ``` For objects, partitions the values. ```typescript import { partition } from 'es-toolkit/compat'; const obj = { a: { score: 90 }, b: { score: 40 }, c: { score: 80 }, }; partition(obj, item => item.score >= 80); // => [[{ score: 90 }, { score: 80 }], [{ score: 40 }]] ``` `null` or `undefined` are treated as empty arrays. ```typescript import { partition } from 'es-toolkit/compat'; partition(null, x => x > 0); // [[], []] partition(undefined, 'active'); // [[], []] ``` #### Parameters * `collection` (`ArrayLike | T | null | undefined`): The array or object to partition. * `predicate` (`((value: T) => unknown) | Partial | [PropertyKey, any] | PropertyKey`, optional): The condition to test each element. Can be a function, partial object, property-value array, or property name. Defaults to `identity`. #### Returns (`[T[], T[]]`): Returns an array containing an array of elements that satisfy the condition and an array of elements that don't. --- --- url: /reference/string/pascalCase.md --- # pascalCase Converts a string to pascal case. ```typescript const converted = pascalCase(str); ``` ## Usage ### `pascalCase(str)` Use `pascalCase` when you want to convert a string to pascal case. Pascal case is a naming convention where the first letter of each word is capitalized and words are joined without separators. ```typescript import { pascalCase } from 'es-toolkit/string'; // Basic usage pascalCase('pascalCase'); // 'PascalCase' pascalCase('some whitespace'); // 'SomeWhitespace' // Words connected with hyphens or underscores pascalCase('hyphen-text'); // 'HyphenText' pascalCase('snake_case'); // 'SnakeCase' // Handling consecutive uppercase letters pascalCase('HTTPRequest'); // 'HttpRequest' pascalCase('XMLHttpRequest'); // 'XmlHttpRequest' ``` It also correctly handles strings with various separators. ```typescript import { pascalCase } from 'es-toolkit/string'; // Mixed separators pascalCase('camelCase-with_mixed.separators'); // 'CamelCaseWithMixedSeparators' // With numbers pascalCase('version2.1.0'); // 'Version210' // With special characters pascalCase('user@email.com'); // 'UserEmailCom' ``` #### Parameters * `str` (`string`): The string to convert to pascal case. #### Returns (`string`): Returns a new string converted to pascal case. ## Demo ::: sandpack ```ts index.ts import { pascalCase } from 'es-toolkit/string'; console.log(pascalCase('pascalCase')); ``` ::: --- --- url: /performance.md description: The performance difference between es-toolkit and alternative libraries --- # Performance ![Graph showing the difference in performance between es-toolkit and lodash. Using es-toolkit results in a performance gain of up to 11 times.](/assets/performance.png) Designed with performance in mind, es-toolkit provides an average of 2× performance improvement compared to alternative libraries like lodash. Some functions achieve up to an 11× performance gain by fully utilizing modern JavaScript APIs. ## Performance Comparison | | es-toolkit@0.0.1 | lodash-es@4.17.21 | Difference | | --------------------------------------------------------- | ---------------- | ----------------- | ---------- | | [omit](./reference/object/omit.md) | 4,767,360 times | 403,624 times | 11.8× | | [pick](./reference/object/pick.md) | 9,121,839 times | 2,663,072 times | 3.43× | | [differenceWith](./reference/array/differenceWith.md) | 9,291,897 times | 4,275,222 times | 2.17× | | [difference](./reference/array/difference.md) | 10,436,101 times | 5,155,631 times | 2.02× | | [intersectionWith](./reference/array/intersectionWith.md) | 8,074,722 times | 3,814,479 times | 2.12× | | [intersection](./reference/array/intersection.md) | 9,999,571 times | 4,630,316 times | 2.15× | | [unionBy](./reference/array/unionBy.md) | 6,435,983 times | 3,794,899 times | 1.69× | | [union](./reference/array/union.md) | 5,059,209 times | 4,771,400 times | 1.06× | | [dropRightWhile](./reference/array/dropRightWhile.md) | 7,529,559 times | 5,606,439 times | 1.34× | | [groupBy](./reference/array/groupBy.md) | 5,000,235 times | 5,206,286 times | 0.96× | Tested with MacBook Pro 14-inch (M1 Max, 2021). Refer to our [benchmark code](https://github.com/toss/es-toolkit/tree/main/benchmarks). --- --- url: /reference/object/pick.md --- # pick Returns a new object containing only the properties corresponding to the specified keys. ```typescript const result = pick(obj, keys); ``` ## Usage ### `pick(obj, keys)` Use `pick` when you want to select only specific keys from an object. It returns a new object containing only the properties corresponding to the specified keys. ```typescript import { pick } from 'es-toolkit/object'; // Select specific keys const obj = { a: 1, b: 2, c: 3, d: 4 }; const result = pick(obj, ['a', 'c']); // result is { a: 1, c: 3 } // Non-existent keys are ignored const safe = pick(obj, ['a', 'nonexistent']); // safe is { a: 1 } // Can be used with nested objects const nested = { user: { name: 'John', age: 30 }, posts: ['post1', 'post2'], settings: { theme: 'dark' }, }; const picked = pick(nested, ['user', 'settings']); // picked is { user: { name: 'John', age: 30 }, settings: { theme: 'dark' } } ``` #### Parameters * `obj` (`T extends Record`): The object to select properties from. * `keys` (`readonly K[]`): An array of keys to select from the object. #### Returns (`Pick`): A new object containing only the properties corresponding to the specified keys. --- --- url: /reference/compat/object/pick.md --- # pick (Lodash compatibility) ::: warning Use `pick` from `es-toolkit` This `pick` function is relatively slow due to complex path processing, calling `get`/`set` functions, and handling `null`/`undefined`. Use the faster and more modern [`pick`](../../object/pick.md) from `es-toolkit` instead. ::: Creates a new object by selecting only specified properties from an object. ```typescript const result = pick(obj, ...keys); ``` ## Usage ### `pick(object, ...props)` Use `pick` when you want to create a new object containing only the desired properties from an object. You can pass multiple keys at once using an array, or pass them one by one as individual arguments. Supports deep key paths so you can also select nested properties. ```typescript import { pick } from 'es-toolkit/compat'; // Basic usage const obj = { a: 1, b: 2, c: 3, d: 4 }; const result = pick(obj, ['a', 'c']); // Result: { a: 1, c: 3 } // Pass as individual arguments const result2 = pick(obj, 'a', 'c'); // Result: { a: 1, c: 3 } // Select deep paths const nested = { user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, admin: true, }; const userInfo = pick(nested, 'user.profile.name', 'admin'); // Result: { user: { profile: { name: 'John' } }, admin: true } // Mix arrays and individual keys const mixed = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; const selected = pick(mixed, ['a', 'b'], 'c', 'd.e'); // Result: { a: 1, b: 2, c: 3, d: { e: 4 } } // Distinguish between dot notation keys and actual dotted keys const ambiguous = { 'a.b': 1, // Actual key 'a.b' a: { b: 2, c: 3 }, // Nested object }; const dotKey = pick(ambiguous, 'a.b'); // Result: { 'a.b': 1 } (actual key takes priority) ``` `null` or `undefined` are treated as empty objects. ```typescript import { pick } from 'es-toolkit/compat'; pick(null, ['a', 'b']); // {} pick(undefined, ['a', 'b']); // {} ``` #### Parameters * `object` (`T | null | undefined`): The object to select properties from. * `...props` (`Array>`): The property keys to select. Can specify single keys, arrays of keys, or deep key paths. #### Returns (`Pick | Partial`): Returns a new object containing only the specified properties. --- --- url: /reference/object/pickBy.md --- # pickBy Returns a new object containing only the properties that satisfy the condition function. ```typescript const result = pickBy(obj, shouldPick); ``` ## Usage ### `pickBy(obj, shouldPick)` Use `pickBy` when you want to selectively pick properties from an object based on a condition function. Only properties for which the condition function returns `true` are included in the new object. ```typescript import { pickBy } from 'es-toolkit/object'; // Pick only properties with string values const obj = { a: 1, b: 'select', c: 3, d: 'also select' }; const result = pickBy(obj, value => typeof value === 'string'); // result is { b: 'select', d: 'also select' } // Pick only even values const numbers = { a: 1, b: 2, c: 3, d: 4 }; const evens = pickBy(numbers, value => value % 2 === 0); // evens is { b: 2, d: 4 } // Use both key and value const data = { user1: 25, user2: 17, admin1: 30, admin2: 28 }; const admins = pickBy(data, (value, key) => key.startsWith('admin') && value > 25); // admins is { admin1: 30, admin2: 28 } ``` #### Parameters * `obj` (`T extends Record`): The object to filter properties from. * `shouldPick` (`(value: T[keyof T], key: keyof T) => boolean`): A condition function that determines whether to pick a property. Receives the value and key, and returns `true` to pick, `false` to exclude. #### Returns (`Partial`): A new object containing only the properties that satisfy the condition function. --- --- url: /reference/compat/object/pickBy.md --- # pickBy (Lodash compatibility) ::: warning Use `pickBy` from `es-toolkit` This `pickBy` function is relatively slow due to array-like object checking, `iteratee` conversion, and key transformation processes. Use the faster and more modern [`pickBy`](../../object/pickBy.md) from `es-toolkit` instead. ::: Creates a new object selecting only properties for which the predicate function returns true. ```typescript const result = pickBy(obj, predicate); ``` ## Usage ### `pickBy(object, predicate)` Executes a predicate function for each property of the object and creates a new object containing only properties for which the predicate returns true. Useful for dynamically selecting properties based on conditions. ```typescript import { pickBy } from 'es-toolkit/compat'; // Select only values of specific type const data = { a: 1, b: 'keep', c: 3, d: 'select' }; const strings = pickBy(data, value => typeof value === 'string'); // Result: { b: 'keep', d: 'select' } // Select properties based on condition const user = { id: 1, name: 'John', age: 0, active: true, email: '' }; const validData = pickBy(user, value => Boolean(value)); // Result: { id: 1, name: 'John', active: true } (only truthy values) // Filter by key name const settings = { userSetting: true, adminSetting: false, debugMode: true }; const userOnly = pickBy(settings, (value, key) => key.startsWith('user')); // Result: { userSetting: true } // Select only number properties const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; const numbersOnly = pickBy(mixed, value => typeof value === 'number'); // Result: { num1: 42, num2: 0 } // Can also be used with arrays const arr = [1, 2, 3, 4, 5]; const evens = pickBy(arr, value => value % 2 === 0); // Result: { '1': 2, '3': 4 } (indices and values of even numbers) // Utilize value, key, and original object const scores = { math: 90, science: 75, english: 85, art: 60 }; const highScores = pickBy(scores, (value, key, obj) => { const average = Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length; return value > average; }); // Result: { math: 90, english: 85 } ``` When called without a predicate function, it selects only truthy values. ```typescript import { pickBy } from 'es-toolkit/compat'; const data = { a: 1, b: '', c: 0, d: 'hello', e: null, f: true }; const truthyValues = pickBy(data); // Result: { a: 1, d: 'hello', f: true } ``` `null` or `undefined` are treated as empty objects. ```typescript import { pickBy } from 'es-toolkit/compat'; pickBy(null, () => true); // {} pickBy(undefined, () => true); // {} ``` #### Parameters * `object` (`Record | Record | object | null | undefined`): The source object to filter. * `predicate` (`ValueKeyIterateeTypeGuard | ValueKeyIteratee | ValueKeyIteratee`, optional): The predicate function to execute for each property. Properties for which this returns true are selected. Defaults to the `identity` function. #### Returns (`Record | Record | Partial`): Returns a new object consisting of properties that match the condition. --- --- url: /reference/compat/object/property.md --- # property (Lodash compatibility) ::: warning Use `get` function directly This `property` function is a wrapper function that internally calls the `get` function, causing additional function call overhead. Use the faster and more modern `get` function directly or use optional chaining (`?.`) instead. ::: Creates a function that retrieves the value at a specified path. ```typescript const getter = property(path); ``` ## Usage ### `property(path)` Use `property` when you want to create a function that retrieves values from a specific path. The created function can be reused across multiple objects, making it convenient to use with array methods. ```typescript import { property } from 'es-toolkit/compat'; // Basic usage const getName = property('name'); const user = { name: 'John', age: 30 }; const result = getName(user); // Result: 'John' // Deep path access const getNestedValue = property('user.profile.name'); const data = { user: { profile: { name: 'Alice', age: 25 } } }; const nestedResult = getNestedValue(data); // Result: 'Alice' // Using array path const getByArray = property(['user', 'profile', 'name']); const arrayResult = getByArray(data); // Result: 'Alice' // Use with array methods const users = [ { user: { profile: { name: 'John' } } }, { user: { profile: { name: 'Jane' } } }, { user: { profile: { name: 'Bob' } } }, ]; const names = users.map(property('user.profile.name')); // Result: ['John', 'Jane', 'Bob'] // Array index access const getFirstItem = property('[0]'); const items = ['first', 'second', 'third']; const firstItem = getFirstItem(items); // Result: 'first' // Number key access const getIndex = property(1); const arr = ['a', 'b', 'c']; const secondItem = getIndex(arr); // Result: 'b' ``` Returns `undefined` if the path doesn't exist. ```typescript import { property } from 'es-toolkit/compat'; const getMissing = property('nonexistent.path'); const result = getMissing({ some: 'data' }); // Result: undefined ``` #### Parameters * `path` (`PropertyPath`): The path to retrieve the value from. Can be a string, number, symbol, or an array of these. #### Returns (`(object: T) => R`): Returns a function that returns the value at the specified path from a given object. --- --- url: /reference/compat/object/propertyOf.md --- # propertyOf (Lodash compatibility) ::: warning Use `get` function directly This `propertyOf` function is a wrapper function that internally calls the `get` function, causing additional function call overhead. Use the faster and more modern `get` function directly or use optional chaining (`?.`) instead. ::: Creates a function that retrieves values from various paths in a specific object. ```typescript const getter = propertyOf(obj); ``` ## Usage ### `propertyOf(object)` Use `propertyOf` when you want to create a function that retrieves values from multiple paths in a single object. Unlike `property`, it fixes the object first and allows you to query various paths. ```typescript import { propertyOf } from 'es-toolkit/compat'; // Basic usage const data = { name: 'John', age: 30, city: 'New York' }; const getValue = propertyOf(data); const name = getValue('name'); // Result: 'John' const age = getValue('age'); // Result: 30 // Deep path access const complexData = { user: { profile: { name: 'Alice', age: 25 } }, settings: { theme: 'dark', lang: 'en' }, }; const getComplexValue = propertyOf(complexData); const userName = getComplexValue('user.profile.name'); // Result: 'Alice' const theme = getComplexValue('settings.theme'); // Result: 'dark' // Using array path const arrayPath = getComplexValue(['user', 'profile', 'age']); // Result: 25 // Process multiple paths as array const paths = ['user.profile.name', 'settings.theme', 'settings.lang']; const values = paths.map(getComplexValue); // Result: ['Alice', 'dark', 'en'] (values from each path) // Array index access const arrayData = [10, 20, 30]; const getArrayValue = propertyOf(arrayData); const firstItem = getArrayValue(0); // Result: 10 const secondItem = getArrayValue('[1]'); // Result: 20 ``` Returns `undefined` if the path doesn't exist. ```typescript import { propertyOf } from 'es-toolkit/compat'; const data = { a: 1, b: 2 }; const getValue = propertyOf(data); const missing = getValue('nonexistent.path'); // Result: undefined ``` #### Parameters * `object` (`T`): The target object to retrieve values from. #### Returns (`(path: PropertyPath) => any`): Returns a function that returns the object's value at a given path. --- --- url: /reference/array/pull.md --- # pull Removes all specified values from an array. ```typescript const result = pull(arr, valuesToRemove); ``` ## Usage ### `pull(arr, valuesToRemove)` Use `pull` when you want to remove all occurrences of specific values from an array. This function modifies the original array directly and returns the modified array. ```typescript import { pull } from 'es-toolkit/array'; // Remove specific values from a number array. const numbers = [1, 2, 3, 4, 5, 2, 4]; pull(numbers, [2, 4]); console.log(numbers); // [1, 3, 5] // Remove specific strings from a string array. const fruits = ['apple', 'banana', 'cherry', 'banana', 'date']; pull(fruits, ['banana', 'cherry']); console.log(fruits); // ['apple', 'date'] // Remove objects with the same reference from an object array. const obj1 = { id: 1 }; const obj2 = { id: 2 }; const obj3 = { id: 3 }; const objects = [obj1, obj2, obj3, obj1]; pull(objects, [obj1]); console.log(objects); // [{ id: 2 }, { id: 3 }] ``` If you want to create a new array without modifying the original, use the `difference` function. ```typescript import { pull } from 'es-toolkit/array'; import { difference } from 'es-toolkit/array'; const original = [1, 2, 3, 4, 5]; // pull modifies the original array. const arr1 = [...original]; pull(arr1, [2, 4]); console.log(arr1); // [1, 3, 5] // difference returns a new array. const arr2 = difference(original, [2, 4]); console.log(original); // [1, 2, 3, 4, 5] (unchanged) console.log(arr2); // [1, 3, 5] ``` #### Parameters * `arr` (`T[]`): The array from which to remove values. * `valuesToRemove` (`readonly unknown[]`): An array of values to remove from the array. #### Returns (`T[]`): The original array with the specified values removed. The original array is modified and returned. --- --- url: /reference/compat/array/pull.md --- # pull (Lodash compatibility) ::: warning Use [pull](../../array/pull.md) from `es-toolkit` This `pull` function is for Lodash compatibility and operates slower due to more complex type handling and overloading. Instead, use the faster and more modern [pull](../../array/pull.md) from `es-toolkit`. ::: Removes all specified values from the array. ```typescript const result = pull(array, ...valuesToRemove); ``` ## Usage ### `pull(array, ...valuesToRemove)` Removes all specified values from the array and modifies the original array. It directly modifies the original array without copying, which can save memory. ```typescript import { pull } from 'es-toolkit/compat'; // Remove specific values from number array const numbers = [1, 2, 3, 2, 4, 2, 5]; pull(numbers, 2, 3); console.log(numbers); // [1, 4, 5] // Remove specific values from string array const fruits = ['apple', 'banana', 'apple', 'cherry']; pull(fruits, 'apple'); console.log(fruits); // ['banana', 'cherry'] ``` #### Parameters * `array` (`T[]`): The array to modify. * `...valuesToRemove` (`T[]`): The values to remove from the array. #### Returns (`T[]`): Returns the modified original array. --- --- url: /reference/compat/array/pullAll.md --- # pullAll (Lodash compatibility) Removes all values from the array that are contained in the array of specified values. ```typescript const result = pullAll(array, valuesToRemove); ``` ## Usage ### `pullAll(array, valuesToRemove)` Removes all values contained in the `valuesToRemove` array from the array and modifies the original array. Similar to the `pull` function, but accepts values to remove as an array. ```typescript import { pullAll } from 'es-toolkit/compat'; // Remove specific values from number array const numbers = [1, 2, 3, 2, 4, 2, 5]; pullAll(numbers, [2, 3]); console.log(numbers); // [1, 4, 5] // Remove specific values from string array const fruits = ['apple', 'banana', 'apple', 'cherry', 'banana']; pullAll(fruits, ['apple', 'banana']); console.log(fruits); // ['cherry'] ``` If you pass an empty array, `null`, or `undefined`, nothing will be removed. ```typescript import { pullAll } from 'es-toolkit/compat'; const numbers = [1, 2, 3]; pullAll(numbers, []); console.log(numbers); // [1, 2, 3] pullAll(numbers, null); console.log(numbers); // [1, 2, 3] ``` #### Parameters * `array` (`T[]`): The array to modify. * `valuesToRemove` (`ArrayLike`, optional): The array containing values to remove from the array. Defaults to `[]`. #### Returns (`T[]`): Returns the modified original array. --- --- url: /reference/compat/array/pullAllBy.md --- # pullAllBy (Lodash compatibility) Removes specified values from the array based on values transformed by an iteratee. ```typescript const modified = pullAllBy(array, valuesToRemove, iteratee); ``` ## Usage ### `pullAllBy(array, values, iteratee)` Removes specified values from the array based on values transformed through the provided iteratee function. The original array is modified and the modified array is returned. ```typescript import { pullAllBy } from 'es-toolkit/compat'; // Remove by comparing property values const array = [{ x: 1 }, { x: 2 }, { x: 3 }, { x: 1 }]; pullAllBy(array, [{ x: 1 }, { x: 3 }], 'x'); console.log(array); // [{ x: 2 }] // Compare by transforming values with a function const numbers = [1, 2, 3, 4, 5]; pullAllBy(numbers, [2, 4], n => n % 2); console.log(numbers); // [1, 3, 5] (only odd numbers remain) ``` If the array is empty, `null`, or `undefined`, it returns the original array as is. ```typescript import { pullAllBy } from 'es-toolkit/compat'; pullAllBy([], [1, 2], x => x); // [] pullAllBy(null as any, [1, 2], x => x); // null ``` #### Parameters * `array` (`T[]`): The array to modify. * `values` (`ArrayLike`, optional): The array of values to remove. * `iteratee` (`ValueIteratee`, optional): The iteratee function to apply to each element. You can use a property name, partial object, or function. #### Returns (`T[]`): Returns the original array with the specified values removed. --- --- url: /reference/compat/array/pullAllWith.md --- # pullAllWith (Lodash Compatibility) Removes specified values from an array using a comparison function. ```typescript const modified = pullAllWith(array, valuesToRemove, comparator); ``` ## Usage ### `pullAllWith(array, values, comparator)` Removes specified values from an array using the provided comparison function. The original array is modified and the modified array is returned. ```typescript import { pullAllWith } from 'es-toolkit/compat'; // Remove with object comparison const array = [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, ]; pullAllWith(array, [{ x: 3, y: 4 }], (a, b) => a.x === b.x && a.y === b.y); console.log(array); // [{ x: 1, y: 2 }, { x: 5, y: 6 }] // Remove by comparing string length const words = ['hello', 'world', 'test', 'code']; pullAllWith(words, ['hi'], (a, b) => a.length === b.length); console.log(words); // ['hello', 'world', 'code'] ('test' removed as it has same length as 'hi') ``` If the array is empty or `null`, `undefined`, the original array is returned as is. ```typescript import { pullAllWith } from 'es-toolkit/compat'; pullAllWith([], [1], (a, b) => a === b); // [] pullAllWith(null as any, [1], (a, b) => a === b); // null ``` #### Parameters * `array` (`T[]`): The array to modify. * `values` (`ArrayLike`, optional): The array of values to remove. * `comparator` (`(a: T, b: T) => boolean`, optional): The function to compare two elements. Should return `true` if the two elements are considered equal. #### Returns (`T[]`): Returns the original array with the specified values removed. --- --- url: /reference/array/pullAt.md --- # pullAt Removes elements at specified indices from an array and returns the removed elements. ```typescript const removed = pullAt(arr, indices); ``` ## Usage ### `pullAt(arr, indicesToRemove)` Use `pullAt` when you want to remove elements at specific positions in an array. This function modifies the original array and returns the removed elements in a new array. It also supports negative indices, which count from the end of the array. ```typescript import { pullAt } from 'es-toolkit/array'; // Remove elements at multiple indices at once. const numbers = [10, 20, 30, 40, 50]; const removed = pullAt(numbers, [1, 3, 4]); console.log(removed); // [20, 40, 50] console.log(numbers); // [10, 30] // Safely handle duplicate indices. const fruits = ['apple', 'banana', 'cherry', 'date']; const removedFruits = pullAt(fruits, [1, 2, 1]); console.log(removedFruits); // ['banana', 'cherry', 'banana'] console.log(fruits); // ['apple', 'date'] ``` If you specify a non-existent index, `undefined` is returned for that position. ```typescript import { pullAt } from 'es-toolkit/array'; const items = [1, 2, 3]; const removed = pullAt(items, [0, 5, 2]); console.log(removed); // [1, undefined, 3] console.log(items); // [2] ``` #### Parameters * `arr` (`T[]`): The array from which to remove elements. * `indicesToRemove` (`number[]`): An array of indices of elements to remove. Negative indices count from the end of the array. #### Returns (`T[]`): A new array containing the removed elements. For non-existent indices, `undefined` is included. --- --- url: /reference/compat/array/pullAt.md --- # pullAt (Lodash Compatibility) ::: warning Use [pullAt](../../array/pullAt.md) from `es-toolkit` instead This `pullAt` function operates slowly due to complex type handling and overloading. Use the faster and more modern [pullAt](../../array/pullAt.md) from `es-toolkit` instead. ::: Removes elements at specified indexes from an array and returns the removed elements. ```typescript const removed = pullAt(array, ...indexes); ``` ## Usage ### `pullAt(array, ...indexes)` Removes elements at specified indexes from an array and returns an array of the removed elements. The original array is modified. ```typescript import { pullAt } from 'es-toolkit/compat'; // Remove by individual indexes const array = [1, 2, 3, 4, 5]; const removed = pullAt(array, 1, 3); console.log(array); // [1, 3, 5] console.log(removed); // [2, 4] // Remove by array of indexes const colors = ['red', 'green', 'blue', 'yellow']; const removedColors = pullAt(colors, [0, 2]); console.log(colors); // ['green', 'yellow'] console.log(removedColors); // ['red', 'blue'] ``` Non-existent indexes are treated as `undefined`. ```typescript import { pullAt } from 'es-toolkit/compat'; const numbers = [10, 20, 30]; const removed = pullAt(numbers, 1, 5); console.log(numbers); // [10, 30] console.log(removed); // [20, undefined] ``` #### Parameters * `array` (`ArrayLike`): The array to modify. * `...indexes` (`Array`): The indexes of elements to remove. Can pass individual numbers or arrays of numbers. #### Returns (`ArrayLike`): Returns an array of removed elements. --- --- url: /reference/math/random.md --- # random Generates a random number within a specified range. The number can include decimals. ```typescript const randomNumber = random(min, max); ``` ## Usage ### `random(maximum)` / `random(minimum, maximum)` Use `random` when you need a random number. It generates numbers with decimal points. ```typescript import { random } from 'es-toolkit/math'; // Generate a random decimal between 0 and 5 (exclusive). const num1 = random(5); console.log(num1); // e.g., 2.718281828 // Generate a random decimal between 2 and 10 (exclusive). const num2 = random(2, 10); console.log(num2); // e.g., 7.158765432 // Can be used with negative ranges. const num3 = random(-5, -1); console.log(num3); // e.g., -3.842134567 // Decimal ranges are also possible. const num4 = random(1.5, 2.5); console.log(num4); // e.g., 1.923456789 ``` Throws an error if the range is invalid. ```typescript import { random } from 'es-toolkit/math'; // An error occurs if the maximum value is 0 or less. try { random(0); } catch (error) { console.error(error.message); // 'Invalid input: The maximum value must be greater than the minimum value.' } // An error occurs if the minimum value is greater than or equal to the maximum value. try { random(5, 3); } catch (error) { console.error(error.message); // 'Invalid input: The maximum value must be greater than the minimum value.' } ``` #### Parameters * `maximum` (`number`): The maximum value (exclusive) when using a single parameter. Must be greater than 0. * `minimum` (`number`): The minimum value (inclusive). * `maximum` (`number`): The maximum value (exclusive). Must be greater than the minimum value. #### Returns (`number`): Returns a random decimal within the specified range. #### Throws Throws an error if the maximum value is less than or equal to the minimum value. --- --- url: /reference/compat/math/random.md --- # random (Lodash Compatibility) ::: warning Use `Math.random()` This `random` function works slowly due to complex argument processing and type conversion. Use the faster `Math.random()` instead. ::: Creates a random number within a range. ```typescript const result = random(min, max, floating); ``` ## Usage ### `random(floating?)` Creates a random number between 0 and 1. ```typescript import { random } from 'es-toolkit/compat'; random(); // Returns: 0.123456789 (decimal between 0~1) random(true); // Returns: 0.987654321 (returns as decimal) random(false); // Returns: 0 or 1 (returns as integer) ``` ### `random(max, floating?)` Creates a random number from 0 to max. ```typescript import { random } from 'es-toolkit/compat'; random(5); // Returns: 3.456789 (decimal between 0~5) random(10, true); // Returns: 7.123456 (decimal between 0~10) random(3, false); // Returns: 2 (integer between 0~3) ``` ### `random(min, max, floating?)` Creates a random number from min to max. ```typescript import { random } from 'es-toolkit/compat'; random(1, 5); // Returns: 3.456789 (decimal between 1~5) random(0, 10, true); // Returns: 6.789012 (decimal between 0~10) random(1, 6, false); // Returns: 4 (integer between 1~6) ``` Range is automatically swapped if reversed. ```typescript import { random } from 'es-toolkit/compat'; random(5, 1); // Returns: 3.456789 (range becomes 1~5) ``` Guard object handles special cases. ```typescript import { random } from 'es-toolkit/compat'; const guard = { 5: 5 }; random(5, 5, guard); // Returns: 2.345678 (decimal between 0~5) ``` #### Parameters * `floating` (`boolean`, optional): Whether to return a decimal. Default is `true`. * `max` (`number`): The maximum value of the range (exclusive). * `min` (`number`): The minimum value of the range (inclusive). * `index` (`string | number`): The key to check in the guard object. * `guard` (`object`): The guard object that validates parameters. #### Returns (`number`): Returns a random number within the specified range. --- --- url: /reference/math/randomInt.md --- # randomInt Generates a random integer within a specified range. ```typescript const randomInteger = randomInt(min, max); ``` ## Usage ### `randomInt(maximum)` / `randomInt(minimum, maximum)` Use `randomInt` when you need a random integer. It returns only integers without decimal points. ```typescript import { randomInt } from 'es-toolkit/math'; // Generate a random integer between 0 and 5 (exclusive). const num1 = randomInt(5); console.log(num1); // e.g., 3 // Generate a random integer between 2 and 10 (exclusive). const num2 = randomInt(2, 10); console.log(num2); // e.g., 7 // Can be used with negative ranges. const num3 = randomInt(-5, -1); console.log(num3); // e.g., -3 // Simulate a dice roll (1-6) const diceRoll = randomInt(1, 7); console.log(diceRoll); // e.g., 4 // Select a random index from an array const items = ['apple', 'banana', 'cherry', 'date']; const randomIndex = randomInt(items.length); console.log(items[randomIndex]); // e.g., 'banana' ``` #### Parameters * `maximum` (`number`): The maximum value (exclusive) when using a single parameter. Must be greater than 0. * `minimum` (`number`): The minimum value (inclusive). * `maximum` (`number`): The maximum value (exclusive). Must be greater than the minimum value. #### Returns (`number`): Returns a random integer within the specified range. #### Throws Throws an error if the maximum value is less than or equal to the minimum value. --- --- url: /reference/math/range.md --- # range Creates an array of numbers within a specified range and step. ```typescript const numbers = range(end); const numbers = range(start, end, step); ``` ## Usage ### `range(end)` Use `range` when you need a consecutive array of numbers from 0 to a specified end value. It's useful for loops. ```typescript import { range } from 'es-toolkit/math'; // Create an array from 0 to 3. const numbers1 = range(4); console.log(numbers1); // [0, 1, 2, 3] // Indices for an array with 10 elements const indices = range(10); console.log(indices); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] // Can be used instead of forEach. range(5).forEach(i => { console.log(`Iteration ${i}`); // Iteration 0, Iteration 1, Iteration 2, Iteration 3, Iteration 4 }); ``` #### Parameters * `end` (`number`): The end value (exclusive). Starts from 0. #### Returns (`number[]`): Returns an array of numbers generated from 0 to the end value. ### `range(start, end, step?)` Use `range` when you need a consecutive array of numbers with a specified start value, end value, and step. It's useful for loops. ```typescript import { range } from 'es-toolkit/math'; // Create an array from 1 to 4. const numbers2 = range(1, 5); console.log(numbers2); // [1, 2, 3, 4] // Create an array from 0 to 20 with increments of 5. const numbers3 = range(0, 20, 5); console.log(numbers3); // [0, 5, 10, 15] // Can also go in the negative direction. const numbers4 = range(0, -5, -1); console.log(numbers4); // [0, -1, -2, -3, -4] // Can go from larger to smaller numbers. const numbers5 = range(5, 0, -1); console.log(numbers5); // [5, 4, 3, 2, 1] // Create page numbers in a specific range const pageNumbers = range(1, 11); console.log(pageNumbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` #### Parameters * `start` (`number`): The start value. Included in the result array. * `end` (`number`): The end value. Not included in the result array. * `step` (`number`, optional): The increment between each number. Must be a non-zero integer. Defaults to `1`. #### Returns (`number[]`): Returns an array of numbers generated with the specified range and step. #### Throws * Throws an error if `step` is 0 or not an integer. --- --- url: /reference/compat/math/range.md --- # range (Lodash Compatibility) ::: warning Use [range](../../math/range.md) from es-toolkit This `range` function works slowly due to complex argument processing and type conversion. Use the faster and more modern [range](../../math/range.md) from `es-toolkit` instead. ::: Creates an array of numbers in a range. ```typescript const numbers = range(start, end, step); ``` ## Usage ### `range(end)` Creates an array of numbers from 0 to end, incrementing by 1. ```typescript import { range } from 'es-toolkit/compat'; range(4); // Returns: [0, 1, 2, 3] range(0); // Returns: [] range(-4); // Returns: [0, -1, -2, -3] ``` ### `range(start, end)` Creates an array of numbers from start to end, incrementing by 1. ```typescript import { range } from 'es-toolkit/compat'; range(1, 5); // Returns: [1, 2, 3, 4] range(5, 1); // Returns: [5, 4, 3, 2] (automatically decrements by -1) range(-2, 3); // Returns: [-2, -1, 0, 1, 2] ``` ### `range(start, end, step)` Creates an array of numbers from start to end, incrementing by step. ```typescript import { range } from 'es-toolkit/compat'; range(0, 20, 5); // Returns: [0, 5, 10, 15] range(0, -4, -1); // Returns: [0, -1, -2, -3] range(1, 4, 0); // Returns: [1, 1, 1] ``` Decimal steps are also possible. ```typescript import { range } from 'es-toolkit/compat'; range(0, 1, 0.2); // Returns: [0, 0.2, 0.4, 0.6, 0.8] range(1, 0, -0.25); // Returns: [1, 0.75, 0.5, 0.25] ``` When used as an iteratee, it's handled with a guard object. ```typescript import { range } from 'es-toolkit/compat'; [1, 2, 3].map(range); // Returns: [[0], [0, 1], [0, 1, 2]] ``` #### Parameters * `start` (`number`): The start value of the range (inclusive). If `end` is not provided, this becomes the end value. * `end` (`number`, optional): The end value of the range (exclusive). * `step` (`number`, optional): The increment step. Default is 1 or -1. #### Returns (`number[]`): Returns an array of numbers in the specified range. --- --- url: /reference/math/rangeRight.md --- # rangeRight Creates an array of numbers in reverse order within a specified range and step. ```typescript const numbers = rangeRight(end); const numbers = rangeRight(start, end, step?); ``` ## Usage ### `rangeRight(end)` Use `rangeRight` when you need a consecutive array of numbers in reverse order from the end value to 0. It's like `range` but the result comes from the back. ```typescript import { rangeRight } from 'es-toolkit/math'; // Create an array from 3 to 0 in reverse order. const numbers1 = rangeRight(4); console.log(numbers1); // [3, 2, 1, 0] // Reverse indices of an array const items = ['a', 'b', 'c', 'd', 'e']; const reverseIndices = rangeRight(items.length); reverseIndices.forEach(i => { console.log(items[i]); // Outputs 'e', 'd', 'c', 'b', 'a' in order }); ``` #### Parameters * `end` (`number`): The end value (exclusive). Starts from 0. #### Returns (`number[]`): Returns a reverse array of numbers generated from the end value to 0. ### `rangeRight(start, end, step?)` Use `rangeRight` when you need a consecutive array of numbers in reverse order with a specified start value, end value, and step. It's like `range` but the result comes from the back. ```typescript import { rangeRight } from 'es-toolkit/math'; // Create an array from 4 to 1 in reverse order. const numbers2 = rangeRight(1, 5); console.log(numbers2); // [4, 3, 2, 1] // Create an array from 15 to 0 with decrements of 5. const numbers3 = rangeRight(0, 20, 5); console.log(numbers3); // [15, 10, 5, 0] // Can also go in the negative direction. const numbers4 = rangeRight(-5, 0, 1); console.log(numbers4); // [-1, -2, -3, -4, -5] // Can go from smaller to larger numbers. const numbers5 = rangeRight(5, 0, -1); console.log(numbers5); // [1, 2, 3, 4, 5] ``` Useful when you need reverse order for countdowns or pagination. ```typescript import { rangeRight } from 'es-toolkit/math'; // Create a countdown const countdown = rangeRight(0, 11); console.log(countdown); // [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] // Pagination from last page to first page const pageNumbers = rangeRight(1, 11); console.log(pageNumbers); // [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] ``` #### Parameters * `start` (`number`): The start value. Included in the result array. * `end` (`number`): The end value. Not included in the result array. * `step` (`number`, optional): The increment between each number. Must be a non-zero integer. Defaults to `1`. #### Returns (`number[]`): Returns a reverse array of numbers generated with the specified range and step. #### Throws * Throws an error if `step` is 0 or not an integer. --- --- url: /reference/compat/math/rangeRight.md --- # rangeRight (Lodash Compatibility) ::: warning Use [rangeRight](../../math/rangeRight.md) from es-toolkit This `rangeRight` function works slowly due to complex argument processing and type conversion. Use the faster and more modern [rangeRight](../../math/rangeRight.md) from `es-toolkit` instead. ::: Creates an array of numbers in a range in reverse order. ```typescript const numbers = rangeRight(start, end, step); ``` ## Usage ### `rangeRight(end)` Creates an array of numbers from 0 to end, incrementing by 1, then reverses the order. ```typescript import { rangeRight } from 'es-toolkit/compat'; rangeRight(4); // Returns: [3, 2, 1, 0] rangeRight(0); // Returns: [] rangeRight(-4); // Returns: [-3, -2, -1, 0] ``` ### `rangeRight(start, end)` Creates an array of numbers from start to end, incrementing by 1, then reverses the order. ```typescript import { rangeRight } from 'es-toolkit/compat'; rangeRight(1, 5); // Returns: [4, 3, 2, 1] rangeRight(5, 1); // Returns: [2, 3, 4, 5] (automatically decrements by -1, then reverses) rangeRight(-2, 3); // Returns: [2, 1, 0, -1, -2] ``` ### `rangeRight(start, end, step)` Creates an array of numbers from start to end, incrementing by step, then reverses the order. ```typescript import { rangeRight } from 'es-toolkit/compat'; rangeRight(0, 8, 2); // Returns: [6, 4, 2, 0] rangeRight(0, -4, -1); // Returns: [-3, -2, -1, 0] rangeRight(1, 4, 0); // Returns: [1, 1, 1] ``` Decimal steps are also possible. ```typescript import { rangeRight } from 'es-toolkit/compat'; rangeRight(0, 1, 0.2); // Returns: [0.8, 0.6, 0.4, 0.2, 0] rangeRight(1, 0, -0.25); // Returns: [0.25, 0.5, 0.75, 1] ``` When used as an iteratee, it's handled with a guard object. ```typescript import { rangeRight } from 'es-toolkit/compat'; [1, 2, 3].map(rangeRight); // Returns: [[0], [1, 0], [2, 1, 0]] ``` #### Parameters * `start` (`number`): The start value of the range (inclusive). If `end` is not provided, this becomes the end value. * `end` (`number`, optional): The end value of the range (exclusive). * `step` (`number`, optional): The increment step. Default is 1 or -1. #### Returns (`number[]`): Returns an array of numbers in the specified range in reverse order. --- --- url: /reference/compat/function/rearg.md --- # rearg (Lodash Compatibility) ::: warning Use arrow functions instead This `rearg` function creates a complex wrapper that rearranges argument order, which can be slow. You can write clearer and faster code by directly rearranging argument order using arrow functions. Use faster, more modern arrow functions instead. ::: Creates a new function that rearranges the arguments of the original function in the specified order. ```typescript const rearranged = rearg(func, ...indices); ``` ## Usage ### `rearg(func, ...indices)` Use `rearg` when you want to change the order of arguments when calling a function. It rearranges the arguments in the order specified by the indices and calls the original function. ```typescript import { rearg } from 'es-toolkit/compat'; const greet = (greeting, name) => `${greeting}, ${name}!`; // Swap argument order (1st, 0th) const rearrangedGreet = rearg(greet, 1, 0); rearrangedGreet('World', 'Hello'); // Returns: "Hello, World!" // Original function remains unchanged greet('Hello', 'World'); // Returns: "Hello, World!" ``` You can also pass indices as an array. ```typescript import { rearg } from 'es-toolkit/compat'; const fn = (a, b, c) => [a, b, c]; // Specify indices using an array const rearranged = rearg(fn, [2, 0, 1]); rearranged('a', 'b', 'c'); // Returns: ['c', 'a', 'b'] ``` You can rearrange only some arguments and leave the rest as is. ```typescript import { rearg } from 'es-toolkit/compat'; const fn = (a, b, c, d) => [a, b, c, d]; // Rearrange only the first two arguments const rearranged = rearg(fn, 1, 0); rearranged('first', 'second', 'third', 'fourth'); // Returns: ['second', 'first', 'third', 'fourth'] ``` Non-existent indices are treated as `undefined`. ```typescript import { rearg } from 'es-toolkit/compat'; const fn = (a, b, c) => [a, b, c]; // Include non-existent index 5 const rearranged = rearg(fn, 5, 1, 0); rearranged('a', 'b', 'c'); // Returns: [undefined, 'b', 'a'] ``` Nested arrays are also flattened and processed. ```typescript import { rearg } from 'es-toolkit/compat'; const fn = (a, b, c, d) => [a, b, c, d]; // Nested array indices const rearranged = rearg(fn, [1, [2, 0]], 3); rearranged('a', 'b', 'c', 'd'); // Returns: ['b', 'c', 'a', 'd'] ``` #### Parameters * `func` (`(...args: any[]) => any`): The function whose arguments will be rearranged. * `...indices` (`Array`): The indices of the arguments to rearrange. Nested arrays are also supported. #### Returns (`(...args: any[]) => any`): Returns a new function with rearranged arguments. --- --- url: /reference/map/reduce.md --- # reduce (for `Map`s) Reduces a Map to a single value by iterating through its entries and applying a callback function. ```typescript const result = reduce(map, callback, initialValue); ``` ::: info This function is available exclusively from `es-toolkit/map` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `reduce(map, callback, initialValue?)` Use `reduce` when you want to transform a Map into a single value by accumulating results from each entry. Provide a callback function that processes each entry and updates the accumulator. If an initial value is provided, it is used as the starting accumulator value. If no initial value is provided and the Map is empty, a TypeError is thrown. ```typescript import { reduce } from 'es-toolkit/map'; const map = new Map([ ['a', 1], ['b', 2], ['c', 3], ]); const result = reduce(map, (acc, value) => acc + value, 0); // Result: 6 ``` You can reduce a Map in various ways. ```typescript import { reduce } from 'es-toolkit/map'; // Sum with initial value const scores = new Map([ ['alice', 95], ['bob', 87], ['charlie', 92], ]); const totalScore = reduce(scores, (acc, score) => acc + score, 0); // Result: 274 // Without initial value (uses first value) const numbers = new Map([ ['a', 10], ['b', 20], ]); const sum = reduce(numbers, (acc, value) => acc + value); // Result: 30 (starts with first value 10) // Build an object from Map const settings = new Map([ ['theme', 'dark'], ['lang', 'en'], ['notifications', true], ]); const config = reduce(settings, (acc, value, key) => ({ ...acc, [key]: value }), {} as Record); // Result: { theme: 'dark', lang: 'en', notifications: true } ``` #### Parameters * `map` (`Map`): The Map to reduce. * `callback` (`(accumulator: A, value: V, key: K, map: Map) => A`): A function that processes each entry and updates the accumulator. * `initialValue` (`A`, optional): The initial value for the accumulator. If not provided, the first value in the Map is used. #### Returns (`A`): The final accumulated value. #### Throws (`TypeError`): If the Map is empty and no initial value is provided. --- --- url: /reference/set/reduce.md --- # reduce (for `Set`s) Reduces a Set to a single value by iterating through its elements and applying a callback function. ```typescript const result = reduce(set, callback, initialValue); ``` ::: info This function is available exclusively from `es-toolkit/set` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `reduce(set, callback, initialValue?)` Use `reduce` when you want to transform a Set into a single value by accumulating results from each element. Provide a callback function that processes each element and updates the accumulator. If an initial value is provided, it is used as the starting accumulator value. If no initial value is provided and the Set is empty, a TypeError is thrown. ```typescript import { reduce } from 'es-toolkit/set'; const set = new Set([1, 2, 3]); const result = reduce(set, (acc, value) => acc + value, 0); // Result: 6 ``` You can reduce a Set in various ways. ```typescript import { reduce } from 'es-toolkit/set'; // Sum with initial value const numbers = new Set([10, 20, 30, 40]); const total = reduce(numbers, (acc, num) => acc + num, 0); // Result: 100 // Without initial value (uses first element) const values = new Set([5, 10]); const sum = reduce(values, (acc, value) => acc + value); // Result: 15 (starts with first value 5) // Build an array from Set const uniqueNames = new Set(['Alice', 'Bob', 'Charlie']); const nameList = reduce(uniqueNames, (acc, name) => [...acc, name.toUpperCase()], [] as string[]); // Result: ['ALICE', 'BOB', 'CHARLIE'] ``` #### Parameters * `set` (`Set`): The Set to reduce. * `callback` (`(accumulator: A, value: T, value2: T, set: Set) => A`): A function that processes each element and updates the accumulator. * `initialValue` (`A`, optional): The initial value for the accumulator. If not provided, the first element in the Set is used. #### Returns (`A`): The final accumulated value. #### Throws (`TypeError`): If the Set is empty and no initial value is provided. --- --- url: /reference/compat/array/reduce.md --- # reduce (Lodash Compatibility) ::: warning Use `Array.prototype.reduce` or `Object.values` with `reduce` This `reduce` function operates slowly due to complex type handling and support for various input formats. Instead, use the faster and more modern `Array.prototype.reduce` method, or for objects, use it together with `Object.values`. ::: Reduces an array or object to a single value. ```typescript const result = reduce(collection, iteratee, initialValue); ``` ## Usage ### `reduce(collection, iteratee, initialValue)` Iterates through all elements of an array or object to calculate an accumulated value. If an initial value is provided, it starts with that value; otherwise, it starts with the first element. ```typescript import { reduce } from 'es-toolkit/compat'; // Calculate sum of array const numbers = [1, 2, 3, 4]; const sum = reduce(numbers, (acc, value) => acc + value, 0); console.log(sum); // 10 // Calculate sum of object values const scores = { math: 95, english: 87, science: 92 }; const totalScore = reduce(scores, (acc, value) => acc + value, 0); console.log(totalScore); // 274 ``` If no initial value is provided, the first element becomes the initial value and iteration starts from the second element. ```typescript import { reduce } from 'es-toolkit/compat'; const numbers = [1, 2, 3, 4]; const sum = reduce(numbers, (acc, value) => acc + value); console.log(sum); // 10 (1 + 2 + 3 + 4) // Empty array returns undefined const empty = []; const result = reduce(empty, (acc, value) => acc + value); console.log(result); // undefined ``` #### Parameters * `collection` (`T[] | ArrayLike | Record | null | undefined`): The array or object to iterate over. * `iteratee` (`(accumulator: any, value: any, index: PropertyKey, collection: any) => any`): The function to call for each element. It receives the accumulated value, current value, index/key, and the original array/object. * `initialValue` (`any`, optional): The initial value for the accumulator. If not provided, the first element becomes the initial value. #### Returns (`any`): Returns the final accumulated value after processing all elements. --- --- url: /reference/array/reduceAsync.md --- # reduceAsync Reduces an array to a single value using an async reducer function. ```typescript const result = await reduceAsync(array, reducer, initialValue); ``` ## Reference ### `reduceAsync(array, reducer, initialValue)` Use `reduceAsync` to reduce an array to a single value by processing each element sequentially. The reducer function is applied sequentially to each element from left to right, passing the accumulated result from one call to the next. ```typescript import { reduceAsync } from 'es-toolkit/array'; // Fetch async values for each number and sum them. const numbers = [1, 2, 3, 4, 5]; const sum = await reduceAsync(numbers, async (acc, n) => acc + (await fetchValue(n)), 0); // Returns: Sum of all fetched values // Transform array to object. const users = [{ id: 1 }, { id: 2 }, { id: 3 }]; const userMap = await reduceAsync( users, async (acc, user) => { const details = await fetchUserDetails(user.id); acc[user.id] = details; return acc; }, {} as Record ); // Returns: { 1: {...}, 2: {...}, 3: {...} } ``` Unlike other async array methods, `reduceAsync` must process elements sequentially and does not support concurrent execution, because the result from the previous step is needed for the next step. #### Parameters * `array` (`readonly T[]`): The array to reduce. * `reducer` (`(accumulator: U, currentValue: T, currentIndex: number, array: readonly T[]) => Promise`): An async function that processes each element. It receives the accumulated value and current value, and returns the new accumulated value. * `initialValue` (`U`): The initial value of the accumulator. #### Returns (`Promise`): A promise that resolves to the final accumulated value. *** ### `reduceAsync(array, reducer)` When reducing an array without an initial value, the first element is used as the initial value and the reducer function is applied starting from the second element. ```typescript import { reduceAsync } from 'es-toolkit/array'; // Calculate sum without initial value. const numbers = [1, 2, 3, 4, 5]; const sum = await reduceAsync(numbers, async (acc, n) => acc + n); // Returns: 15 (1 + 2 + 3 + 4 + 5) // Empty array returns undefined. const emptyArray: number[] = []; const result = await reduceAsync(emptyArray, async (acc, n) => acc + n); // Returns: undefined ``` Calling `reduceAsync` on an empty array without an initial value returns `undefined`. #### Parameters * `array` (`readonly T[]`): The array to reduce. * `reducer` (`(accumulator: T, currentValue: T, currentIndex: number, array: readonly T[]) => Promise`): An async function that processes each element. It receives the accumulated value and current value, and returns the new accumulated value. #### Returns (`Promise`): A promise that resolves to the final accumulated value. Returns `undefined` if the array is empty. --- --- url: /reference/compat/array/reduceRight.md --- # reduceRight (Lodash Compatibility) ::: warning Use `Array.prototype.reduceRight` or `Object.values` with `reduceRight` This `reduceRight` function operates slowly due to complex type handling and support for various input formats. Instead, use the faster and more modern `Array.prototype.reduceRight` method, or for objects, use `reduceRight` together with `Object.values`. ::: Reduces an array or object to a single value by iterating from right to left. ```typescript const result = reduceRight(collection, iteratee, initialValue); ``` ## Usage ### `reduceRight(collection, iteratee, initialValue)` Iterates through all elements of an array or object from right to left to calculate an accumulated value. If an initial value is provided, it starts with that value; otherwise, it starts with the last element. ```typescript import { reduceRight } from 'es-toolkit/compat'; // Concatenate array to string (from right) const letters = ['a', 'b', 'c', 'd']; const result = reduceRight(letters, (acc, value) => acc + value, ''); console.log(result); // 'dcba' // Multiply object values (reverse of key order) const numbers = { x: 2, y: 3, z: 4 }; const product = reduceRight(numbers, (acc, value) => acc * value, 1); console.log(product); // 24 (1 * 4 * 3 * 2) ``` If no initial value is provided, the last element becomes the initial value and iteration starts from the second to last element. ```typescript import { reduceRight } from 'es-toolkit/compat'; const numbers = [1, 2, 3, 4]; const sum = reduceRight(numbers, (acc, value) => acc + value); console.log(sum); // 10 (4 + 3 + 2 + 1) // Empty array returns undefined const empty = []; const result = reduceRight(empty, (acc, value) => acc + value); console.log(result); // undefined ``` #### Parameters * `collection` (`T[] | ArrayLike | Record | null | undefined`): The array or object to iterate over. * `iteratee` (`(accumulator: any, value: any, index: PropertyKey, collection: any) => any`): The function to call for each element. It receives the accumulated value, current value, index/key, and the original array/object. * `initialValue` (`any`, optional): The initial value for the accumulator. If not provided, the last element becomes the initial value. #### Returns (`any`): Returns the final accumulated value after processing all elements. --- --- url: /reference/compat/array/reject.md --- # reject (Lodash Compatibility) ::: warning Use `Array.filter()` This `reject` function is implemented with complexity to support various predicate forms for compatibility with Lodash. For simple function predicates, `Array.filter()` works more simply and faster. Instead, use the faster and more modern `Array.filter()`. For example, `reject(arr, func)` can be replaced with `arr.filter(item => !func(item))`. ::: Iterates over a collection and returns a new array of elements that do not match the predicate function. ```typescript const filtered = reject(collection, predicate); ``` ## Usage ### `reject(collection, predicate)` Returns a new array containing only elements from an array, object, or string that do not match the given condition. It performs the opposite operation of `filter`. ```typescript import { reject } from 'es-toolkit/compat'; // Filter out even numbers reject([1, 2, 3, 4, 5], n => n % 2 === 0); // => [1, 3, 5] // Filter out objects that have a specific property reject([{ a: 1 }, { a: 2 }, { b: 1 }], 'a'); // => [{ b: 1 }] // Filter out objects that have a specific property value reject([{ a: 1 }, { a: 2 }, { a: 3 }], { a: 2 }); // => [{ a: 1 }, { a: 3 }] // Filter out specific characters from a string reject('abc', char => char === 'b'); // => ['a', 'c'] ``` This function supports various forms of predicates. ```typescript import { reject } from 'es-toolkit/compat'; // Condition using a function reject(users, user => user.age < 18); // Partial matching of objects reject(users, { active: false }); // Property-value array reject(users, ['status', 'pending']); // Check truthy value by property name reject(users, 'premium'); ``` #### Parameters * `collection` (`ArrayLike | Record | string | null | undefined`): The collection to iterate over. * `predicate` (`((item: T, index: number, collection: any) => unknown) | Partial | [keyof T, unknown] | PropertyKey`, optional): The condition to execute for each element. Defaults to `identity`. #### Returns (`T[]`): Returns a new array composed of elements that do not match the predicate condition. --- --- url: /reference/array/remove.md --- # remove Removes elements from an array based on a condition function and returns the removed elements in a new array. It modifies the original array directly. ```typescript const removed = remove(arr, shouldRemoveElement); ``` ## Usage ### `remove(arr, shouldRemoveElement)` Use `remove` when you want to remove elements that meet a specific condition from an array and check what elements were removed. This function modifies the original array while returning the removed elements in a separate array. If you want to keep the original array, use the `filter` method. ```typescript import { remove } from 'es-toolkit/array'; // Remove even numbers. const numbers = [1, 2, 3, 4, 5]; const removedNumbers = remove(numbers, value => value % 2 === 0); console.log(numbers); // [1, 3, 5] (original array is modified) console.log(removedNumbers); // [2, 4] (removed elements) // Remove objects that meet a specific condition. const users = [ { name: 'john', age: 25 }, { name: 'jane', age: 17 }, { name: 'bob', age: 30 }, ]; const minors = remove(users, user => user.age < 18); console.log(users); // [{ name: 'john', age: 25 }, { name: 'bob', age: 30 }] console.log(minors); // [{ name: 'jane', age: 17 }] ``` You can also use index and original array information. ```typescript import { remove } from 'es-toolkit/array'; // Remove elements based on index. const items = ['a', 'b', 'c', 'd', 'e']; const removedAtEvenIndex = remove(items, (value, index) => index % 2 === 0); console.log(items); // ['b', 'd'] console.log(removedAtEvenIndex); // ['a', 'c', 'e'] ``` #### Parameters * `arr` (`T[]`): The array to modify. * `shouldRemoveElement` (`(value: T, index: number, array: T[]) => boolean`): A condition function called for each element. Elements for which it returns `true` are removed. * `value`: The element currently being processed. * `index`: The index of the current element. * `array`: The original array. #### Returns (`T[]`): Returns a new array containing the removed elements. --- --- url: /reference/compat/array/remove.md --- # remove (Lodash Compatibility) ::: warning Use `remove` from `es-toolkit` This `remove` function is implemented in a complex way to support various forms of predicates for Lodash compatibility. The `remove` function in the main library only supports simple function predicates, so it operates faster. Instead, use the faster and more modern [remove](../../array/remove.md) from `es-toolkit`. ::: Removes elements that match a condition from an array and returns the removed elements. ```typescript const removedElements = remove(array, predicate); ``` ## Usage ### `remove(array, predicate)` Iterates through the array and removes elements that match the given condition from the original array, returning the removed elements as a new array. Note that the original array is directly modified. ```typescript import { remove } from 'es-toolkit/compat'; // Remove with function condition const numbers = [1, 2, 3, 4, 5]; const evens = remove(numbers, n => n % 2 === 0); console.log(numbers); // => [1, 3, 5] console.log(evens); // => [2, 4] // Remove with partial object matching const objects = [{ a: 1 }, { a: 2 }, { a: 3 }]; const removed = remove(objects, { a: 1 }); console.log(objects); // => [{ a: 2 }, { a: 3 }] console.log(removed); // => [{ a: 1 }] // Remove with property-value pair const items = [{ name: 'apple' }, { name: 'banana' }, { name: 'cherry' }]; const cherries = remove(items, ['name', 'cherry']); console.log(items); // => [{ name: 'apple' }, { name: 'banana' }] console.log(cherries); // => [{ name: 'cherry' }] ``` This function supports various forms of predicates. ```typescript import { remove } from 'es-toolkit/compat'; // Function condition remove(users, user => user.active === false); // Partial object matching remove(users, { status: 'inactive' }); // Property-value array remove(users, ['type', 'guest']); // Check truthy value by property name remove(users, 'isDeleted'); ``` #### Parameters * `array` (`ArrayLike`): The array to modify. * `predicate` (`((value: T, index: number, array: ArrayLike) => boolean) | Partial | [keyof T, unknown] | keyof T`, optional): The condition to execute for each element. Default is `identity`. #### Returns (`T[]`): Returns a new array consisting of elements that were removed because they matched the condition. --- --- url: /reference/compat/string/repeat.md --- # repeat (Lodash compatibility) ::: warning Use JavaScript's `String.prototype.repeat` This `repeat` function operates slower due to handling non-string values and integer conversion. Instead, use the faster and more modern JavaScript's `String.prototype.repeat`. ::: Repeats a string a specified number of times. ```typescript const repeated = repeat(str, n); ``` ## Usage ### `repeat(str, n?)` Use `repeat` when you want to repeat a string multiple times to create a new string. If the repeat count is less than 1, it returns an empty string. ```typescript import { repeat } from 'es-toolkit/compat'; // Repeat string repeat('abc', 2); // Returns: 'abcabc' repeat('hello', 3); // Returns: 'hellohellohello' // Repeating 0 times returns empty string repeat('abc', 0); // Returns: '' ``` `null` or `undefined` are treated as empty strings. ```typescript import { repeat } from 'es-toolkit/compat'; repeat(null, 3); // Returns: '' repeat(undefined, 2); // Returns: '' ``` If you don't specify the repeat count, it repeats once. ```typescript import { repeat } from 'es-toolkit/compat'; repeat('abc'); // Returns: 'abc' ``` #### Parameters * `str` (`string`, optional): The string to repeat. * `n` (`number`, optional): The number of times to repeat. Defaults to `1`. #### Returns (`string`): Returns the string repeated the specified number of times. --- --- url: /reference/compat/string/replace.md --- # replace (Lodash compatibility) ::: warning Use JavaScript's `String.prototype.replace` This `replace` function operates slower due to handling non-string values. Instead, use the faster and more modern JavaScript's `String.prototype.replace`. ::: Replaces matching patterns in a string with another string. ```typescript const replaced = replace(target, pattern, replacement); ``` ## Usage ### `replace(target, pattern, replacement)` Use `replace` when you want to find a specific pattern in a string and replace it with another string. You can use a string or regular expression pattern, and the replacement can be specified as a string or function. ```typescript import { replace } from 'es-toolkit/compat'; // Replace with string pattern replace('abcde', 'de', '123'); // Returns: 'abc123' // Replace with regular expression pattern replace('abcde', /[bd]/g, '-'); // Returns: 'a-c-e' ``` You can also use a function to dynamically decide the replacement. ```typescript import { replace } from 'es-toolkit/compat'; // Decide replacement content with function replace('abcde', 'de', match => match.toUpperCase()); // Returns: 'abcDE' // Combination of regular expression and function replace('abcde', /[bd]/g, match => match.toUpperCase()); // Returns: 'aBcDe' ``` `null` or `undefined` targets are treated as empty strings. ```typescript import { replace } from 'es-toolkit/compat'; replace(null, 'test', 'replaced'); // Returns: '' replace(undefined, /test/g, 'replaced'); // Returns: '' ``` #### Parameters * `target` (`string`): The target string to replace. * `pattern` (`string | RegExp`): The pattern to find. * `replacement` (`string | Function`): The replacement content. If a function, it receives the matched string and should return the replacement string. #### Returns (`string`): Returns a new string with the pattern replaced. --- --- url: /reference/function/rest.md --- # rest Creates a new function that bundles parameters from a specific index into an array and passes them to the function. ```typescript const restFunc = rest(func, startIndex); ``` ## Usage ### `rest(func, startIndex?)` Use `rest` when you want to bundle the remaining parameters into an array. Parameters before the specific index are passed individually, and parameters after are bundled into an array. This is useful for creating functions that accept variable parameters or when you want to change how existing functions handle parameters. ```typescript import { rest } from 'es-toolkit/function'; // Basic usage (bundle from the last parameter into an array) function sum(a: number, b: number, numbers: number[]) { return a + b + numbers.reduce((sum, n) => sum + n, 0); } const restSum = rest(sum); // startIndex defaults to func.length - 1 (2) console.log(restSum(1, 2, 3, 4, 5)); // 1 + 2 + (3 + 4 + 5) = 15 // The sum function is called with [1, 2, [3, 4, 5]] // Bundle into an array starting from a different index function logMessage(level: string, messages: string[]) { console.log(`[${level}] ${messages.join(' ')}`); } const restLog = rest(logMessage, 1); // Bundle from index 1 restLog('INFO', 'Application', 'started', 'successfully'); // Called as logMessage('INFO', ['Application', 'started', 'successfully']) // Practical example: first parameter individual, rest as an array function format(template: string, values: any[]) { return values.reduce((result, value, index) => { return result.replace(`{${index}}`, value); }, template); } const restFormat = rest(format, 1); console.log(restFormat('Hello {0}, welcome to {1}!', 'John', 'our site')); // 'Hello John, welcome to our site!' ``` It also handles cases where there are fewer parameters. ```typescript import { rest } from 'es-toolkit/function'; function greet(greeting: string, name: string, extras: string[]) { const extraText = extras.length > 0 ? ` ${extras.join(' ')}` : ''; return `${greeting} ${name}!${extraText}`; } const restGreet = rest(greet); console.log(restGreet('Hello', 'Alice', 'Have a great day!')); // 'Hello Alice! Have a great day!' console.log(restGreet('Hi', 'Bob')); // 'Hi Bob!' (extras becomes an empty array) console.log(restGreet('Hey')); // 'Hey undefined!' (name is undefined, extras is an empty array) ``` #### Parameters * `func` (`F`): The function to change parameter handling. * `startIndex` (`number`, optional): The index from which to start bundling into an array. Defaults to `func.length - 1`, bundling from the last parameter. #### Returns (`(...args: any[]) => ReturnType`): Returns a new function that bundles parameters from a specific index into an array and passes them to the original function. --- --- url: /reference/compat/function/rest.md --- # rest (Lodash Compatibility) ::: warning Use `rest` from `es-toolkit` instead This `rest` function may have reduced performance due to additional logic such as default value handling and index validation. Use faster, more modern [rest](../../function/rest.md) from `es-toolkit` instead. ::: Creates a function that groups the remaining arguments from a specified index into an array. ```typescript const restFunc = rest(func, start); ``` ## Usage ### `rest(func, start)` Use `rest` when you want to transform function arguments by grouping the remaining arguments from a specified index into an array. It's useful for creating variadic functions. ```typescript import { rest } from 'es-toolkit/compat'; // Basic usage - group the last arguments into an array function logMessage(level, message, ...details) { console.log(`[${level}] ${message}`, details); } const restLogger = rest(logMessage, 2); restLogger('ERROR', 'Error occurred', 'Detail 1', 'Detail 2'); // Internally calls logMessage('ERROR', 'Error occurred', [['Detail 1', 'Detail 2']]) // Different index example function process(action, target, ...args) { return { action, target, args }; } const restProcess = rest(process, 1); restProcess('update', 'user', 'name', 'John', 'age', 25); // { action: 'update', target: ['user', 'name', 'John', 'age', 25], args: [] } ``` Use this when you want the last arguments of a function to be received as an array. In modern JavaScript, it's more common to use rest parameter syntax (`...args`). #### Parameters * `func` (`Function`): The function to transform. * `start` (`number`, optional): The index from which to start grouping arguments into an array. Default is `func.length - 1`. #### Returns (`Function`): Returns a new function that groups the remaining arguments from the specified index into an array. --- --- url: /reference/compat/object/result.md --- # result (Lodash Compatibility) ::: warning Use the `get` function or optional chaining This `result` function performs slowly due to complex path handling and function invocation logic. Instead, use the faster and more modern `get` function or optional chaining (`?.`). ::: Retrieves a value from a path in an object, but if it encounters a function, it calls it and returns the result. ```typescript const result = result(obj, path, defaultValue); ``` ## Usage ### `result(object, path, defaultValue)` Use `result` when you want to retrieve a value from a path in an object and automatically call any functions along the path. It's similar to the `get` function, but it executes functions it encounters and returns the result if the final value is also a function. ```typescript import { result } from 'es-toolkit/compat'; // Basic usage (regular values) const obj = { a: { b: { c: 3 } } }; const value = result(obj, 'a.b.c'); // Result: 3 // Automatic function invocation const objWithFunc = { compute: () => ({ value: 42 }), getValue: function () { return this.compute().value; }, }; const computed = result(objWithFunc, 'getValue'); // Result: 42 (getValue function is called) // Function invocation along the path const nested = { data: () => ({ user: { getName: () => 'John' } }), }; const name = result(nested, 'data.user.getName'); // Result: 'John' (both data() and getName() are called) // Using default value const incomplete = { a: { b: null } }; const withDefault = result(incomplete, 'a.b.c', 'default value'); // Result: 'default value' // When default value is a function const withFuncDefault = result(incomplete, 'a.b.c', () => 'computed default'); // Result: 'computed default' (default value function is called) // Using array path const arrayPath = result(objWithFunc, ['getValue']); // Result: 42 // Dynamic default value const dynamic = result(incomplete, 'missing.path', function () { return `Generated at ${new Date().toISOString()}`; }); // Result: string with current time ``` The `this` context is preserved when calling functions. ```typescript import { result } from 'es-toolkit/compat'; const calculator = { multiplier: 2, compute: function () { return 10 * this.multiplier; }, }; const calculatedValue = result(calculator, 'compute'); // Result: 20 (this.multiplier is correctly referenced) ``` #### Parameters * `object` (`any`): The object to query. * `path` (`PropertyPath`): The path of the property to get. Can be a string, array, or array of keys. * `defaultValue` (`R | ((...args: any[]) => R)`, optional): The default value to return if the value is `undefined`. If it's a function, it calls and returns the result. #### Returns (`R`): Returns the resolved value. Functions along the path are called, and if the final value is also a function, it returns the result of calling it. --- --- url: /reference/function/retry.md --- # retry Retries a Promise-returning function until it succeeds. ```typescript const result = await retry(asyncFunc, options); ``` ## Usage ### `retry(func, options?)` Use `retry` when you want to automatically retry an asynchronous function that fails. This is useful for operations that can temporarily fail, such as API calls or network requests. You can configure the number of retries, retry interval, and cancellation signal. The retry interval can be a fixed value or a function that dynamically calculates based on the retry count. ```typescript import { retry } from 'es-toolkit/function'; // Basic usage (infinite retries) const data1 = await retry(async () => { const response = await fetch('/api/data'); if (!response.ok) throw new Error('Failed to fetch'); return response.json(); }); // Limit retry count const data2 = await retry(async () => { return await fetchData(); }, 3); // Set retry interval (100ms) const data3 = await retry( async () => { return await fetchData(); }, { retries: 3, delay: 100, } ); // Dynamic retry interval (exponential backoff) const data4 = await retry( async () => { return await fetchData(); }, { retries: 5, delay: attempts => Math.min(100 * Math.pow(2, attempts), 5000), } ); ``` You can use `shouldRetry` option when you want to retry only on specific errors. ```typescript import { retry } from 'es-toolkit/function'; class NetworkError extends Error { constructor(public status: number) { super(`Network error: ${status}`); } } // Retry only on 500+ errors const data5 = await retry( async () => { const response = await fetch('/api/data'); if (!response.ok) { throw new NetworkError(response.status); } return response.json(); }, { retries: 3, shouldRetry: (error, attempt) => error instanceof NetworkError && error.status >= 500, } ); ``` You can also cancel retries using AbortSignal. ```typescript import { retry } from 'es-toolkit/function'; const controller = new AbortController(); // Cancel retry after 5 seconds setTimeout(() => controller.abort(), 5000); try { const data = await retry( async () => { return await fetchData(); }, { retries: 10, delay: 1000, signal: controller.signal, } ); console.log(data); } catch (error) { console.log('Retry was canceled or failed:', error); } ``` #### Parameters * `func` (`() => Promise`): The asynchronous function to retry. * `options` (`number | RetryOptions`, optional): The number of retries or options object. * `retries` (`number`, optional): The number of times to retry. Defaults to `Infinity` for infinite retries. * `delay` (`number | (attempts: number) => number`, optional): The retry interval (in milliseconds). Can be a number or a function. Defaults to `0`. * `signal` (`AbortSignal`, optional): A signal that can cancel retries. * `shouldRetry` (`(error: unknown, attempt: number) => boolean`, optional): A function that determines whether to retry. If it returns `false`, the error is thrown immediately. * `error`: The error object that occurred. * `attempt`: The current attempt count (starting from 0). #### Returns (`Promise`): Returns the result of the successfully executed function. #### Throws Throws the last error when the retry count is exceeded or when canceled by AbortSignal. --- --- url: /reference/compat/array/reverse.md --- # reverse (Lodash Compatibility) ::: warning Use `Array.prototype.reverse()` This `reverse` function includes `null` and `undefined` handling for Lodash compatibility. If you only need simple array reversal, the native JavaScript `Array.prototype.reverse()` method is more intuitive and faster. Instead, use the faster and more modern `Array.prototype.reverse()`. ::: Reverses array elements in place. ```typescript const reversed = reverse(array); ``` ## Usage ### `reverse(array)` Reverses the order of the array so that the first element becomes the last and the last element becomes the first. It directly modifies the original array and returns the modified array. ```typescript import { reverse } from 'es-toolkit/compat'; // Reverse a number array const numbers = [1, 2, 3, 4, 5]; const reversed = reverse(numbers); console.log(numbers); // => [5, 4, 3, 2, 1] console.log(reversed); // => [5, 4, 3, 2, 1] // Reverse a string array const words = ['apple', 'banana', 'cherry']; reverse(words); console.log(words); // => ['cherry', 'banana', 'apple'] // Empty arrays or null/undefined are returned as is reverse([]); // => [] reverse(null); // => null reverse(undefined); // => undefined ``` Note that this function directly modifies the original array. ```typescript import { reverse } from 'es-toolkit/compat'; const original = [1, 2, 3]; const result = reverse(original); console.log(original === result); // => true (same array object) console.log(original); // => [3, 2, 1] (original is modified) ``` #### Parameters * `array` (`T[] | null | undefined`): The array to reverse. If `null` or `undefined`, it is returned as is. #### Returns (`T[] | null | undefined`): Returns the reversed array. If the input is `null` or `undefined`, that value is returned as is. --- --- url: /reference/string/reverseString.md --- # reverseString Reverses a string. ```typescript const reversed = reverseString(value); ``` ## Usage ### `reverseString(value)` Use `reverseString` when you want to reverse the order of characters in a string. It correctly handles Unicode characters and emojis. ```typescript import { reverseString } from 'es-toolkit/string'; // Basic string reversal reverseString('hello'); // 'olleh' reverseString('world'); // 'dlrow' // Mixed case strings reverseString('PascalCase'); // 'esaClacsaP' // Strings with spaces reverseString('hello world'); // 'dlrow olleh' ``` It accurately handles emojis and special characters. ```typescript import { reverseString } from 'es-toolkit/string'; // Strings with emojis reverseString('foo 😄 bar'); // 'rab 😄 oof' reverseString('안녕하세요'); // '요세하녕안' // Numbers and special characters reverseString('12345'); // '54321' reverseString('a-b-c'); // 'c-b-a' ``` #### Parameters * `value` (`string`): The string to reverse. #### Returns (`string`): Returns a new string with the characters in reverse order. ## Demo ::: sandpack ```ts index.ts import { reverseString } from 'es-toolkit'; console.log(reverseString('hello')); ``` ::: --- --- url: /reference/math/round.md --- # round Rounds a number to a specified number of decimal places. ```typescript const rounded = round(value, precision?); ``` ## Usage ### `round(value, precision?)` Use `round` when you want to round a number to a specific number of decimal places. It's a mathematical function for precise calculations. ```typescript import { round } from 'es-toolkit/math'; // Default - rounds to integer. const num1 = round(1.2345); console.log(num1); // 1 // Round to 2 decimal places. const num2 = round(1.2345, 2); console.log(num2); // 1.23 // Round to 3 decimal places. const num3 = round(1.2387, 3); console.log(num3); // 1.239 // Can also round negative numbers. const num4 = round(-1.2345, 2); console.log(num4); // -1.23 // Handles large numbers too. const num5 = round(123.456789, 4); console.log(num5); // 123.4568 ``` Useful in price calculations and statistics. ```typescript import { round } from 'es-toolkit/math'; // Price calculation (to 2 decimal places) const price = 19.999; const finalPrice = round(price, 2); console.log(finalPrice); // 20.00 // Percentage calculation (to 1 decimal place) const percentage = 66.66666; const displayPercentage = round(percentage, 1); console.log(displayPercentage); // 66.7 // Rating calculation (to 1 decimal place) const rating = 4.267; const displayRating = round(rating, 1); console.log(displayRating); // 4.3 ``` Round in calculations where accuracy matters. ```typescript import { round } from 'es-toolkit/math'; // Clean up math calculation results const result = Math.PI * 2; const cleanResult = round(result, 5); console.log(cleanResult); // 6.28318 // Round measurement values const measurement = 15.789123; const rounded = round(measurement, 3); console.log(rounded); // 15.789 ``` Invalid precision values throw an error. ```typescript import { round } from 'es-toolkit/math'; // Error occurs if precision is not an integer. try { round(1.23, 2.5); } catch (error) { console.error(error.message); // 'Precision must be an integer.' } ``` #### Parameters * `value` (`number`): The number to round. * `precision` (`number`, optional): The number of decimal places. Must be an integer. Defaults to `0`. #### Returns (`number`): Returns the number rounded to the specified precision. #### Throws * Throws an error if `precision` is not an integer. --- --- url: /reference/compat/math/round.md --- # round (Lodash Compatibility) ::: warning Use `Math.round()` This `round` function works slowly due to precision handling. Use `Math.round()` instead or calculate to the desired decimal places. ::: Rounds a number. ```typescript const rounded = round(number, precision); ``` ## Usage ### `round(number, precision?)` Rounds a number to the specified decimal places. ```typescript import { round } from 'es-toolkit/compat'; // Basic rounding (0 decimal places) round(4.006); // Returns: 4 round(4.6); // Returns: 5 // Specify decimal places round(4.006, 2); // Returns: 4.01 round(4.123456, 3); // Returns: 4.123 ``` Negative precision is also possible. ```typescript import { round } from 'es-toolkit/compat'; // Round to tens place round(4060, -2); // Returns: 4100 round(1234, -1); // Returns: 1230 round(1234, -3); // Returns: 1000 ``` Handles negative numbers as well. ```typescript import { round } from 'es-toolkit/compat'; round(-4.006); // Returns: -4 round(-4.006, 2); // Returns: -4.01 round(-1234, -2); // Returns: -1200 ``` #### Parameters * `number` (`number`): The number to round. * `precision` (`number`, optional): The number of decimal places to round to. Default is `0`. #### Returns (`number`): Returns the rounded number. --- --- url: /reference/array/sample.md --- # sample Returns a randomly selected element from an array. ```typescript const randomElement = sample(arr); ``` ## Usage ### `sample(arr)` Use `sample` when you want to randomly select one element from an array. It's useful for selecting random items in games, randomly fetching test data, or conducting draws. ```typescript import { sample } from 'es-toolkit/array'; // Randomly select one from a number array. const numbers = [1, 2, 3, 4, 5]; const randomNumber = sample(numbers); // Returns: one of 1, 2, 3, 4, 5 // Randomly select one from a string array. const fruits = ['apple', 'banana', 'cherry', 'date']; const randomFruit = sample(fruits); // Returns: one of 'apple', 'banana', 'cherry', 'date' // Randomly select one from an object array. const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 35 }, ]; const randomUser = sample(users); // Returns: one of the three users randomly ``` It can also be used with various types of arrays. ```typescript import { sample } from 'es-toolkit/array'; // Boolean array const booleans = [true, false]; const randomBoolean = sample(booleans); // Returns: true or false // Mixed type array const mixed = [1, 'hello', { key: 'value' }, [1, 2, 3]]; const randomItem = sample(mixed); // Returns: any of the elements in the array ``` #### Parameters * `arr` (`readonly T[]`): The array from which to randomly select an element. #### Returns (`T`): A randomly selected element from the array. --- --- url: /reference/compat/array/sample.md --- # sample (Lodash Compatibility) ::: warning Use `es-toolkit`'s [sample](../../array/sample.md) This `sample` function operates slowly due to `null` or `undefined` handling, object value processing, etc. Instead, use the faster and more modern `es-toolkit`'s [sample](../../array/sample.md). ::: Gets a random element from an array or object. ```typescript const randomItem = sample(collection); ``` ## Usage ### `sample(collection)` Use `sample` to select a random element from an array or object. For arrays, it returns a random element, and for objects, it returns a random value. ```typescript import { sample } from 'es-toolkit/compat'; // Get a random element from an array sample([1, 2, 3, 4, 5]); // Returns a random number between 1 and 5 // Get a random value from an object sample({ a: 1, b: 2, c: 3 }); // Returns a random value among 1, 2, 3 // Handles strings as well sample('hello'); // Returns a random character among 'h', 'e', 'l', 'l', 'o' ``` `null` or `undefined` returns `undefined`. ```typescript import { sample } from 'es-toolkit/compat'; sample(null); // undefined sample(undefined); // undefined ``` #### Parameters * `collection` (`ArrayLike | Record | null | undefined`): The array or object to sample from. #### Returns (`T | string | undefined`): Returns a randomly selected element from the array or object. Returns `undefined` if the collection is empty or `null`, `undefined`. --- --- url: /reference/array/sampleSize.md --- # sampleSize Returns a new array of randomly selected elements with the specified size. ```typescript const sampled = sampleSize(array, size); ``` ## Usage ### `sampleSize(array, size)` Use `sampleSize` when you want to randomly sample multiple elements from an array. It uses Floyd's algorithm to efficiently generate random samples without duplicates. It's useful for extracting samples in surveys or randomly selecting multiple items in games. ```typescript import { sampleSize } from 'es-toolkit/array'; // Randomly select 3 from a number array. const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const randomNumbers = sampleSize(numbers, 3); // Returns: [2, 7, 9] (example, actually random) // Randomly select 2 from a string array. const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']; const randomFruits = sampleSize(fruits, 2); // Returns: ['cherry', 'apple'] (example, actually random) ``` You can sample with various sizes. ```typescript import { sampleSize } from 'es-toolkit/array'; const items = ['a', 'b', 'c', 'd', 'e']; // Select 1 element const single = sampleSize(items, 1); // Returns: ['c'] (example) // Select same as entire array size (shuffle effect) const all = sampleSize(items, 5); // Returns: ['b', 'd', 'a', 'e', 'c'] (example) // Select empty array const none = sampleSize(items, 0); // Returns: [] ``` #### Parameters * `array` (`readonly T[]`): The array to sample from. * `size` (`number`): The number of elements to select. #### Returns (`T[]`): Returns a new array consisting of randomly selected elements. #### Throws Throws an error if `size` is greater than the length of the array. --- --- url: /reference/compat/array/sampleSize.md --- # sampleSize (Lodash Compatibility) ::: warning Use `es-toolkit`'s [sampleSize](../../array/sampleSize.md) This `sampleSize` function operates slowly due to `null` or `undefined` handling, object support, default value processing, etc. Instead, use the faster and more modern `es-toolkit`'s [sampleSize](../../array/sampleSize.md). ::: Randomly selects a specified number of elements from an array or object. ```typescript const sampled = sampleSize(collection, size); ``` ## Usage ### `sampleSize(collection, size?)` Use `sampleSize` to randomly select elements from an array or object. It uses Floyd's algorithm to sample efficiently without duplicates. ```typescript import { sampleSize } from 'es-toolkit/compat'; // Randomly select 3 elements from an array. sampleSize([1, 2, 3, 4, 5], 3); // Returns: [2, 4, 5] (actual results may vary) // Randomly select 2 values from an object. sampleSize({ a: 1, b: 2, c: 3, d: 4 }, 2); // Returns: [2, 4] (actual results may vary) ``` `null` or `undefined` is handled as an empty array. ```typescript import { sampleSize } from 'es-toolkit/compat'; sampleSize(null, 2); // Returns: [] sampleSize(undefined, 2); // Returns: [] ``` #### Parameters * `collection` (`Record | Record | T | null | undefined`): The array or object to sample from. * `size` (`number`, optional): The number of elements to select. The default is `1`. #### Returns (`T[]`): Returns a new array composed of randomly selected elements. --- --- url: /reference/promise/Semaphore.md --- # Semaphore Limits the number of asynchronous tasks that can execute simultaneously. ```typescript const semaphore = new Semaphore(capacity); ``` ## Usage ### `Semaphore(capacity)` Use `Semaphore` when you want to limit the number of asynchronous tasks that can execute concurrently. It's particularly useful in situations where you need to control resource usage, such as database connection pools, API call rate limiting, or file download limits. ```typescript import { Semaphore } from 'es-toolkit'; const semaphore = new Semaphore(3); // API call rate limiting example (maximum 3 concurrent executions) async function callAPI(id: number) { await semaphore.acquire(); try { console.log(`Starting API call: ${id}`); const response = await fetch(`/api/data/${id}`); return response.json(); } finally { semaphore.release(); console.log(`Completed API call: ${id}`); } } // File download limiting example async function downloadFile(url: string) { await semaphore.acquire(); try { console.log(`Starting download: ${url}`); // File download logic await fetch(url); } finally { semaphore.release(); console.log(`Completed download: ${url}`); } } // Even if 5 tasks are called simultaneously, only 3 execute concurrently callAPI(1); callAPI(2); callAPI(3); callAPI(4); // Waits until one of the previous tasks completes callAPI(5); // Waits until one of the previous tasks completes ``` #### Parameters * `capacity` (`number`): The maximum number of tasks that can execute concurrently. Must be an integer greater than 1. #### Properties * `capacity` (`number`): The maximum number of tasks that can execute concurrently. * `available` (`number`): The number of currently available permits. If `0`, all permits are in use. #### Methods * `acquire` (`() => Promise`): Acquires permission to execute an asynchronous task, or waits until permission is granted. * `release` (`() => void`): Returns permission so that the next waiting task can execute. --- --- url: /reference/compat/object/set.md --- # set (Lodash Compatibility) ::: warning Use direct assignment instead This `set` function internally calls the `updateWith` function and operates slowly due to complex path processing and object creation logic. Use faster and more modern direct assignment or destructuring assignment instead. ::: Sets the value at the specified path of the object. ```typescript const result = set(obj, path, value); ``` ## Usage ### `set(object, path, value)` Use `set` when you want to set a value at a specific path in an object. If any part of the path doesn't exist, it's automatically created. Useful when dealing with nested objects or arrays. ```typescript import { set } from 'es-toolkit/compat'; // Basic usage const obj = { a: { b: { c: 3 } } }; set(obj, 'a.b.c', 4); console.log(obj.a.b.c); // 4 // Set value in array const arr = [1, 2, 3]; set(arr, '1', 4); console.log(arr[1]); // 4 // Create non-existent path const empty = {}; set(empty, 'user.profile.name', 'John'); console.log(empty); // Result: { user: { profile: { name: 'John' } } } // Use array path const data = {}; set(data, ['nested', 'array', 0], 'first item'); console.log(data); // Result: { nested: { array: ['first item'] } } // Auto-create array indices const list = {}; set(list, 'items[0]', 'first'); set(list, 'items[2]', 'third'); console.log(list); // Result: { items: ['first', undefined, 'third'] } // Mix nested objects and arrays const complex = {}; set(complex, 'users[0].profile.settings.theme', 'dark'); console.log(complex); // Result: { users: [{ profile: { settings: { theme: 'dark' } } }] } // Handle numeric keys const numeric = {}; set(numeric, 123, 'number key'); console.log(numeric[123]); // 'number key' // Overwrite existing values const existing = { a: { b: 'old' } }; set(existing, 'a.b', 'new'); console.log(existing.a.b); // 'new' ``` The original object is directly modified and returned. ```typescript import { set } from 'es-toolkit/compat'; const original = { x: 1 }; const result = set(original, 'y', 2); console.log(original === result); // true console.log(original); // { x: 1, y: 2 } ``` #### Parameters * `object` (`T`): The object to set the value in. * `path` (`PropertyPath`): The path of the property to set. Can be a string, array, or array of keys. * `value` (`any`): The value to set. #### Returns (`T`): Returns the modified object (same as the original object). --- --- url: /reference/compat/object/setWith.md --- # setWith (Lodash Compatibility) ::: warning Use direct assignment instead This `setWith` function internally calls the `updateWith` function and operates slowly due to complex path processing and customizer logic. Use faster and more modern direct assignment or destructuring assignment instead. ::: Sets a value at the specified path while controlling how objects are created with a customizer function. ```typescript const result = setWith(obj, path, value, customizer); ``` ## Usage ### `setWith(object, path, value, customizer)` Use `setWith` when you want to set a value at a specific path in an object while controlling the type of intermediate objects created with a customizer function. If the customizer returns `undefined`, the default logic (array for array indices, object otherwise) is used. ```typescript import { setWith } from 'es-toolkit/compat'; // Basic usage (no customizer) const obj1 = {}; setWith(obj1, 'a.b.c', 4); console.log(obj1); // Result: { a: { b: { c: 4 } } } // Customizer forcing array creation const obj2 = {}; setWith(obj2, '[0][1]', 'value', () => []); console.log(obj2); // Result: { '0': [undefined, 'value'] } // Customize only under specific conditions const obj3 = {}; setWith(obj3, 'a[0].b.c', 'nested', (value, key) => { // Return empty object only for numeric keys (array indices) return typeof key === 'string' && /^\d+$/.test(key) ? {} : undefined; }); console.log(obj3); // Result: { a: { '0': { b: { c: 'nested' } } } } // Use Object constructor as customizer const obj4 = {}; setWith(obj4, 'x[0].y', 42, Object); console.log(obj4); // Result: { x: { '0': { y: 42 } } } // Complex customizer logic const obj5 = {}; setWith(obj5, 'data.items[0].props.config', 'value', (value, key, object) => { console.log('Creating:', key, 'in', object); // Use Map for specific keys if (key === 'props') { return new Map(); } // Array for numeric keys if (typeof key === 'string' && /^\d+$/.test(key)) { return []; } // Regular object by default return {}; }); // Use WeakMap as intermediate object const obj6 = {}; setWith(obj6, 'cache.user.profile', 'data', (value, key) => { if (key === 'cache') { return new WeakMap(); } return undefined; // Use default behavior }); ``` The customizer function receives three parameters. ```typescript import { setWith } from 'es-toolkit/compat'; const obj = {}; setWith(obj, 'a.b[0].c', 'value', (nsValue, key, nsObject) => { console.log('nsValue:', nsValue); // Current value (usually undefined) console.log('key:', key); // Key to create console.log('nsObject:', nsObject); // Parent object // Return different object types based on specific conditions return key === 'b' ? [] : {}; }); ``` #### Parameters * `object` (`T`): The object to set the value in. * `path` (`PropertyPath`): The path of the property to set. * `value` (`any`): The value to set. * `customizer` (`(nsValue: any, key: string, nsObject: T) => any`, optional): Function to customize the creation of intermediate objects. #### Returns (`T | R`): Returns the modified object. --- --- url: /reference/array/shuffle.md --- # shuffle Returns a new array with the elements randomly shuffled. ```typescript const shuffled = shuffle(arr); ``` ## Usage ### `shuffle(arr)` Use `shuffle` when you want to randomly shuffle the elements in an array. It uses the Fisher-Yates algorithm to ensure perfect random shuffling where all permutations appear with equal probability. It's useful for shuffling a deck in card games, randomizing quiz question order, or shuffling a playlist. ```typescript import { shuffle } from 'es-toolkit/array'; // Shuffle a number array. const numbers = [1, 2, 3, 4, 5]; const shuffledNumbers = shuffle(numbers); // Returns: [3, 1, 4, 5, 2] (example, actually random) console.log(numbers); // [1, 2, 3, 4, 5] (original is unchanged) // Shuffle a string array. const fruits = ['apple', 'banana', 'cherry', 'date']; const shuffledFruits = shuffle(fruits); // Returns: ['cherry', 'apple', 'date', 'banana'] (example, actually random) ``` You can shuffle various types of arrays. ```typescript import { shuffle } from 'es-toolkit/array'; // Shuffle an object array. const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 35 }, ]; const shuffledUsers = shuffle(users); // Returns: a new array with user objects shuffled in random order // Shuffle a mixed type array. const mixed = [1, 'hello', true, { key: 'value' }]; const shuffledMixed = shuffle(mixed); // Returns: a new array with elements shuffled in random order ``` #### Parameters * `arr` (`readonly T[]`): The array to shuffle. #### Returns (`T[]`): Returns a new array with elements shuffled in random order. The original array is not changed. --- --- url: /reference/compat/array/shuffle.md --- # shuffle (Lodash Compatibility) ::: warning Use `es-toolkit`'s `shuffle` This `shuffle` function includes additional processing for Lodash compatibility and operates slowly. Instead, use the faster and more modern `es-toolkit`'s [shuffle](../../array/shuffle.md). ::: Shuffles the elements of an array or object randomly and returns a new array. ```typescript const result = shuffle(collection); ``` ## Usage ### `shuffle(collection)` Uses the Fisher-Yates algorithm to randomly shuffle the elements of an array or object and returns a new array. The original is not modified. ```typescript import { shuffle } from 'es-toolkit/compat'; // Shuffle a number array const numbers = [1, 2, 3, 4, 5]; const shuffled1 = shuffle(numbers); // Returns: for example [3, 1, 5, 2, 4] (different order each time) // Shuffle a string array const fruits = ['apple', 'banana', 'cherry', 'date']; const shuffled2 = shuffle(fruits); // Returns: for example ['cherry', 'apple', 'date', 'banana'] // Shuffle object values const obj = { a: 1, b: 2, c: 3, d: 4 }; const shuffled3 = shuffle(obj); // Returns: for example [3, 1, 4, 2] (object values are randomly shuffled) ``` `null` or `undefined` is handled as an empty array. ```typescript import { shuffle } from 'es-toolkit/compat'; shuffle(null); // Returns: [] shuffle(undefined); // Returns: [] ``` #### Parameters * `collection` (`ArrayLike | T | null | undefined`): The array or object to shuffle. #### Returns (`T[]`): Returns a new array with elements randomly shuffled. --- --- url: /reference/compat/array/size.md --- # size (Lodash Compatibility) ::: warning Use `.length` property This `size` function operates complexly due to `null`, `undefined` handling and support for various types. Instead, use the faster and more modern `.length` property or `Object.keys().length`. ::: Returns the size of arrays, strings, and objects. ```typescript const length = size(collection); ``` ## Usage ### `size(collection)` Use `size` to check the size of arrays, strings, objects, Maps, and Sets. It provides consistent size information for various types of collections. ```typescript import { size } from 'es-toolkit/compat'; // Number of elements in an array size([1, 2, 3]); // Returns 3 // Number of characters in a string size('hello'); // Returns 5 // Number of enumerable properties in an object size({ a: 1, b: 2, c: 3 }); // Returns 3 // Number of elements in a Map size( new Map([ ['a', 1], ['b', 2], ]) ); // Returns 2 // Number of elements in a Set size(new Set([1, 2, 3])); // Returns 3 ``` `null` or `undefined` returns 0. ```typescript import { size } from 'es-toolkit/compat'; size(null); // 0 size(undefined); // 0 size({}); // 0 size([]); // 0 ``` #### Parameters * `collection` (`object | string | null | undefined`): The array, string, object, Map, or Set to check the size of. #### Returns (`number`): Returns the size of the collection. Returns 0 if `null` or `undefined`. --- --- url: /reference/compat/array/slice.md --- # slice (Lodash Compatibility) ::: warning Use `Array.prototype.slice` This `slice` function operates slowly due to `null` or `undefined` handling and special processing of sparse arrays. JavaScript's native `Array.prototype.slice` method is faster and more standardized. Instead, use the faster and more modern `Array.prototype.slice`. ::: Slices a portion of an array to create a new array. ```typescript const sliced = slice(array, start, end); ``` ## Usage ### `slice(array, start, end)` Use `slice` when you need only a specific portion of an array. It creates a new array containing elements from the start position up to, but not including, the end position. ```typescript import { slice } from 'es-toolkit/compat'; // Slice from index 1 to 2 slice([1, 2, 3, 4], 1, 3); // Returns: [2, 3] // Use negative indices slice([1, 2, 3, 4], -2); // Returns: [3, 4] // Specify only start position slice([1, 2, 3, 4], 2); // Returns: [3, 4] ``` `null` or `undefined` is handled as an empty array. ```typescript import { slice } from 'es-toolkit/compat'; slice(null); // [] slice(undefined); // [] ``` When processing sparse arrays, empty slots are filled with `undefined`. ```typescript import { slice } from 'es-toolkit/compat'; const sparse = new Array(3); sparse[1] = 'b'; slice(sparse); // Returns: [undefined, 'b', undefined] ``` Using negative indices calculates from the end of the array. ```typescript import { slice } from 'es-toolkit/compat'; slice([1, 2, 3, 4, 5], -3, -1); // Returns: [3, 4] ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to slice. * `start` (`number`, optional): The start position. Negative values calculate from the end. The default is `0`. * `end` (`number`, optional): The end position (not included). Negative values calculate from the end. The default is the array's length. #### Returns (`T[]`): Returns a new array containing elements from `start` up to, but not including, `end`. --- --- url: /reference/string/snakeCase.md --- # snakeCase Converts a string to snake case. ```typescript const converted = snakeCase(str); ``` ## Usage ### `snakeCase(str)` Use `snakeCase` when you want to convert a string to snake case. Snake case is a naming convention where each word is written in lowercase and words are connected with underscores (\_). ```typescript import { snakeCase } from 'es-toolkit/string'; // Basic usage snakeCase('camelCase'); // 'camel_case' snakeCase('some whitespace'); // 'some_whitespace' // Words connected with hyphens or other separators snakeCase('hyphen-text'); // 'hyphen_text' snakeCase('PascalCase'); // 'pascal_case' // Handling consecutive uppercase letters snakeCase('HTTPRequest'); // 'http_request' snakeCase('XMLHttpRequest'); // 'xml_http_request' ``` It also correctly handles strings with various separators. ```typescript import { snakeCase } from 'es-toolkit/string'; // Mixed separators snakeCase('camelCase-with_mixed.separators'); // 'camel_case_with_mixed_separators' // With numbers snakeCase('version2.1.0'); // 'version_2_1_0' // With special characters snakeCase('user@email.com'); // 'user_email_com' ``` #### Parameters * `str` (`string`): The string to convert to snake case. #### Returns (`string`): Returns a new string converted to snake case. --- --- url: /reference/compat/string/snakeCase.md --- # snakeCase (Lodash compatibility) ::: warning Use `snakeCase` from `es-toolkit` This `snakeCase` function operates slowly due to normalization logic for handling `null` or `undefined`. Instead, use the faster and more modern [snakeCase](../../string/snakeCase.md) from `es-toolkit`. ::: Converts a string to snake case. ```typescript const snakeCased = snakeCase(str); ``` ## Usage ### `snakeCase(str)` Use `snakeCase` when you want to convert a string to snake*case. Snake case is a naming convention where each word is written in lowercase and connected with underscores (*). ```typescript import { snakeCase } from 'es-toolkit/compat'; // Convert camel case snakeCase('camelCase'); // Returns: 'camel_case' // Convert space-separated string snakeCase('some whitespace'); // Returns: 'some_whitespace' // Convert hyphen-separated string snakeCase('hyphen-text'); // Returns: 'hyphen_text' // Handle consecutive uppercase letters snakeCase('HTTPRequest'); // Returns: 'http_request' ``` `null` or `undefined` are treated as empty strings. ```typescript import { snakeCase } from 'es-toolkit/compat'; snakeCase(null); // '' snakeCase(undefined); // '' ``` #### Parameters * `str` (`string`, optional): The string to convert to snake case. #### Returns (`string`): Returns the converted string in snake case. --- --- url: /reference/map/some.md --- # some (for `Map`s) Tests whether at least one entry in a Map satisfies the provided predicate function. ```typescript const anyMatch = some(map, doesMatch); ``` ::: info This function is available exclusively from `es-toolkit/map` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `some(map, doesMatch)` Use `some` when you want to check if at least one entry in a Map meets a specific condition. Provide a predicate function that tests each entry, and it returns true if the predicate is satisfied for at least one entry, and false otherwise. ```typescript import { some } from 'es-toolkit/map'; const map = new Map([ ['a', 1], ['b', 2], ['c', 3], ]); const result = some(map, value => value > 2); // Result: true const result2 = some(map, value => value > 5); // Result: false ``` You can test various conditions. ```typescript import { some } from 'es-toolkit/map'; // Check if any value meets criteria const inventory = new Map([ ['apple', { quantity: 0, inStock: false }], ['banana', { quantity: 5, inStock: true }], ['orange', { quantity: 0, inStock: false }], ]); const hasStock = some(inventory, item => item.inStock); // Result: true // Check if any key matches pattern const data = new Map([ ['user_1', 'Alice'], ['user_2', 'Bob'], ['group_1', 'Admins'], ]); const hasAdmin = some(data, (value, key) => key.startsWith('admin_')); // Result: false ``` #### Parameters * `map` (`Map`): The Map to test. * `doesMatch` (`(value: V, key: K, map: Map) => boolean`): A predicate function that tests each entry. #### Returns (`boolean`): true if at least one entry satisfies the predicate, false otherwise. --- --- url: /reference/set/some.md --- # some (for `Set`s) Tests whether at least one element in a Set satisfies the provided predicate function. ```typescript const anyMatch = some(set, doesMatch); ``` ::: info This function is available exclusively from `es-toolkit/set` to avoid potential conflicts with similar functions for other collection types. ::: ## Usage ### `some(set, doesMatch)` Use `some` when you want to check if at least one element in a Set meets a specific condition. Provide a predicate function that tests each element, and it returns true if the predicate is satisfied for at least one element, and false otherwise. ```typescript import { some } from 'es-toolkit/set'; const set = new Set([1, 2, 3]); const result = some(set, value => value > 2); // Result: true const result2 = some(set, value => value > 5); // Result: false ``` You can test various conditions. ```typescript import { some } from 'es-toolkit/set'; // Check if any value meets criteria const numbers = new Set([1, 3, 5, 7, 9]); const hasEven = some(numbers, num => num % 2 === 0); // Result: false const hasLarge = some(numbers, num => num > 5); // Result: true // Check object properties const users = new Set([ { name: 'Alice', admin: false }, { name: 'Bob', admin: true }, { name: 'Charlie', admin: false }, ]); const hasAdmin = some(users, user => user.admin); // Result: true ``` #### Parameters * `set` (`Set`): The Set to test. * `doesMatch` (`(value: T, value2: T, set: Set) => boolean`): A predicate function that tests each element. #### Returns (`boolean`): true if at least one element satisfies the predicate, false otherwise. --- --- url: /reference/compat/array/some.md --- # some (Lodash Compatibility) ::: warning Use `Array.prototype.some()` method This `some` function operates in a complex manner due to handling various types of conditions and object support. Instead, use the faster and more modern `Array.prototype.some()` method. ::: Checks if any element in an array or object satisfies the given condition. ```typescript const hasMatch = some(collection, predicate); ``` ## Usage ### `some(collection, predicate)` Use `some` when you want to check if at least one element in an array or object satisfies a condition. It supports various forms of conditions. ```typescript import { some } from 'es-toolkit/compat'; // Using a condition function on an array some([1, 2, 3, 4], n => n % 2 === 0); // Returns true (2 and 4 are even) // Matching with partial object on an array some([{ a: 1 }, { a: 2 }, { a: 3 }], { a: 2 }); // Returns true // Matching with property-value pair on an array some([{ a: 1 }, { a: 2 }, { a: 3 }], ['a', 2]); // Returns true // Checking if property is truthy on an array some([{ a: 0 }, { a: 1 }, { a: 0 }], 'a'); // Returns true (element with a=1 exists) // Using a condition function on an object some({ a: 1, b: 2, c: 3 }, n => n % 2 === 0); // Returns true (2 is even) ``` If no condition is provided, it checks if there are any truthy values. ```typescript import { some } from 'es-toolkit/compat'; some([0, 1, 2]); // true (1 and 2 are truthy) some([false, null, undefined]); // false (all values are falsy) some(null); // false (treated as empty array) ``` #### Parameters * `collection` (`ArrayLike | Record | null | undefined`): The array or object to check. * `predicate` (optional): The function to check the condition, partial object, property-value pair, or property name. #### Returns (`boolean`): Returns `true` if at least one element satisfies the condition, `false` otherwise. --- --- url: /reference/array/sortBy.md --- # sortBy Returns a new array sorted in ascending order by the given criteria. ```typescript const sorted = sortBy(arr, criteria); ``` ## Usage ### `sortBy(arr, criteria)` Use `sortBy` when you want to sort an array of objects by multiple properties or computed values. Provide property names or transformation functions as an array, and it sorts in ascending order with priority in that order. It's useful for sorting table data or when complex sorting logic is needed. ```typescript import { sortBy } from 'es-toolkit/array'; // Sort by a single property. const users = [ { name: 'john', age: 30 }, { name: 'jane', age: 25 }, { name: 'bob', age: 35 }, ]; const byAge = sortBy(users, ['age']); // Returns: [{ name: 'jane', age: 25 }, { name: 'john', age: 30 }, { name: 'bob', age: 35 }] // Sort by multiple properties. const employees = [ { name: 'john', department: 'engineering', age: 30 }, { name: 'jane', department: 'hr', age: 25 }, { name: 'bob', department: 'engineering', age: 35 }, { name: 'alice', department: 'engineering', age: 25 }, ]; const sorted = sortBy(employees, ['department', 'age']); // Returns: Sort by department first, then by age // [ // { name: 'alice', department: 'engineering', age: 25 }, // { name: 'john', department: 'engineering', age: 30 }, // { name: 'bob', department: 'engineering', age: 35 }, // { name: 'jane', department: 'hr', age: 25 } // ] ``` You can create complex sorting criteria using functions. ```typescript import { sortBy } from 'es-toolkit/array'; // Mix functions and properties. const products = [ { name: 'laptop', price: 1000, category: 'electronics' }, { name: 'shirt', price: 50, category: 'clothing' }, { name: 'phone', price: 800, category: 'electronics' }, ]; const sorted = sortBy(products, [ 'category', item => -item.price, // Sort price in descending order ]); // Returns: Sort by category first, then by highest price // Sort by computed values. const words = ['hello', 'a', 'wonderful', 'world']; const byLength = sortBy( words.map(word => ({ word, length: word.length })), ['length'] ); // Returns: Array of objects sorted by string length ``` #### Parameters * `arr` (`readonly T[]`): The array of objects to sort. * `criteria` (`Array<((item: T) => unknown) | keyof T>`): Sorting criteria. An array of object property names or transformation functions, with earlier criteria having higher priority. #### Returns (`T[]`): Returns a new array sorted in ascending order by the specified criteria. --- --- url: /reference/compat/array/sortBy.md --- # sortBy (Lodash Compatibility) ::: warning Use the `Array.prototype.sort` method instead This `sortBy` function behaves in a complex way due to handling various types of criteria and object support. Instead, use the faster and more modern `Array.prototype.sort` method. ::: Sorts an array in ascending order based on multiple criteria. ```typescript const sorted = sortBy(collection, ...iteratees); ``` ## Usage ### `sortBy(collection, ...iteratees)` Use `sortBy` to sort an array or object in ascending order using multiple criteria. It executes the sorting criteria functions for each element and sorts based on the resulting values. ```typescript import { sortBy } from 'es-toolkit/compat'; // Sort users by name. const users = [ { user: 'fred', age: 48 }, { user: 'barney', age: 34 }, { user: 'fred', age: 40 }, { user: 'barney', age: 36 }, ]; sortBy(users, ['user']); // Returns: [ // { user: 'barney', age: 34 }, // { user: 'barney', age: 36 }, // { user: 'fred', age: 48 }, // { user: 'fred', age: 40 }, // ] // Sort using a function. sortBy(users, [ function (o) { return o.user; }, ]); // Returns: [ // { user: 'barney', age: 34 }, // { user: 'barney', age: 36 }, // { user: 'fred', age: 48 }, // { user: 'fred', age: 40 }, // ] ``` You can also use multiple criteria at once. ```typescript import { sortBy } from 'es-toolkit/compat'; const users = [ { user: 'fred', age: 48 }, { user: 'barney', age: 34 }, { user: 'fred', age: 40 }, { user: 'barney', age: 36 }, ]; // Sort by name first, then by age. sortBy(users, ['user', item => item.age]); // Returns: [ // { user: 'barney', age: 34 }, // { user: 'barney', age: 36 }, // { user: 'fred', age: 40 }, // { user: 'fred', age: 48 }, // ] ``` `null` and `undefined` are treated as empty arrays. ```typescript import { sortBy } from 'es-toolkit/compat'; sortBy(null, ['key']); // [] sortBy(undefined, ['key']); // [] ``` #### Parameters * `collection` (`ArrayLike | object | null | undefined`): The array or object to sort. * `...iteratees` (`Array | ObjectIteratee>>`): The functions or property names that determine the sorting criteria. #### Returns (`T[]`): Returns a new array sorted in ascending order. --- --- url: /reference/compat/array/sortedIndex.md --- # sortedIndex (Lodash compatibility) ::: warning Implement binary search directly This `sortedIndex` function operates with complexity due to handling `null`, `undefined`, and various type support. Instead, implement a faster, more modern binary search directly or use a dedicated library. ::: Finds the lowest index at which a value should be inserted into a sorted array. ```typescript const index = sortedIndex(array, value); ``` ## Usage ### `sortedIndex(array, value)` Use `sortedIndex` to find the position to insert a value in a sorted array. It uses binary search to find the position quickly. ```typescript import { sortedIndex } from 'es-toolkit/compat'; // Find insertion position in number array sortedIndex([30, 50], 40); // Returns 1 (40 is positioned between 30 and 50) // Find insertion position in string array sortedIndex(['a', 'c'], 'b'); // Returns 1 ('b' is positioned between 'a' and 'c') // When the same value exists, returns the first position sortedIndex([1, 2, 2, 3], 2); // Returns 1 (position of the first 2) ``` For `null` or `undefined` arrays, returns 0. ```typescript import { sortedIndex } from 'es-toolkit/compat'; sortedIndex(null, 1); // 0 sortedIndex(undefined, 1); // 0 ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The sorted array. Using an unsorted array can produce incorrect results. * `value` (`T`): The value to insert. #### Returns (`number`): Returns the lowest index to insert the value. If the array is `null` or `undefined`, returns 0. --- --- url: /reference/compat/array/sortedIndexBy.md --- # sortedIndexBy (Lodash compatibility) ::: warning Implement binary search and transformation function directly This `sortedIndexBy` function operates slowly due to complex iteratee handling and type conversion. Instead, implement faster, more modern binary search and transformation functions directly. ::: Finds the lowest index at which a value should be inserted into a sorted array after applying a transformation function. ```typescript const index = sortedIndexBy(array, value, iteratee); ``` ## Usage ### `sortedIndexBy(array, value, iteratee)` Use `sortedIndexBy` to find the insertion position of a value in a sorted array after applying a transformation function. It applies the transformation function to each element and the value to compare. ```typescript import { sortedIndexBy } from 'es-toolkit/compat'; // Find insertion position in object array sorted by property const objects = [{ x: 4 }, { x: 5 }]; sortedIndexBy(objects, { x: 4 }, 'x'); // Returns 0 // Transform using function const numbers = [10, 20, 30]; sortedIndexBy(numbers, 25, n => n); // Returns 2 // Transform with property-value array const users = [{ name: 'alice' }, { name: 'bob' }]; sortedIndexBy(users, { name: 'bob' }, ['name', 'bob']); // Returns 1 (equivalent to inserting true into [false, true]) ``` For `null` or `undefined` arrays, returns 0. ```typescript import { sortedIndexBy } from 'es-toolkit/compat'; sortedIndexBy(null, { x: 1 }, 'x'); // 0 sortedIndexBy(undefined, { x: 1 }, 'x'); // 0 ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The sorted array. Using an unsorted array can produce incorrect results. * `value` (`T`): The value to insert. * `iteratee` (optional): The transformation function, property name, or property-value array to apply to each element and value. #### Returns (`number`): Returns the lowest index to insert the value. If the array is `null` or `undefined`, returns 0. --- --- url: /reference/compat/array/sortedIndexOf.md --- # sortedIndexOf (Lodash compatibility) ::: warning Implement binary search directly This `sortedIndexOf` function operates slowly due to complex binary search handling and type validation. Instead, implement faster, more modern binary search directly or use `Array.prototype.indexOf()`. ::: Finds the index where a value first appears in a sorted array. ```typescript const index = sortedIndexOf(array, value); ``` ## Usage ### `sortedIndexOf(array, value)` Use `sortedIndexOf` to find the index where a specific value first appears in a sorted array. It uses binary search to find the value quickly. ```typescript import { sortedIndexOf } from 'es-toolkit/compat'; // Find value in number array sortedIndexOf([11, 22, 33, 44, 55], 33); // Returns 2 // When value doesn't exist sortedIndexOf([11, 22, 33, 44, 55], 30); // Returns -1 // When duplicate values exist, returns the first index sortedIndexOf([1, 2, 2, 3, 3, 3, 4], 3); // Returns 3 (position of the first 3) // 0 and -0 are treated as equal sortedIndexOf([-0, 0], 0); // Returns 0 ``` Empty arrays, `null`, or `undefined` return -1. ```typescript import { sortedIndexOf } from 'es-toolkit/compat'; sortedIndexOf([], 1); // -1 sortedIndexOf(null, 1); // -1 sortedIndexOf(undefined, 1); // -1 ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The sorted array. Using an unsorted array can produce incorrect results. * `value` (`T`): The value to find. #### Returns (`number`): Returns the index where the value first appears. If the value doesn't exist, returns -1. --- --- url: /reference/compat/array/sortedLastIndex.md --- # sortedLastIndex (Lodash compatibility) ::: warning Implement binary search directly This `sortedLastIndex` function operates slowly due to complex binary search handling and type validation. Instead, implement faster, more modern binary search directly. ::: Finds the highest index at which a value should be inserted into a sorted array. ```typescript const index = sortedLastIndex(array, value); ``` ## Usage ### `sortedLastIndex(array, value)` Use `sortedLastIndex` to find the highest position to insert a value in a sorted array. When duplicate values exist, it returns the index after the last position. ```typescript import { sortedLastIndex } from 'es-toolkit/compat'; // Find last insertion position in array with duplicate values sortedLastIndex([4, 5, 5, 5, 6], 5); // Returns 4 (position after the last 5) // Find insertion position for new value sortedLastIndex([10, 20, 30], 25); // Returns 2 (25 is positioned before 30) // When value doesn't exist sortedLastIndex([1, 2, 3], 0); // Returns 0 (positioned at the front) ``` For `null` or `undefined` arrays, returns 0. ```typescript import { sortedLastIndex } from 'es-toolkit/compat'; sortedLastIndex(null, 1); // 0 sortedLastIndex(undefined, 1); // 0 ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The sorted array. Using an unsorted array can produce incorrect results. * `value` (`T`): The value to insert. #### Returns (`number`): Returns the highest index to insert the value. If the array is `null` or `undefined`, returns 0. --- --- url: /reference/compat/array/sortedLastIndexBy.md --- # sortedLastIndexBy (Lodash compatibility) ::: warning Implement binary search and transformation function directly This `sortedLastIndexBy` function operates slowly due to complex iteratee handling and type conversion. Instead, implement faster, more modern binary search and transformation functions directly. ::: Finds the highest index at which a value should be inserted into a sorted array after applying a transformation function. ```typescript const index = sortedLastIndexBy(array, value, iteratee); ``` ## Usage ### `sortedLastIndexBy(array, value, iteratee)` Use `sortedLastIndexBy` to find the highest insertion position of a value in a sorted array after applying a transformation function. When duplicate values exist, it returns the index after the last value. ```typescript import { sortedLastIndexBy } from 'es-toolkit/compat'; // Find last insertion position in object array sorted by property const objects = [{ x: 4 }, { x: 5 }, { x: 5 }]; sortedLastIndexBy(objects, { x: 5 }, 'x'); // Returns 3 (position after the last x: 5) // Transform using function const numbers = [10, 20, 20, 30]; sortedLastIndexBy(numbers, 20, n => n); // Returns 3 ``` For `null` or `undefined` arrays, returns 0. ```typescript import { sortedLastIndexBy } from 'es-toolkit/compat'; sortedLastIndexBy(null, { x: 1 }, 'x'); // 0 sortedLastIndexBy(undefined, { x: 1 }, 'x'); // 0 ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The sorted array. Using an unsorted array can produce incorrect results. * `value` (`T`): The value to insert. * `iteratee` (optional): The transformation function, property name, or property-value array to apply to each element and value. #### Returns (`number`): Returns the highest index to insert the value. If the array is `null` or `undefined`, returns 0. --- --- url: /reference/compat/array/sortedLastIndexOf.md --- # sortedLastIndexOf (Lodash compatibility) ::: warning Implement binary search directly This `sortedLastIndexOf` function operates slowly due to complex binary search handling and type validation. Instead, implement faster, more modern binary search directly or use `Array.prototype.lastIndexOf()`. ::: Finds the index where a value last appears in a sorted array. ```typescript const index = sortedLastIndexOf(array, value); ``` ## Usage ### `sortedLastIndexOf(array, value)` Use `sortedLastIndexOf` to find the index where a specific value last appears in a sorted array. It uses binary search to find the value quickly. ```typescript import { sortedLastIndexOf } from 'es-toolkit/compat'; // Find value in number array sortedLastIndexOf([1, 2, 3, 4, 5], 3); // Returns 2 // When value doesn't exist sortedLastIndexOf([1, 2, 3, 4, 5], 6); // Returns -1 // When duplicate values exist, returns the last index sortedLastIndexOf([1, 2, 2, 3, 3, 3, 4], 3); // Returns 5 (position of the last 3) // 0 and -0 are treated as equal sortedLastIndexOf([-0, 0], 0); // Returns 1 ``` Empty arrays, `null`, or `undefined` return -1. ```typescript import { sortedLastIndexOf } from 'es-toolkit/compat'; sortedLastIndexOf([], 1); // -1 sortedLastIndexOf(null, 1); // -1 sortedLastIndexOf(undefined, 1); // -1 ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The sorted array. Using an unsorted array can produce incorrect results. * `value` (`T`): The value to find. #### Returns (`number`): Returns the index where the value last appears. If the value doesn't exist, returns -1. --- --- url: /reference/compat/string/split.md --- # split (Lodash compatibility) ::: warning Use JavaScript's `String.prototype.split` This `split` function operates slowly due to handling `null` or `undefined`. Instead, use the faster and more modern JavaScript's `String.prototype.split`. ::: Splits a string into an array using a separator. ```typescript const segments = split(str, separator); ``` ## Usage ### `split(string, separator?, limit?)` Use `split` when you want to divide a string into an array using a specific separator. You can also limit the maximum length of the resulting array. ```typescript import { split } from 'es-toolkit/compat'; // Split by hyphen split('a-b-c', '-'); // Returns: ['a', 'b', 'c'] // Limit the number of results split('a-b-c-d', '-', 2); // Returns: ['a', 'b'] // Split by regular expression split('hello world', /\s/); // Returns: ['hello', 'world'] ``` If no separator is specified, the entire string becomes the first element of the array. ```typescript import { split } from 'es-toolkit/compat'; split('hello'); // Returns: ['hello'] ``` `null` or `undefined` are treated as empty strings. ```typescript import { split } from 'es-toolkit/compat'; split(null); // Returns: [''] split(undefined); // Returns: [''] ``` #### Parameters * `string` (`string`, optional): The string to split. Defaults to an empty string. * `separator` (`RegExp | string`, optional): The separator to use for splitting. * `limit` (`number`, optional): The maximum length of the resulting array. #### Returns (`string[]`): Returns an array of strings split by the separator. --- --- url: /reference/function/spread.md --- # spread Creates a new function that spreads a parameter array into individual parameters of the function. ```typescript const spreadFunc = spread(func); ``` ## Usage ### `spread(func)` Use `spread` when you want to spread an array-form parameter into individual parameters to pass to a function. This plays a similar role to JavaScript's spread operator (`...`), but it transforms the function to accept an array instead. This is useful in situations where you frequently use the `apply` method. ```typescript import { spread } from 'es-toolkit/function'; // Basic usage function add(a: number, b: number) { return a + b; } const spreadAdd = spread(add); console.log(spreadAdd([5, 3])); // 8 // Function with multiple parameters function greet(greeting: string, name: string, punctuation: string) { return `${greeting}, ${name}${punctuation}`; } const spreadGreet = spread(greet); console.log(spreadGreet(['Hello', 'World', '!'])); // 'Hello, World!' // Using with Math functions const numbers = [1, 2, 3, 4, 5]; const spreadMax = spread(Math.max); console.log(spreadMax(numbers)); // 5 const spreadMin = spread(Math.min); console.log(spreadMin(numbers)); // 1 ``` The `this` context is also maintained. ```typescript import { spread } from 'es-toolkit/function'; const calculator = { multiply: function (a: number, b: number, c: number) { return a * b * c; }, }; const spreadMultiply = spread(calculator.multiply); console.log(spreadMultiply.call(calculator, [2, 3, 4])); // 24 ``` #### Parameters * `func` (`F`): The function to accept a parameter array spread into individual parameters. #### Returns (`(args: Parameters) => ReturnType`): Returns a new function that accepts a parameter array and passes it to the original function in spread form. --- --- url: /reference/compat/function/spread.md --- # spread (Lodash Compatibility) ::: warning Use modern spread operator instead This `spread` function handles complex logic to spread array arguments at a specific index into individual arguments, which can be slow. Use the faster, more modern spread operator (`...`) directly instead. ::: Creates a new function that spreads array arguments into individual arguments when calling the function. ```typescript const spreadFunc = spread(func, argsIndex); ``` ## Usage ### `spread(func, argsIndex)` Use `spread` when you want to call a function by spreading an array argument into individual arguments. You can specify the position of the array, allowing it to work with other arguments. ```typescript import { spread } from 'es-toolkit/compat'; // Basic usage - first argument is an array function add(a, b) { return a + b; } const spreadAdd = spread(add); spreadAdd([1, 2]); // 3 // When the second argument is an array function greet(greeting, names) { return `${greeting}, ${names.join(' and ')}!`; } const spreadGreet = spread(greet, 1); spreadGreet('Hello', ['Alice', 'Bob']); // 'Hello, Alice and Bob!' // Modern spread operator example (recommended) function modernAdd(a, b) { return a + b; } const numbers = [1, 2]; modernAdd(...numbers); // 3 - simpler and faster ``` It's especially useful when passing arrays as function arguments, but in modern JavaScript, using the spread operator is more common. #### Parameters * `func` (`Function`): The function to transform. * `argsIndex` (`number`, optional): The position of the array argument. Default is `0`. #### Returns (`Function`): Returns a new function that spreads the array argument when called. --- --- url: /reference/string/startCase.md --- # startCase Converts the first letter of each word in a string to uppercase. ```typescript const converted = startCase(str); ``` ## Usage ### `startCase(str)` Use `startCase` when you want to convert a string to start case (where the first letter of each word is capitalized). It capitalizes the first letter of each word, converts the rest to lowercase, and joins the words with spaces. ```typescript import { startCase } from 'es-toolkit/string'; // Basic usage startCase('hello world'); // 'Hello World' startCase('HELLO WORLD'); // 'Hello World' // Converting camelCase or PascalCase startCase('fooBar'); // 'Foo Bar' startCase('PascalCase'); // 'Pascal Case' // Words connected with hyphens or underscores startCase('hello-world'); // 'Hello World' startCase('hello_world'); // 'Hello World' ``` It also correctly handles strings with various delimiters and special characters. ```typescript import { startCase } from 'es-toolkit/string'; // Cases with multiple delimiters startCase('--foo-bar--'); // 'Foo Bar' startCase('__FOO_BAR__'); // 'Foo Bar' // Handling consecutive uppercase letters and numbers startCase('XMLHttpRequest'); // 'Xml Http Request' startCase('_abc_123_def'); // 'Abc 123 Def' // Cases with empty strings or only meaningless delimiters startCase('_-_-_-_'); // '' startCase('12abc 12ABC'); // '12 Abc 12 Abc' ``` #### Parameters * `str` (`string`): The string to convert to start case. #### Returns (`string`): Returns a new string with the first letter of each word capitalized and joined with spaces. ## Demo ::: sandpack ```ts index.ts import { startCase } from 'es-toolkit/string'; console.log(startCase('startCase')); ``` ::: --- --- url: /reference/compat/string/startCase.md --- # startCase (Lodash compatibility) ::: warning Use `startCase` from `es-toolkit` This `startCase` function runs slower due to normalization logic for handling `null` or `undefined`. Instead, use the faster and more modern [startCase](../../string/startCase.md) from `es-toolkit`. ::: Converts a string to start case. ```typescript const startCased = startCase(str); ``` ## Usage ### `startCase(str)` Use `startCase` when you want to convert a string to Start Case. Start Case is a naming convention where the first letter of each word is capitalized and separated by spaces. ```typescript import { startCase } from 'es-toolkit/compat'; // Convert regular string startCase('hello world'); // Returns: 'Hello World' // Keep words that are already uppercase startCase('HELLO WORLD'); // Returns: 'HELLO WORLD' // Convert hyphen-separated string startCase('hello-world'); // Returns: 'Hello World' // Convert underscore-separated string startCase('hello_world'); // Returns: 'Hello World' ``` `null` or `undefined` are treated as empty strings. ```typescript import { startCase } from 'es-toolkit/compat'; startCase(null); // '' startCase(undefined); // '' ``` #### Parameters * `str` (`string`, optional): The string to convert to start case. #### Returns (`string`): Returns the start case converted string. --- --- url: /reference/compat/string/startsWith.md --- # startsWith (Lodash compatibility) ::: warning Use JavaScript's `String.prototype.startsWith` This `startsWith` function is slower due to handling `null` or `undefined`. Use the faster and more modern JavaScript's `String.prototype.startsWith` instead. ::: Checks if a string starts with a given string. ```typescript const result = startsWith(str, target); ``` ## Usage ### `startsWith(str, target, position?)` Use `startsWith` when you want to check if a string starts with a specific string. You can also specify the position to start the search. ```typescript import { startsWith } from 'es-toolkit/compat'; // Check if string starts with target startsWith('fooBar', 'foo'); // Returns: true startsWith('fooBar', 'bar'); // Returns: false // Check from a specific position startsWith('fooBar', 'Bar', 3); // Returns: true (checks if it starts with 'Bar' from position 3) ``` Returns `false` for `null` or `undefined`. ```typescript import { startsWith } from 'es-toolkit/compat'; startsWith(null, 'test'); // Returns: false startsWith('test', null); // Returns: false ``` #### Parameters * `str` (`string`, optional): The string to check. * `target` (`string`, optional): The string to search for at the start. * `position` (`number`, optional): The position to start the search. Defaults to `0`. #### Returns (`boolean`): Returns `true` if the string starts with the given string, otherwise `false`. --- --- url: /reference/compat/util/stubArray.md --- # stubArray (Lodash Compatibility) ::: warning Use `[]` directly instead This `stubArray` function is a simple wrapper that returns an empty array and represents unnecessary abstraction. Use the faster and more direct `[]` instead. ::: Always returns a new empty array. ```typescript const emptyArray = stubArray(); ``` ## Usage ### `stubArray()` A function that always returns a new empty array. Use this when you need an empty array as a default value or when you need consistent return values in functional programming. ```typescript import { stubArray } from 'es-toolkit/compat'; // Returns an empty array const emptyArray = stubArray(); console.log(emptyArray); // => [] // Use as default value in array methods const items = [1, 2, 3]; const result = items.filter(x => x > 5) || stubArray(); console.log(result); // => [] // Use in functional programming const getData = () => stubArray(); const data = getData(); data.push('item'); // Safe because it's a new array ``` Returns a new array instance each time. ```typescript import { stubArray } from 'es-toolkit/compat'; const arr1 = stubArray(); const arr2 = stubArray(); console.log(arr1 === arr2); // => false (different instances) console.log(Array.isArray(arr1)); // => true console.log(arr1.length); // => 0 ``` #### Parameters None. #### Returns (`any[]`): Returns a new empty array. --- --- url: /reference/compat/util/stubFalse.md --- # stubFalse (Lodash Compatibility) ::: warning Use `false` directly instead This `stubFalse` function is a simple wrapper that returns `false` and represents unnecessary abstraction. Use the faster and more direct `false` value instead. ::: Always returns `false`. ```typescript const falseValue = stubFalse(); ``` ## Usage ### `stubFalse()` A function that always returns `false`. This is useful when you need a consistent false value in functional programming or as a default value in conditional callbacks. ```typescript import { stubFalse } from 'es-toolkit/compat'; // Returns false const result = stubFalse(); console.log(result); // => false // Use as default condition in array filtering const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter(stubFalse); // Removes all elements console.log(evenNumbers); // => [] // Use in functional programming const isValid = condition => (condition ? someValidation : stubFalse); const validator = isValid(false); console.log(validator()); // => false ``` Returns the same `false` value every time. ```typescript import { stubFalse } from 'es-toolkit/compat'; const result1 = stubFalse(); const result2 = stubFalse(); console.log(result1 === result2); // => true console.log(typeof result1); // => 'boolean' console.log(result1); // => false ``` #### Parameters None. #### Returns (`false`): Always returns `false`. --- --- url: /reference/compat/util/stubObject.md --- # stubObject (Lodash Compatibility) ::: warning Use `{}` directly instead This `stubObject` function is a simple wrapper that returns an empty object and represents unnecessary abstraction. Use the faster and more direct `{}` instead. ::: Always returns a new empty object. ```typescript const emptyObject = stubObject(); ``` ## Usage ### `stubObject()` A function that always returns a new empty object. Use this when you need an empty object as a default value or when you need consistent return values in functional programming. ```typescript import { stubObject } from 'es-toolkit/compat'; // Returns an empty object const emptyObject = stubObject(); console.log(emptyObject); // => {} // Use as default value function processData(data = stubObject()) { return { ...data, processed: true }; } console.log(processData()); // => { processed: true } console.log(processData({ name: 'John' })); // => { name: 'John', processed: true } // Use in functional programming const createEmpty = () => stubObject(); const obj = createEmpty(); obj.newProperty = 'value'; // Safe because it's a new object ``` Returns a new object instance each time. ```typescript import { stubObject } from 'es-toolkit/compat'; const obj1 = stubObject(); const obj2 = stubObject(); console.log(obj1 === obj2); // => false (different instances) console.log(typeof obj1); // => 'object' console.log(Object.keys(obj1).length); // => 0 ``` #### Parameters None. #### Returns (`any`): Returns a new empty object. --- --- url: /reference/compat/util/stubString.md --- # stubString (Lodash Compatibility) ::: warning Use `''` directly instead This `stubString` function is a simple wrapper that returns an empty string and represents unnecessary abstraction. Use the faster and more direct `''` instead. ::: Always returns an empty string. ```typescript const emptyString = stubString(); ``` ## Usage ### `stubString()` A function that always returns an empty string. Use this when you need an empty string as a default value or when you need consistent return values in functional programming. ```typescript import { stubString } from 'es-toolkit/compat'; // Returns an empty string const emptyString = stubString(); console.log(emptyString); // => '' // Use as default value function formatMessage(message = stubString()) { return message || 'Default message'; } console.log(formatMessage()); // => 'Default message' console.log(formatMessage('Hello')); // => 'Hello' // Use in functional programming const createEmpty = () => stubString(); const str = createEmpty(); console.log(str.length); // => 0 ``` Returns the same empty string every time. ```typescript import { stubString } from 'es-toolkit/compat'; const str1 = stubString(); const str2 = stubString(); console.log(str1 === str2); // => true console.log(typeof str1); // => 'string' console.log(str1.length); // => 0 ``` #### Parameters None. #### Returns (`string`): Always returns an empty string. --- --- url: /reference/compat/util/stubTrue.md --- # stubTrue (Lodash Compatibility) ::: warning Use `true` literal instead This `stubTrue` function performs slowly due to unnecessary function calls. Use the faster and more modern `true` literal instead. ::: Always returns the `true` value. ```typescript const result = stubTrue(); ``` ## Usage ### `stubTrue()` Use `stubTrue` when you need a callback function or default value that always returns `true`. This is useful for providing a consistent `true` value in array method filtering or conditional logic. ```typescript import { stubTrue } from 'es-toolkit/compat'; // Filter that keeps all elements in an array const items = [1, 2, 3, 4, 5]; const allItems = items.filter(stubTrue); console.log(allItems); // [1, 2, 3, 4, 5] ``` It can also be used as a default value in conditional settings. ```typescript import { stubTrue } from 'es-toolkit/compat'; // Options that are enabled by default const defaultOptions = { enableFeatureA: stubTrue(), enableFeatureB: stubTrue(), enableFeatureC: stubTrue(), }; console.log(defaultOptions); // { enableFeatureA: true, enableFeatureB: true, enableFeatureC: true } ``` #### Parameters None. #### Returns (`boolean`): Always returns `true`. --- --- url: /reference/compat/math/subtract.md --- # subtract (Lodash Compatibility) ::: warning Use `-` operator This `subtract` function works slowly due to additional function calls. Use the faster and simpler `-` operator instead. ::: Subtracts two numbers. ```typescript const result = subtract(value, other); ``` ## Usage ### `subtract(value, other)` Use `subtract` when you want to subtract two numbers. ```typescript import { subtract } from 'es-toolkit/compat'; // Basic subtraction subtract(6, 4); // Returns: 2 subtract(10, 3); // Returns: 7 // Negative number handling subtract(-6, 4); // Returns: -10 subtract(6, -4); // Returns: 10 // NaN handling subtract(NaN, 4); // Returns: NaN subtract(6, NaN); // Returns: NaN subtract(NaN, NaN); // Returns: NaN ``` #### Parameters * `value` (`number`): The base number for subtraction. * `other` (`number`): The number to subtract. #### Returns (`number`): Returns the result of subtracting the second number from the first. If either is NaN, returns NaN. --- --- url: /reference/math/sum.md --- # sum Returns the sum of all elements in an array of numbers. ```typescript const total = sum(numbers); ``` ## Usage ### `sum(nums)` Use `sum` when you want to calculate the total of numbers. It adds up all numbers in an array to compute the sum. ```typescript import { sum } from 'es-toolkit/math'; // Basic number sum const numbers = [1, 2, 3, 4, 5]; const total = sum(numbers); console.log(total); // 15 // Sum of decimal numbers const prices = [19.99, 25.5, 3.75]; const totalPrice = sum(prices); console.log(totalPrice); // 49.24 // Sum with negative and positive numbers mixed const values = [-10, 5, -3, 8]; const result = sum(values); console.log(result); // 0 // Single number array const single = [42]; const singleSum = sum(single); console.log(singleSum); // 42 ``` Empty arrays and real-world examples. ```typescript import { sum } from 'es-toolkit/math'; // Empty array returns 0. const empty = sum([]); console.log(empty); // 0 // Calculate score total const scores = [85, 92, 78, 96, 88]; const totalScore = sum(scores); const averageScore = totalScore / scores.length; console.log(totalScore); // 439 console.log(averageScore); // 87.8 // Calculate monthly sales total const monthlySales = [12000, 15000, 18000, 14000, 16000]; const totalSales = sum(monthlySales); console.log(totalSales); // 75000 // Calculate shopping cart total const cartItems = [29.99, 15.5, 8.75, 42.0]; const cartTotal = sum(cartItems); console.log(cartTotal); // 96.24 ``` Calculation results can be used with other functions. ```typescript import { sum } from 'es-toolkit/math'; import { round } from 'es-toolkit/math'; // Round after summing const measurements = [1.234, 2.567, 3.891]; const total = sum(measurements); const rounded = round(total, 2); console.log(rounded); // 7.69 // Calculate percentages const votes = [45, 32, 23]; const totalVotes = sum(votes); const percentages = votes.map(vote => round((vote / totalVotes) * 100, 1)); console.log(percentages); // [45.0, 32.0, 23.0] ``` #### Parameters * `nums` (`readonly number[]`): The array of numbers to sum. #### Returns (`number`): Returns the sum of all numbers in the array. Returns `0` for empty arrays. --- --- url: /reference/compat/math/sum.md --- # sum (Lodash Compatibility) ::: warning Use [sum](../../math/sum.md) from es-toolkit This `sum` function works slowly due to type conversion and null/undefined handling. Use the faster and more modern [sum](../../math/sum.md) from `es-toolkit` instead. ::: Adds all values in an array. ```typescript const total = sum(array); ``` ## Usage ### `sum(array)` Adds all numbers in an array to get the total sum. ```typescript import { sum } from 'es-toolkit/compat'; // Number array sum([1, 2, 3]); // Returns: 6 sum([1.5, 2.5, 3]); // Returns: 7 // Empty array sum([]); // Returns: 0 ``` Handles BigInt and strings as well. ```typescript import { sum } from 'es-toolkit/compat'; // BigInt array sum([1n, 2n, 3n]); // Returns: 6n // String array (concatenated) sum(['1', '2']); // Returns: '12' ``` Invalid values are ignored. ```typescript import { sum } from 'es-toolkit/compat'; sum([1, undefined, 2]); // Returns: 3 (undefined ignored) sum(null); // Returns: 0 sum(undefined); // Returns: 0 ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array containing values to add. #### Returns (`number`): Returns the total sum of all values. --- --- url: /reference/math/sumBy.md --- # sumBy Calculates the sum of array elements using a transformation function. ```typescript const total = sumBy(items, getValue); ``` ## Usage ### `sumBy(items, getValue)` Use `sumBy` when you want to convert each element of an array to a number and calculate the sum. It's useful for summing specific properties from an array of objects. ```typescript import { sumBy } from 'es-toolkit/math'; // Sum a specific property from an array of objects const products = [ { name: 'laptop', price: 1000 }, { name: 'mouse', price: 25 }, { name: 'keyboard', price: 75 }, ]; const totalPrice = sumBy(products, item => item.price); console.log(totalPrice); // 1100 // Sum user ages const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 35 }, ]; const totalAge = sumBy(users, user => user.age); console.log(totalAge); // 90 // Sum string lengths const words = ['hello', 'world', 'test']; const totalLength = sumBy(words, word => word.length); console.log(totalLength); // 14 ``` Complex calculations are also possible. ```typescript import { sumBy } from 'es-toolkit/math'; // Sum with weighted scores const scores = [ { subject: 'math', score: 90, weight: 0.3 }, { subject: 'english', score: 85, weight: 0.2 }, { subject: 'science', score: 95, weight: 0.5 }, ]; const weightedSum = sumBy(scores, item => item.score * item.weight); console.log(weightedSum); // 91 // Sum lengths of arrays const arrays = [[1, 2], [3, 4, 5], [6]]; const totalElements = sumBy(arrays, arr => arr.length); console.log(totalElements); // 6 // Conditional calculation const orders = [ { id: 1, amount: 100, status: 'completed' }, { id: 2, amount: 200, status: 'pending' }, { id: 3, amount: 150, status: 'completed' }, ]; const completedTotal = sumBy(orders, order => (order.status === 'completed' ? order.amount : 0)); console.log(completedTotal); // 250 ``` Real-world use case examples. ```typescript import { sumBy } from 'es-toolkit/math'; // Sum monthly sales const monthlyReports = [ { month: 'January', sales: 12000, expenses: 8000 }, { month: 'February', sales: 15000, expenses: 9000 }, { month: 'March', sales: 18000, expenses: 11000 }, ]; const totalSales = sumBy(monthlyReports, report => report.sales); const totalExpenses = sumBy(monthlyReports, report => report.expenses); const totalProfit = totalSales - totalExpenses; console.log(totalSales); // 45000 console.log(totalExpenses); // 28000 console.log(totalProfit); // 17000 // Calculate total score for averaging student grades const students = [ { name: 'Alice', tests: [85, 90, 88] }, { name: 'Bob', tests: [92, 87, 95] }, { name: 'Charlie', tests: [78, 85, 82] }, ]; const totalTestScores = sumBy(students, student => student.tests.reduce((sum, score) => sum + score, 0)); console.log(totalTestScores); // 762 ``` Empty arrays return 0. ```typescript import { sumBy } from 'es-toolkit/math'; const emptyArray = []; const result = sumBy(emptyArray, x => x.value); console.log(result); // 0 ``` #### Parameters * `items` (`readonly T[]`): The array to calculate the sum from. * `getValue` (`(element: T) => number`): A function that converts each element to a number. #### Returns (`number`): Returns the sum of values after applying the transformation function. Returns `0` for empty arrays. --- --- url: /reference/compat/math/sumBy.md --- # sumBy (Lodash Compatibility) ::: warning Use [sumBy](../../math/sumBy.md) from es-toolkit This `sumBy` function works slowly due to iteratee function processing and type conversion. Use the faster and more modern [sumBy](../../math/sumBy.md) from `es-toolkit` instead. ::: Adds values that meet a condition. ```typescript const total = sumBy(array, iteratee); ``` ## Usage ### `sumBy(array, iteratee)` Adds the results of applying a function to each element in an array. ```typescript import { sumBy } from 'es-toolkit/compat'; // Number array sumBy([1, 2, 3], value => value); // Returns: 6 sumBy([1.5, 2.5, 3.5], value => Math.floor(value)); // Returns: 6 (1 + 2 + 3) // Empty array sumBy([], value => value); // Returns: 0 ``` ### `sumBy(array)` If no function is provided, it adds the array values directly. ```typescript import { sumBy } from 'es-toolkit/compat'; sumBy([1, 2, 3]); // Returns: 6 sumBy([1n, 2n, 3n]); // Returns: 6n ``` Add specific properties from object arrays. ```typescript import { sumBy } from 'es-toolkit/compat'; const people = [ { name: 'John', age: 25 }, { name: 'Jane', age: 30 }, { name: 'Bob', age: 35 }, ]; sumBy(people, person => person.age); // Returns: 90 // Can also use property name sumBy(people, 'age'); // Returns: 90 ``` Concatenates strings as well. ```typescript import { sumBy } from 'es-toolkit/compat'; const items = [{ a: '1' }, { a: '2' }]; sumBy(items, obj => obj.a); // Returns: '12' ``` Invalid values are ignored. ```typescript import { sumBy } from 'es-toolkit/compat'; sumBy([1, undefined, 2], value => value); // Returns: 3 (undefined ignored) sumBy(null); // Returns: 0 sumBy(undefined); // Returns: 0 ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to process. * `iteratee` (`((value: T) => number) | string`, optional): The function or property name to apply to each element. #### Returns (`number`): Returns the total sum of values that meet the condition. --- --- url: /reference/array/tail.md --- # tail Returns a new array consisting of all elements except the first. ```typescript const result = tail(arr); ``` ## Usage ### `tail(arr)` Use `tail` when you want to get all elements except the first from an array. If the array is empty or has only one element, it returns an empty array. It's useful when processing all elements except the first in a stack or queue. ```typescript import { tail } from 'es-toolkit/array'; // Exclude the first element from a number array. const numbers = [1, 2, 3, 4, 5]; tail(numbers); // Returns: [2, 3, 4, 5] // Exclude the first element from a string array. const strings = ['first', 'second', 'third']; tail(strings); // Returns: ['second', 'third'] // An array with only one element returns an empty array. const single = [42]; tail(single); // Returns: [] ``` It safely handles empty arrays and special cases. ```typescript import { tail } from 'es-toolkit/array'; // An empty array returns an empty array. const empty: number[] = []; tail(empty); // Returns: [] // It can also handle nested arrays. const nested = [ [1, 2], [3, 4], [5, 6], ]; tail(nested); // Returns: [[3, 4], [5, 6]] // It can also handle object arrays. const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }, ]; tail(users); // Returns: [{ id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }] ``` #### Parameters * `arr` (`readonly T[]`): The array from which to exclude the first element. #### Returns (`T[]`): Returns a new array excluding the first element. If the input array is empty or has only one element, it returns an empty array. --- --- url: /reference/compat/array/tail.md --- # tail (Lodash compatibility) ::: warning Please use [tail](../../array/tail.md) from `es-toolkit` This `tail` function operates slowly due to handling `null` or `undefined`. Please use the faster and modern [tail](../../array/tail.md) from `es-toolkit` instead. ::: Returns all elements of an array except the first one. ```typescript const result = tail(array); ``` ## Usage ### `tail(array)` Use `tail` when you want to create a new array containing all elements except the first one from the input array. If the input array is empty or has only one element, it returns an empty array. ```typescript import { tail } from 'es-toolkit/compat'; // Remove the first element from a number array. tail([1, 2, 3]); // Returns: [2, 3] // Remove the first element from a string array. tail(['a', 'b', 'c']); // Returns: ['b', 'c'] // Array with only one element. tail([1]); // Returns: [] // Empty array. tail([]); // Returns: [] ``` `null` or `undefined` is treated as an empty array. ```typescript import { tail } from 'es-toolkit/compat'; tail(null); // [] tail(undefined); // [] ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to remove the first element from. #### Returns (`T[]`): Returns a new array containing all elements except the first one. --- --- url: /reference/array/take.md --- # take Creates a new array by taking the specified number of elements from the beginning of the array. ```typescript const taken = take(arr, count); ``` ## Usage ### `take(arr, count?)` Use `take` when you only need a few elements from the front of an array. If the requested count is greater than the array length, it returns the entire array. ```typescript import { take } from 'es-toolkit/array'; // Take the first 3 elements. take([1, 2, 3, 4, 5], 3); // Returns: [1, 2, 3] // Take the first 2 elements. take(['a', 'b', 'c'], 2); // Returns: ['a', 'b'] ``` If you request more elements than the array has, it returns the entire array. ```typescript import { take } from 'es-toolkit/array'; take([1, 2, 3], 5); // Returns: [1, 2, 3] ``` If you omit `count`, it takes only the first element. ```typescript import { take } from 'es-toolkit/array'; take([1, 2, 3]); // Returns: [1] ``` #### Parameters * `arr` (`T[]`): The array to take elements from. * `count` (`number`, optional): The number of elements to take. Default is `1`. #### Returns (`T[]`): Returns a new array containing the first `count` elements from the array. --- --- url: /reference/compat/array/take.md --- # take (Lodash compatibility) ::: warning Please use [take](../../array/take.md) from `es-toolkit` This `take` function operates slowly due to additional processing for compatibility with Lodash. Please use the faster and modern [take](../../array/take.md) from `es-toolkit` instead. ::: Takes a specified number of elements from the beginning of an array and creates a new array. ```typescript const result = take([1, 2, 3, 4, 5], 3); // result becomes [1, 2, 3]. ``` ## Usage ### `take(array, count)` Takes a specified number of elements from the beginning of an array and returns a new array. If `count` is greater than the array length, returns the entire array. ```typescript import { take } from 'es-toolkit/compat'; // Basic usage const numbers = [1, 2, 3, 4, 5]; const result1 = take(numbers, 3); // Returns: [1, 2, 3] // Request count greater than array length const result2 = take(numbers, 10); // Returns: [1, 2, 3, 4, 5] (entire array) // Request 0 elements const result3 = take(numbers, 0); // Returns: [] // Handle empty array const result4 = take([], 3); // Returns: [] // Handle negative number const result5 = take(numbers, -1); // Returns: [] ``` #### Parameters * `array` (`T[]`): The array to take elements from. * `count` (`number`): The number of elements to take. Default is 1. #### Returns (`T[]`): A new array containing the specified number of elements from the beginning. --- --- url: /reference/array/takeRight.md --- # takeRight Creates a new array by taking the specified number of elements from the end of the array. ```typescript const taken = takeRight(arr, count); ``` ## Usage ### `takeRight(arr, count?)` Use `takeRight` when you only need a few elements from the end of an array. If the requested count is greater than the array length, it returns the entire array. ```typescript import { takeRight } from 'es-toolkit/array'; // Take the last 2 elements. takeRight([1, 2, 3, 4, 5], 2); // Returns: [4, 5] // Take the last 2 elements. takeRight(['a', 'b', 'c'], 2); // Returns: ['b', 'c'] ``` If you request more elements than the array has, it returns the entire array. ```typescript import { takeRight } from 'es-toolkit/array'; takeRight([1, 2, 3], 5); // Returns: [1, 2, 3] ``` If you omit `count`, it takes only the last element. ```typescript import { takeRight } from 'es-toolkit/array'; takeRight([1, 2, 3]); // Returns: [3] ``` #### Parameters * `arr` (`T[]`): The array to take elements from. * `count` (`number`, optional): The number of elements to take. Default is `1`. #### Returns (`T[]`): Returns a new array containing the last `count` elements from the array. --- --- url: /reference/compat/array/takeRight.md --- # takeRight (Lodash compatibility) ::: warning Please use [takeRight](../../array/takeRight.md) from `es-toolkit` This `takeRight` function operates slowly due to handling `null` or `undefined`. Please use the faster and modern [takeRight](../../array/takeRight.md) from `es-toolkit` instead. ::: Takes a specified number of elements from the end of an array. ```typescript const result = takeRight(array, count); ``` ## Usage ### `takeRight(array, count)` Use `takeRight` when you want to create a new array by taking a specified number of elements from the end of an array. If the requested count is greater than the array length, returns the entire array. ```typescript import { takeRight } from 'es-toolkit/compat'; // Take the last 2 elements from a number array. takeRight([1, 2, 3, 4, 5], 2); // Returns: [4, 5] // Take the last 3 elements from a string array. takeRight(['a', 'b', 'c'], 2); // Returns: ['b', 'c'] // When requested count is greater than array length takeRight([1, 2, 3], 5); // Returns: [1, 2, 3] // Request 0 elements takeRight([1, 2, 3], 0); // Returns: [] // Request negative number takeRight([1, 2, 3], -1); // Returns: [] ``` `null` or `undefined` is treated as an empty array. ```typescript import { takeRight } from 'es-toolkit/compat'; takeRight(null, 2); // [] takeRight(undefined, 2); // [] ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to take elements from. * `count` (`number`, optional): The number of elements to take. Default is `1`. #### Returns (`T[]`): Returns a new array containing the specified number of elements from the end. --- --- url: /reference/array/takeRightWhile.md --- # takeRightWhile Returns a new array by taking elements from the end of the array while the condition function returns true. ```typescript const result = takeRightWhile(arr, shouldContinueTaking); ``` ## Usage ### `takeRightWhile(arr, shouldContinueTaking)` Use `takeRightWhile` when you want to take elements from the end of an array that meet a condition. It stops when it encounters the first element for which the condition function returns false. ```typescript import { takeRightWhile } from 'es-toolkit/array'; // Take numbers less than 4 from the end takeRightWhile([5, 4, 3, 2, 1], n => n < 4); // Result: [3, 2, 1] // Take numbers greater than 3 from the end takeRightWhile([1, 2, 3], n => n > 3); // Result: [] // Take elements with string length <= 5 takeRightWhile(['hello', 'world', 'foo', 'bar'], str => str.length <= 5); // Result: ['hello', 'world', 'foo', 'bar'] ``` #### Parameters * `arr` (`T[]`): The array to take elements from. * `shouldContinueTaking` (`(item: T, index: number, array: T[]) => boolean`): A condition function called with each element, its index, and the array. Elements are included in the result as long as this function returns true. #### Returns (`T[]`): A new array containing the elements taken from the end while the condition function returns true. ## Examples ```typescript // Using index parameter takeRightWhile([10, 20, 30, 40], (x, index) => index > 1); // Returns: [30, 40] // Using array parameter takeRightWhile([1, 2, 3, 4], (x, index, arr) => x >= arr.length / 2); // Returns: [2, 3, 4] ``` --- --- url: /reference/compat/array/takeRightWhile.md --- # takeRightWhile (Lodash compatibility) ::: warning Please use [takeRightWhile](../../array/takeRightWhile.md) from `es-toolkit` This `takeRightWhile` function operates slowly due to handling `null` or `undefined`. Please use the faster and modern [takeRightWhile](../../array/takeRightWhile.md) from `es-toolkit` instead. ::: Takes elements from the end of an array while the condition is satisfied. ```typescript const result = takeRightWhile(array, predicate); ``` ## Usage ### `takeRightWhile(array, predicate)` Use `takeRightWhile` when you want to create a new array by taking elements from the end of an array while the condition is satisfied. It stops when the condition evaluates to false. ```typescript import { takeRightWhile } from 'es-toolkit/compat'; // Using function condition const numbers = [1, 2, 3, 4, 5]; takeRightWhile(numbers, x => x > 3); // Returns: [4, 5] // Using object property condition const users = [ { user: 'barney', active: true }, { user: 'fred', active: false }, { user: 'pebbles', active: false }, ]; takeRightWhile(users, o => !o.active); // Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] // Matching with partial object takeRightWhile(users, { active: false }); // Returns: [{ user: 'pebbles', active: false }] // Matching with property-value array takeRightWhile(users, ['active', false]); // Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] // Checking for truthy value by property name const items = [{ active: false }, { active: true }, { active: true }]; takeRightWhile(items, 'active'); // Returns: [{ active: true }, { active: true }] ``` `null` or `undefined` is treated as an empty array. ```typescript import { takeRightWhile } from 'es-toolkit/compat'; takeRightWhile(null, x => x > 0); // [] takeRightWhile(undefined, x => x > 0); // [] ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to process. * `predicate` (`ListIteratee`, optional): The condition to run for each element. Can be a function, partial object, property-value array, or property name. Default is the identity function. #### Returns (`T[]`): Returns a new array of elements taken from the end while the condition is satisfied. --- --- url: /reference/array/takeWhile.md --- # takeWhile Creates a new array by taking elements from the beginning of the array while the condition function returns true. ```typescript const taken = takeWhile(arr, predicate); ``` ## Usage ### `takeWhile(arr, predicate)` Use `takeWhile` when you only need elements from the beginning of an array that meet a specific condition. It stops taking elements when it encounters the first element that doesn't meet the condition. ```typescript import { takeWhile } from 'es-toolkit/array'; // Take only elements less than 3. takeWhile([1, 2, 3, 4], x => x < 3); // Returns: [1, 2] // Return an empty array since there are no elements greater than 3 from the beginning. takeWhile([1, 2, 3, 4], x => x > 3); // Returns: [] ``` It can also be used with object arrays. ```typescript import { takeWhile } from 'es-toolkit/array'; const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 35 }, { name: 'David', age: 40 }, ]; // Take only users under 30 years old. takeWhile(users, user => user.age < 30); // Returns: [{ name: 'Alice', age: 25 }] ``` #### Parameters * `arr` (`T[]`): The array to take elements from. * `predicate` (`(element: T, index: number, array: T[]) => boolean`): A condition function called for each element with the element, its index, and the array. Elements are taken while this function returns true. #### Returns (`T[]`): Returns a new array containing the elements taken from the beginning while the condition function returns true. ## Examples ```typescript // Using index parameter takeWhile([10, 20, 30, 40], (x, index) => index < 2); // Returns: [10, 20] // Using array parameter takeWhile([1, 2, 3, 4], (x, index, arr) => x < arr.length); // Returns: [1, 2, 3] ``` --- --- url: /reference/compat/array/takeWhile.md --- # takeWhile (Lodash compatibility) ::: warning Please use [takeWhile](../../array/takeWhile.md) from `es-toolkit` This `takeWhile` function operates slowly due to handling `null` or `undefined`. Please use the faster and modern [takeWhile](../../array/takeWhile.md) from `es-toolkit` instead. ::: Takes elements from the beginning of an array while the condition is satisfied. ```typescript const result = takeWhile(array, predicate); ``` ## Usage ### `takeWhile(array, predicate)` Use `takeWhile` when you want to create a new array by taking elements from the beginning of an array while the condition is satisfied. It stops when the condition evaluates to false. ```typescript import { takeWhile } from 'es-toolkit/compat'; // Using function condition const numbers = [1, 2, 3, 4, 5]; takeWhile(numbers, x => x < 3); // Returns: [1, 2] // Using object property condition const users = [ { user: 'barney', active: false }, { user: 'fred', active: false }, { user: 'pebbles', active: true }, ]; takeWhile(users, o => !o.active); // Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] // Matching with partial object takeWhile(users, { active: false }); // Returns: [{ user: 'barney', active: false }] // Matching with property-value array takeWhile(users, ['active', false]); // Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] // Checking for truthy value by property name const items = [{ active: true }, { active: true }, { active: false }]; takeWhile(items, 'active'); // Returns: [{ active: true }, { active: true }] ``` `null` or `undefined` is treated as an empty array. ```typescript import { takeWhile } from 'es-toolkit/compat'; takeWhile(null, x => x > 0); // [] takeWhile(undefined, x => x > 0); // [] ``` #### Parameters * `array` (`ArrayLike | null | undefined`): The array to process. * `predicate` (`ListIteratee`, optional): The condition to run for each element. Can be a function, partial object, property-value array, or property name. Default is the identity function. #### Returns (`T[]`): Returns a new array of elements taken from the beginning while the condition is satisfied. --- --- url: /reference/compat/string/template.md --- # template (Lodash compatibility) ::: warning Use JavaScript template literals This `template` function operates slowly due to complex string processing. Use faster and more modern JavaScript template literals instead. ::: Creates a function that interpolates values into a string template to generate a new string. ```typescript const compiled = template(templateString); ``` ## Usage ### `template(string, options?)` Use `template` when you want to interpolate data into a string template to create a completed string. You can safely escape values, interpolate them as-is, or execute JavaScript code. Basic usage allows you to interpolate or escape values. ```typescript import { template } from 'es-toolkit/compat'; // Interpolate values as-is const compiled = template('<%= value %>'); compiled({ value: 'Hello, World!' }); // Returns: 'Hello, World!' // Safely escape HTML const safeCompiled = template('<%- value %>'); safeCompiled({ value: '' }); // Returns: '<script>alert("xss")</script>' ``` You can also execute JavaScript code. ```typescript import { template } from 'es-toolkit/compat'; // Using conditional statements const compiled = template('<% if (user) { %>Hello <%= user %>!<% } %>'); compiled({ user: 'es-toolkit' }); // Returns: 'Hello es-toolkit!' // Using loops const listTemplate = template('<% users.forEach(function(user) { %>
  • <%= user %>
  • <% }); %>'); listTemplate({ users: ['Alice', 'Bob', 'Charlie'] }); // Returns: '
  • Alice
  • Bob
  • Charlie
  • ' ``` You can specify variable names for safer usage. ```typescript import { template } from 'es-toolkit/compat'; const compiled = template('<%= data.name %> is <%= data.age %> years old', { variable: 'data', }); compiled({ name: 'Alice', age: 25 }); // Returns: 'Alice is 25 years old' ``` You can import and use external functions. ```typescript import { template } from 'es-toolkit/compat'; const compiled = template('<%= _.toUpper(message) %>', { imports: { _: { toUpper: str => str.toUpperCase() } }, }); compiled({ message: 'hello world' }); // Returns: 'HELLO WORLD' ``` You can also create custom delimiters. ```typescript import { template } from 'es-toolkit/compat'; // Interpolate with custom delimiters const compiled = template('{{ message }}', { interpolate: /\{\{([\s\S]+?)\}\}/g, }); compiled({ message: 'Hello!' }); // Returns: 'Hello!' // Escape with custom delimiters const safeCompiled = template('[- html -]', { escape: /\[-([\s\S]+?)-\]/g, }); safeCompiled({ html: '
    content
    ' }); // Returns: '<div>content</div>' ``` #### Parameters * `string` (`string`): The template string. * `options` (`object`, optional): Configuration object. * `options.escape` (`RegExp`, optional): Regular expression delimiter for HTML escaping. Default is `<%-([\s\S]+?)%>`. * `options.evaluate` (`RegExp`, optional): Regular expression delimiter for executing JavaScript code. Default is `<%([\s\S]+?)%>`. * `options.interpolate` (`RegExp`, optional): Regular expression delimiter for value interpolation. Default is `<%=([\s\S]+?)%>`. * `options.variable` (`string`, optional): Variable name for the data object. * `options.imports` (`object`, optional): Functions to be used in the template. * `options.sourceURL` (`string`, optional): Source URL for debugging purposes. #### Returns (`TemplateExecutor`): A function that takes a data object and returns the completed string. The generated function code can also be accessed via the `source` property. --- --- url: /reference/function/throttle.md --- # throttle Limits a function to be executed at most once per specified time interval. ```typescript const throttledFunc = throttle(func, throttleMs, options); ``` ## Usage ### `throttle(func, throttleMs, options?)` Use `throttle` when you want to limit function calls to a specific time interval. This is useful for optimizing performance when handling frequently occurring events like scrolling, resizing, or mouse movement. Unlike `debounce`, throttle ensures the function is executed at least once during the specified time period. ```typescript import { throttle } from 'es-toolkit/function'; // Basic usage (execute at most once per second) const throttledLog = throttle(() => { console.log('Function executed!'); }, 1000); // First call: executes immediately throttledLog(); // Logs 'Function executed!' // Additional calls within 1 second: ignored throttledLog(); throttledLog(); // After 1 second, the last call executes as trailing // Scroll event optimization const handleScroll = throttle(() => { console.log('Scroll position:', window.scrollY); }, 100); // At most once per 100ms window.addEventListener('scroll', handleScroll); // API call optimization const searchThrottled = throttle(async (query: string) => { const results = await fetch(`/api/search?q=${query}`); console.log('Search results:', await results.json()); }, 300); // Even if called on every input, actual search executes only every 300ms searchThrottled('hello'); searchThrottled('hello w'); searchThrottled('hello world'); ``` You can adjust the leading and trailing options. ```typescript import { throttle } from 'es-toolkit/function'; // Enable only leading (execute only at start) const leadingOnly = throttle(() => console.log('Leading only'), 1000, { edges: ['leading'] }); // Enable only trailing (execute only at end) const trailingOnly = throttle(() => console.log('Trailing only'), 1000, { edges: ['trailing'] }); leadingOnly(); // Executes immediately leadingOnly(); // Ignored leadingOnly(); // Ignored trailingOnly(); // Does not execute immediately trailingOnly(); // Ignored trailingOnly(); // Executes after 1 second ``` You can also control it manually. ```typescript import { throttle } from 'es-toolkit/function'; const throttledFunc = throttle(() => console.log('executed'), 1000); throttledFunc(); // Executes immediately throttledFunc(); // Waiting // Immediately process pending execution throttledFunc.flush(); // Cancel pending execution throttledFunc.cancel(); ``` #### Parameters * `func` (`F`): The function to throttle. * `throttleMs` (`number`): The time interval (in milliseconds) to throttle execution. * `options` (`ThrottleOptions`, optional): Additional options. * `signal` (`AbortSignal`, optional): A signal that can cancel function execution. * `edges` (`Array<'leading' | 'trailing'>`, optional): Determines when to execute the function. Defaults to `['leading', 'trailing']`. #### Returns (`ThrottledFunction`): Returns a new throttled function with `cancel` and `flush` methods. --- --- url: /reference/compat/function/throttle.md --- # throttle (Lodash Compatibility) ::: warning Use `throttle` from `es-toolkit` instead This `throttle` function uses the debounce function internally for Lodash compatibility, making it somewhat complex. It also has more complex default and option handling. Use faster, more modern [throttle](../../function/throttle.md) from `es-toolkit` instead. ::: Limits function calls to execute at most once per specified time interval. ```typescript const throttledFunc = throttle(func, wait, options); ``` ## Usage ### `throttle(func, wait, options)` Use `throttle` when you want to limit function calls to execute at most once per specified time interval. It's useful for limiting the frequency of event handlers or API calls. ```typescript import { throttle } from 'es-toolkit/compat'; // Basic usage - execute at most once per second const throttledLog = throttle(() => { console.log('Event occurred!'); }, 1000); // Example with options const throttledScroll = throttle(handleScroll, 100, { leading: true, // Execute immediately on first call trailing: false, // Don't execute on last call }); window.addEventListener('scroll', throttledScroll); ``` It's essential for performance when handling rapidly occurring events like scroll or resize events. #### Parameters * `func` (`Function`): The function to throttle. * `wait` (`number`, optional): The wait time in milliseconds. Default is `0`. * `options` (`ThrottleSettings`, optional): Throttling options. * `leading` (`boolean`): Whether to execute on the first call. Default is `true`. * `trailing` (`boolean`): Whether to execute after the last call. Default is `true`. #### Returns (`DebouncedFunc`): Returns the throttled function. You can cancel pending executions with the `cancel()` method. --- --- url: /reference/promise/timeout.md --- # timeout Returns a `Promise` that throws a `TimeoutError` after the specified time. ```typescript await timeout(ms); ``` ## Usage ### `timeout(ms)` Use `timeout` when you want to throw a timeout error after a specific time has passed. It's useful when used together with `Promise.race()` to set time limits on tasks. ```typescript import { timeout } from 'es-toolkit/promise'; // Basic usage - throws TimeoutError after 1 second try { await timeout(1000); console.log('This code will not execute'); } catch (error) { console.log('Timeout error occurred:', error.message); // 'The operation was timed out' } ``` You can use it with `Promise.race()` to set time limits on tasks: ```typescript async function fetchWithTimeout(url: string) { try { const result = await Promise.race([ fetch(url), timeout(5000), // 5 second limit ]); return result; } catch (error) { if (error.name === 'TimeoutError') { console.log('Request is taking too long'); } throw error; } } ``` You can also use it when you want to fail the entire operation if any of multiple asynchronous tasks don't complete within the specified time. ```typescript async function multipleOperationsWithTimeout() { try { await Promise.race([ Promise.all([fetch('/api/data1'), fetch('/api/data2'), fetch('/api/data3')]), timeout(3000), // 3 second limit for all tasks ]); console.log('All tasks completed on time'); } catch (error) { console.log('Tasks did not complete on time'); } } ``` #### Parameters * `ms` (`number`): The amount of time in milliseconds until the `TimeoutError` is thrown. #### Returns (`Promise`): Returns a Promise that rejects with a `TimeoutError` after the specified time. #### Errors Throws `TimeoutError` after the specified time has passed. --- --- url: /reference/error/TimeoutError.md --- # TimeoutError An error class representing an operation that has timed out. ```typescript const error = new TimeoutError(message); ``` ## Usage ### `new TimeoutError(message?)` An error class used when an operation's time limit has been exceeded. It is thrown when operations like [timeout](../promise/timeout.md) or [withTimeout](../promise/withTimeout.md) have timed out. ```typescript import { TimeoutError } from 'es-toolkit/error'; // Create an error with the default message. throw new TimeoutError(); // Error message: 'The operation was timed out' // Create an error with a custom message. throw new TimeoutError('API request has timed out'); // Error message: 'API request has timed out' ``` An example of using it with timeout. ```typescript import { timeout, TimeoutError } from 'es-toolkit'; async function fetchWithTimeout(url: string) { try { const response = await timeout(() => fetch(url), 3000); return response; } catch (error) { if (error instanceof TimeoutError) { console.log('Request has timed out'); } throw error; } } // Throws TimeoutError if it takes more than 3 seconds await fetchWithTimeout('https://example.com/api/slow'); ``` #### Parameters * `message` (`string`, optional): The error message. Defaults to `'The operation was timed out'`. #### Returns (`TimeoutError`): Returns an error instance representing a timed out operation. It inherits from `Error` and the `name` property is `'TimeoutError'`. --- --- url: /reference/compat/util/times.md --- # times (Lodash Compatibility) Executes a function the given number of times and returns the results as an array. ```typescript const result = times(n, iteratee); ``` ## Usage ### `times(n, iteratee)` Executes the iteratee function the given number of times and returns the results as an array. The current index is passed to the function in each iteration. ```typescript import { times } from 'es-toolkit/compat'; // Array of indices from 0 to 2 multiplied by 2 times(3, i => i * 2); // Returns: [0, 2, 4] // Generate the same value multiple times times(2, () => 'es-toolkit'); // Returns: ['es-toolkit', 'es-toolkit'] ``` If no function is provided, it returns an array of indices. ```typescript import { times } from 'es-toolkit/compat'; times(3); // Returns: [0, 1, 2] ``` #### Parameters * `n` (`number`): The number of times to iterate. Converted to an integer. Returns an empty array if less than 1 or not a safe integer. * `iteratee` (`(num: number) => T`, optional): The function to execute for each iteration. Receives the index as an argument. If not provided, returns the index as is. #### Returns (`T[]`): Returns an array of results from executing the function in each iteration. --- --- url: /reference/compat/util/toArray.md --- # toArray (Lodash Compatibility) ::: warning Use Object.values and Array.from instead This `toArray` function performs slowly due to complex type validation and handling of various inputs. Instead, use faster and more modern Object.values or Array.from. ::: Converts a value to an array. ```typescript const array = toArray(value); ``` ## Usage ### `toArray(value)` Converts various values to arrays. Objects are converted to arrays of their values, array-like objects are converted to arrays, and everything else becomes an empty array. ```typescript import { toArray } from 'es-toolkit/compat'; // Convert object to array of values toArray({ a: 1, b: 2 }); // Returns: [1, 2] // Convert string to array of characters toArray('abc'); // Returns: ['a', 'b', 'c'] // Convert Map to array of values const map = new Map([ ['a', 1], ['b', 2], ]); toArray(map); // Returns: [['a', 1], ['b', 2]] ``` null or undefined are converted to empty arrays. ```typescript import { toArray } from 'es-toolkit/compat'; toArray(null); // Returns: [] toArray(undefined); // Returns: [] ``` #### Parameters * `value` (`unknown`): The value to convert to an array. #### Returns (`any[]`): Returns the converted array. --- --- url: /reference/object/toCamelCaseKeys.md --- # toCamelCaseKeys Returns a new object with all keys in objects and arrays converted to camelCase. Camel case is a naming convention where the first word is lowercase and the first letter of subsequent words is capitalized and concatenated. For example, it's written as `camelCase`. ```typescript const camelCased = toCamelCaseKeys(obj); ``` ## Usage ### `toCamelCaseKeys(obj)` Use `toCamelCaseKeys` when you want to convert all keys of an object to camel case. Nested objects and objects within arrays are also converted recursively. For example, object keys are converted as follows: * `snake_case` → `camelCase` (e.g. `user_id` → `userId`) * `PascalCase` → `camelCase` (e.g. `UserId` → `userId`) * `uppercase keys` → `camelCase` (e.g. `FIRST_NAME` → `firstName`, `LAST` → `last`) ```typescript import { toCamelCaseKeys } from 'es-toolkit/object'; // Basic object conversion const obj = { user_id: 1, first_name: 'John', last_name: 'Doe' }; const result = toCamelCaseKeys(obj); // result is { userId: 1, firstName: 'John', lastName: 'Doe' } // Objects within arrays are also converted const users = [ { user_id: 1, first_name: 'John' }, { user_id: 2, first_name: 'Jane' }, ]; const convertedUsers = toCamelCaseKeys(users); // convertedUsers is [{ userId: 1, firstName: 'John' }, { userId: 2, firstName: 'Jane' }] // Nested objects are fully converted const nested = { user_data: { user_id: 1, contact_info: { email_address: 'john@example.com', phone_number: '123-456-7890', }, }, }; const nestedResult = toCamelCaseKeys(nested); // nestedResult is { // userData: { // userId: 1, // contactInfo: { // emailAddress: 'john@example.com', // phoneNumber: '123-456-7890' // } // } // } // PascalCase and uppercase keys are also converted const raw = { UserId: 1, FIRST_NAME: 'JinHo', LAST: 'Yeom' }; const converted = toCamelCaseKeys(raw); // converted is { userId: 1, firstName: 'JinHo', last: 'Yeom' } ``` #### Parameters * `obj` (`T`): The object, array, or primitive value to convert keys to camelCase. #### Returns (`ToCamelCaseKeys`): Returns a new object with all keys converted to camelCase. --- --- url: /reference/compat/object/toDefaulted.md --- # toDefaulted (Lodash Compatibility) ::: warning Use spread operator or `Object.assign` instead This `toDefaulted` function operates slowly due to deep cloning and complex default value handling. Use faster and more modern spread operator (`...`) or `Object.assign()` instead. ::: Creates a new object by applying default values to an object. ```typescript const defaulted = toDefaulted(object, ...sources); ``` ## Usage ### `toDefaulted(object, ...sources)` Use `toDefaulted` when you want to create a new object by applying default values from one or more source objects to a target object. Default values are only set for properties that are `undefined` or come from `Object.prototype`. ```typescript import { toDefaulted } from 'es-toolkit/compat'; // Basic default value assignment const user = { name: 'John' }; const defaults = { name: 'Anonymous', age: 25, role: 'user' }; toDefaulted(user, defaults); // => { name: 'John', age: 25, role: 'user' } // Apply defaults from multiple sources const config = { theme: 'dark' }; const defaults1 = { theme: 'light', lang: 'en' }; const defaults2 = { lang: 'ko', region: 'Asia' }; toDefaulted(config, defaults1, defaults2); // => { theme: 'dark', lang: 'en', region: 'Asia' } ``` Only `undefined` values are replaced with defaults, while `null` values are preserved. ```typescript import { toDefaulted } from 'es-toolkit/compat'; const data = { name: undefined, age: null, active: false, }; const defaults = { name: 'Default', age: 18, active: true, role: 'user', }; toDefaulted(data, defaults); // => { name: 'Default', age: null, active: false, role: 'user' } ``` The original object is not modified; a new object is returned. ```typescript import { toDefaulted } from 'es-toolkit/compat'; const original = { a: 1 }; const result = toDefaulted(original, { a: 2, b: 3 }); console.log(original); // { a: 1 } (not modified) console.log(result); // { a: 1, b: 3 } (new object) ``` #### Parameters * `object` (`object`): The target object that will receive default values. * `sources` (`object[]`): The source objects that provide default values. Applied in left-to-right order. #### Returns (`object`): Returns a new object with the default values applied. --- --- url: /reference/array/toFilled.md --- # toFilled Creates a new array by filling part or all of it with the specified value. ```typescript const filled = toFilled(arr, value, start?, end?); ``` ## Usage ### `toFilled(arr, value, start?, end?)` Use `toFilled` when you want to fill a specific range of an array with a specified value. It creates and returns a new array without modifying the original array. ```typescript import { toFilled } from 'es-toolkit/array'; const array = [1, 2, 3, 4, 5]; // Fill with '*' from index 2 to the end. toFilled(array, '*', 2); // Returns: [1, 2, '*', '*', '*'] // Fill with '*' from index 1 to before index 4. toFilled(array, '*', 1, 4); // Returns: [1, '*', '*', '*', 5] ``` If you omit the start and end positions, it fills the entire array. ```typescript import { toFilled } from 'es-toolkit/array'; const array = [1, 2, 3, 4, 5]; toFilled(array, '*'); // Returns: ['*', '*', '*', '*', '*'] ``` You can also use negative indices. They count from the end of the array. ```typescript import { toFilled } from 'es-toolkit/array'; const array = [1, 2, 3, 4, 5]; // Fill with '*' from 4th from the end to before 1st from the end. toFilled(array, '*', -4, -1); // Returns: [1, '*', '*', '*', 5] ``` #### Parameters * `arr` (`T[]`): The original array to base on. * `value` (`U`): The value to fill the array with. * `start` (`number`, optional): The start position for filling. Default is `0`. * `end` (`number`, optional): The end position for filling. Default is the array length. #### Returns (`Array`): Returns a new array with the specified range filled with the value. The original array is not modified. --- --- url: /reference/compat/util/toFinite.md --- # toFinite (Lodash Compatibility) Converts a value to a finite number. ```typescript const finite = toFinite(value); ``` ## Usage ### `toFinite(value)` Converts a value to a finite number. Infinity values are converted to Number.MAX\_VALUE, and NaN is treated as 0. ```typescript import { toFinite } from 'es-toolkit/compat'; // Regular numbers are returned as is toFinite(3.2); // Returns: 3.2 // Infinity is converted to MAX_VALUE toFinite(Infinity); // Returns: 1.7976931348623157e+308 toFinite(-Infinity); // Returns: -1.7976931348623157e+308 // String numbers are converted to numbers toFinite('3.2'); // Returns: 3.2 ``` Invalid values are converted to 0. ```typescript import { toFinite } from 'es-toolkit/compat'; toFinite(NaN); // Returns: 0 toFinite(Symbol.iterator); // Returns: 0 toFinite(null); // Returns: 0 ``` #### Parameters * `value` (`unknown`): The value to convert. #### Returns (`number`): Returns the converted finite number. --- --- url: /reference/compat/util/toInteger.md --- # toInteger (Lodash Compatibility) Converts a value to an integer. ```typescript const integer = toInteger(value); ``` ## Usage ### `toInteger(value)` Converts a value to an integer. The decimal part is discarded, leaving only the integer part. ```typescript import { toInteger } from 'es-toolkit/compat'; // Convert decimal to integer toInteger(3.2); // Returns: 3 // Convert string number to integer toInteger('3.2'); // Returns: 3 // Very small numbers become 0 toInteger(Number.MIN_VALUE); // Returns: 0 // Infinity becomes MAX_VALUE toInteger(Infinity); // Returns: 1.7976931348623157e+308 ``` Invalid values are converted to 0. ```typescript import { toInteger } from 'es-toolkit/compat'; toInteger(NaN); // Returns: 0 toInteger(Symbol.iterator); // Returns: 0 toInteger(null); // Returns: 0 ``` #### Parameters * `value` (`unknown`): The value to convert. #### Returns (`number`): Returns the converted integer. --- --- url: /reference/compat/util/toLength.md --- # toLength (Lodash Compatibility) Converts a value to a valid array index. ```typescript const length = toLength(value); ``` ## Usage ### `toLength(value)` Converts a value to a valid array index. Limits to an integer between 0 and 2^32-1. ```typescript import { toLength } from 'es-toolkit/compat'; // Convert decimal to integer toLength(3.2); // Returns: 3 // Negative numbers become 0 toLength(-1); // Returns: 0 // Convert string numbers toLength('42'); // Returns: 42 // Very large numbers are limited to the maximum value toLength(Number.MAX_VALUE); // Returns: 4294967295 ``` null or undefined are converted to 0. ```typescript import { toLength } from 'es-toolkit/compat'; toLength(null); // Returns: 0 toLength(undefined); // Returns: 0 ``` #### Parameters * `value` (`unknown`): The value to convert. #### Returns (`number`): Returns a valid array index between 0 and 2^32-1. --- --- url: /reference/compat/string/toLower.md --- # toLower (Lodash compatibility) ::: warning Use JavaScript's `String.prototype.toLowerCase` This `toLower` function operates slowly due to handling non-string values. Use JavaScript's `String.prototype.toLowerCase` instead, which is faster and more modern. ::: Converts a value to a string and then transforms it to lowercase. ```typescript const lowercased = toLower(value); ``` ## Usage ### `toLower(value?)` Use `toLower` when you want to convert a value to a lowercase string. It first converts any type of value to a string and then transforms it to lowercase. ```typescript import { toLower } from 'es-toolkit/compat'; // Convert string to lowercase toLower('--FOO-BAR--'); // Returns: '--foo-bar--' toLower('Hello World'); // Returns: 'hello world' // Convert number toLower(123); // Returns: '123' // Convert array toLower([1, 2, 3]); // Returns: '1,2,3' ``` `null` or `undefined` are treated as empty strings. ```typescript import { toLower } from 'es-toolkit/compat'; toLower(null); // Returns: '' toLower(undefined); // Returns: '' toLower(); // Returns: '' ``` #### Parameters * `value` (`unknown`, optional): The value to convert to lowercase. #### Returns (`string`): Returns the lowercased string. --- --- url: /reference/object/toMerged.md --- # toMerged Returns a new object with the source object deeply merged into a copy of the target object. ```typescript const result = toMerged(target, source); ``` ## Usage ### `toMerged(target, source)` Use `toMerged` when you want to deeply merge two objects but don't want to modify the original object. Unlike [merge](./merge.md), this function does not modify the original `target` object and returns a new object. ```typescript import { toMerged } from 'es-toolkit/object'; // Basic object merging const target = { a: 1, b: { x: 1, y: 2 } }; const source = { b: { y: 3, z: 4 }, c: 5 }; const result = toMerged(target, source); // result is { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } // target remains { a: 1, b: { x: 1, y: 2 } } // Arrays are also merged const arrayTarget = { a: [1, 2], b: { x: 1 } }; const arraySource = { a: [3], b: { y: 2 } }; const arrayResult = toMerged(arrayTarget, arraySource); // arrayResult is { a: [3, 2], b: { x: 1, y: 2 } } // arrayTarget is not modified // null values are handled appropriately const nullTarget = { a: null }; const nullSource = { a: [1, 2, 3] }; const nullResult = toMerged(nullTarget, nullSource); // nullResult is { a: [1, 2, 3] } ``` `undefined` values do not overwrite existing values. ```typescript const target = { a: 1, b: 2 }; const source = { b: undefined, c: 3 }; const result = toMerged(target, source); // result is { a: 1, b: 2, c: 3 } (b is not overwritten) ``` #### Parameters * `target` (`T extends Record`): The target object to be merged. This object is not modified. * `source` (`S extends Record`): The source object to merge into the target object. #### Returns (`T & S`): Returns a new object with the target and source objects merged. ## Demo ::: sandpack ```ts index.ts import { toMerged } from 'es-toolkit'; const target = { a: 1, b: { x: 1, y: 2 } }; const source = { b: { y: 3, z: 4 }, c: 5 }; const result = toMerged(target, source); console.log(result); ``` ::: --- --- url: /reference/compat/util/toNumber.md --- # toNumber (Lodash Compatibility) ::: warning Use Number constructor instead This `toNumber` function performs slowly due to symbol type validation and additional processing. Use the faster and more modern Number constructor instead. ::: Converts a value to a number. ```typescript const number = toNumber(value); ``` ## Usage ### `toNumber(value)` Converts a value to a number. Symbols are treated as NaN. ```typescript import { toNumber } from 'es-toolkit/compat'; // Regular numbers are returned as is toNumber(3.2); // Returns: 3.2 // Convert string numbers toNumber('3.2'); // Returns: 3.2 // Infinity is also returned as is toNumber(Infinity); // Returns: Infinity // Very small numbers are also returned as is toNumber(Number.MIN_VALUE); // Returns: 5e-324 ``` Symbols and NaN are converted to NaN. ```typescript import { toNumber } from 'es-toolkit/compat'; toNumber(Symbol.iterator); // Returns: NaN toNumber(NaN); // Returns: NaN ``` #### Parameters * `value` (`unknown`): The value to convert. #### Returns (`number`): Returns the converted number. --- --- url: /reference/compat/object/toPairs.md --- # toPairs (Lodash Compatibility) ::: warning Use `Object.entries` instead This `toPairs` function operates slowly due to complex logic for handling `Map` and `Set`, array-like object processing, etc. Use faster and more modern `Object.entries()` instead. ::: Converts an object to an array of key-value pairs. ```typescript const pairs = toPairs(object); ``` ## Usage ### `toPairs(object)` Use `toPairs` when you want to convert an object's own enumerable properties to an array of `[key, value]` pairs. Inherited properties are not included. ```typescript import { toPairs } from 'es-toolkit/compat'; // Basic object conversion const object = { a: 1, b: 2, c: 3 }; toPairs(object); // => [['a', 1], ['b', 2], ['c', 3]] // Object with numeric keys const numbers = { 0: 'zero', 1: 'one', 2: 'two' }; toPairs(numbers); // => [['0', 'zero'], ['1', 'one'], ['2', 'two']] ``` Can also handle `Map` and `Set`. ```typescript import { toPairs } from 'es-toolkit/compat'; // Map object conversion const map = new Map(); map.set('name', 'John'); map.set('age', 30); toPairs(map); // => [['name', 'John'], ['age', 30]] // Set object conversion (value is the same as key) const set = new Set([1, 2, 3]); toPairs(set); // => [[1, 1], [2, 2], [3, 3]] ``` Safely handles `null` or `undefined`. ```typescript import { toPairs } from 'es-toolkit/compat'; toPairs(null); // => [] toPairs(undefined); // => [] ``` #### Parameters * `object` (`object`): The object, Map, or Set to convert. #### Returns (`Array<[string, any]>`): Returns an array of key-value pairs. --- --- url: /reference/compat/object/toPairsIn.md --- # toPairsIn (Lodash Compatibility) ::: warning Use `Object.entries` or `for...in` loop instead This `toPairsIn` function operates slowly due to complex logic for handling inherited properties, `Map` and `Set` processing, etc. Use faster and more modern `Object.entries()` or a `for...in` loop if you need inherited properties. ::: Converts an object to an array of key-value pairs, including inherited properties. ```typescript const pairs = toPairsIn(object); ``` ## Usage ### `toPairsIn(object)` Use `toPairsIn` when you want to convert all enumerable properties of an object (including inherited properties) to an array of `[key, value]` pairs. Unlike `toPairs`, properties in the prototype chain are also included. ```typescript import { toPairsIn } from 'es-toolkit/compat'; // Basic object conversion const object = { a: 1, b: 2 }; toPairsIn(object); // => [['a', 1], ['b', 2]] // Include inherited properties function Parent() { this.inherited = 'value'; } Parent.prototype.proto = 'property'; const child = new Parent(); child.own = 'own'; toPairsIn(child); // => [['inherited', 'value'], ['own', 'own'], ['proto', 'property']] ``` Can also handle `Map` and `Set`. ```typescript import { toPairsIn } from 'es-toolkit/compat'; // Map object conversion const map = new Map([ ['key1', 'value1'], ['key2', 'value2'], ]); toPairsIn(map); // => [['key1', 'value1'], ['key2', 'value2']] // Set object conversion const set = new Set([1, 2, 3]); toPairsIn(set); // => [[1, 1], [2, 2], [3, 3]] ``` #### Parameters * `object` (`object`): The object, Map, or Set to convert. #### Returns (`Array<[string, any]>`): Returns an array of key-value pairs (including inherited properties). --- --- url: /reference/compat/util/toPath.md --- # toPath (Lodash Compatibility) Converts a deep key string to a path array. ```typescript const path = toPath(deepKey); ``` ## Usage ### `toPath(deepKey)` Converts a deep key string to a path array. Supports both dot notation and bracket notation. ```typescript import { toPath } from 'es-toolkit/compat'; // Dot notation toPath('a.b.c'); // Returns: ['a', 'b', 'c'] // Bracket notation toPath('a[b][c]'); // Returns: ['a', 'b', 'c'] // Mixed notation toPath('a.b[c].d'); // Returns: ['a', 'b', 'c', 'd'] // Quoted keys toPath('a["b.c"].d'); // Returns: ['a', 'b.c', 'd'] ``` It also handles leading dots and empty keys. ```typescript import { toPath } from 'es-toolkit/compat'; // Leading dot toPath('.a.b.c'); // Returns: ['', 'a', 'b', 'c'] // Empty string toPath(''); // Returns: [] // Complex path toPath('.a[b].c.d[e]["f.g"].h'); // Returns: ['', 'a', 'b', 'c', 'd', 'e', 'f.g', 'h'] ``` #### Parameters * `deepKey` (`any`): The deep key string to convert to a path array. #### Returns (`string[]`): Returns an array of strings representing each part of the path. --- --- url: /reference/compat/util/toPlainObject.md --- # toPlainObject (Lodash Compatibility) ::: warning Use Object.assign or spread operator instead This `toPlainObject` function performs slowly due to complex prototype handling and key enumeration. Use the faster and more modern Object.assign({}, obj) or {...obj} instead. ::: Converts a value to a plain object. ```typescript const plainObj = toPlainObject(value); ``` ## Usage ### `toPlainObject(value)` Converts a value to a plain object. Flattens inherited enumerable string key properties to own properties. ```typescript import { toPlainObject } from 'es-toolkit/compat'; // Constructor function and prototype function Foo() { this.b = 2; } Foo.prototype.c = 3; const foo = new Foo(); toPlainObject(foo); // Returns: { b: 2, c: 3 } // Convert array to object toPlainObject([1, 2, 3]); // Returns: { 0: 1, 1: 2, 2: 3 } ``` It handles various object types. ```typescript import { toPlainObject } from 'es-toolkit/compat'; // Convert string to object toPlainObject('abc'); // Returns: { 0: 'a', 1: 'b', 2: 'c' } // Already plain object const obj = { a: 1, b: 2 }; toPlainObject(obj); // Returns: { a: 1, b: 2 } ``` #### Parameters * `value` (`any`): The value to convert. #### Returns (`any`): Returns a plain object with inherited enumerable properties flattened to own properties. --- --- url: /reference/compat/util/toSafeInteger.md --- # toSafeInteger (Lodash Compatibility) Converts a value to a safe integer. ```typescript const result = toSafeInteger(value); ``` ## Usage ### `toSafeInteger(value)` Use `toSafeInteger` when you want to convert a value to a safe integer. A safe integer is an integer that can be accurately represented in JavaScript, within the range of `Number.MIN_SAFE_INTEGER` and `Number.MAX_SAFE_INTEGER`. ```typescript import { toSafeInteger } from 'es-toolkit/compat'; toSafeInteger(3.2); // Returns: 3 toSafeInteger(Infinity); // Returns: 9007199254740991 toSafeInteger('3.2'); // Returns: 3 // String conversion toSafeInteger('abc'); // Returns: 0 // Handle special values toSafeInteger(NaN); // Returns: 0 toSafeInteger(null); // Returns: 0 toSafeInteger(undefined); // Returns: 0 ``` Infinity values are also limited to the safe range. ```typescript import { toSafeInteger } from 'es-toolkit/compat'; toSafeInteger(-Infinity); // Returns: -9007199254740991 (Number.MIN_SAFE_INTEGER) toSafeInteger(Number.MAX_VALUE); // Returns: 9007199254740991 ``` Useful when using as array indices or ID values. ```typescript import { toSafeInteger } from 'es-toolkit/compat'; function getArrayItem(arr: any[], index: any) { const safeIndex = toSafeInteger(index); return arr[safeIndex]; } const items = ['a', 'b', 'c', 'd', 'e']; console.log(getArrayItem(items, '2.7')); // 'c' (index 2) console.log(getArrayItem(items, Infinity)); // undefined (out of range) ``` #### Parameters * `value` (`unknown`): The value to convert. #### Returns (`number`): Returns the converted safe integer. --- --- url: /reference/object/toSnakeCaseKeys.md --- # toSnakeCaseKeys Returns a new object with all keys in objects and arrays converted to snake\_case. Snake case is a naming convention where each word in an identifier is written in lowercase and connected with underscores (`_`). For example, it's written as `snake_case`. ```typescript const snakeCased = toSnakeCaseKeys(obj); ``` ## Usage ### `toSnakeCaseKeys(obj)` Use `toSnakeCaseKeys` when you want to convert all keys of an object to snake\_case. Nested objects and objects within arrays are also converted recursively. For example, object keys are converted as follows: * `camelCase` → `snake_case` (e.g. `userId` → `user_id`) * `PascalCase` → `snake_case` (e.g. `UserId` → `user_id`) * `UPPERCASE_KEYS` → `snake_case` (e.g. `FIRST_NAME` → `first_name`, `LAST` → `last`) ```typescript import { toSnakeCaseKeys } from 'es-toolkit/object'; // Basic object conversion const obj = { userId: 1, firstName: 'John', lastName: 'Doe' }; const result = toSnakeCaseKeys(obj); // result is { user_id: 1, first_name: 'John', last_name: 'Doe' } // Objects within arrays are also converted const users = [ { userId: 1, firstName: 'John' }, { userId: 2, firstName: 'Jane' }, ]; const convertedUsers = toSnakeCaseKeys(users); // convertedUsers is [{ user_id: 1, first_name: 'John' }, { user_id: 2, first_name: 'Jane' }] // Nested objects are fully converted const nested = { userData: { userId: 1, contactInfo: { emailAddress: 'john@example.com', phoneNumber: '123-456-7890', }, }, }; const nestedResult = toSnakeCaseKeys(nested); // nestedResult is { // user_data: { // user_id: 1, // contact_info: { // email_address: 'john@example.com', // phone_number: '123-456-7890' // } // } // } ``` #### Parameters * `obj` (`T`): The object, array, or primitive value to convert keys to snake\_case. #### Returns (`ToSnakeCaseKeys`): Returns a new object with all keys converted to snake\_case. --- --- url: /reference/compat/util/toString.md --- # toString (Lodash Compatibility) ::: warning Use String constructor instead This `toString` function performs slowly due to complex array handling and -0 special case processing. Use the faster and more modern String(value) instead. ::: Converts a value to a string. ```typescript const str = toString(value); ``` ## Usage ### `toString(value)` Converts a value to a string. null and undefined become empty strings, and the sign of -0 is preserved. ```typescript import { toString } from 'es-toolkit/compat'; // Basic types toString(null); // Returns: '' toString(undefined); // Returns: '' toString('hello'); // Returns: 'hello' toString(123); // Returns: '123' // Preserve -0 sign toString(-0); // Returns: '-0' ``` Arrays are converted recursively. ```typescript import { toString } from 'es-toolkit/compat'; // Convert array to string toString([1, 2, 3]); // Returns: '1,2,3' // Nested arrays toString([1, [2, 3], 4]); // Returns: '1,2,3,4' // Array containing -0 toString([1, 2, -0]); // Returns: '1,2,-0' // Array containing symbols toString([Symbol('a'), Symbol('b')]); // Returns: 'Symbol(a),Symbol(b)' ``` #### Parameters * `value` (`any`): The value to convert. #### Returns (`string`): Returns the converted string. null and undefined return empty strings. --- --- url: /reference/compat/string/toUpper.md --- # toUpper (Lodash compatibility) ::: warning Use JavaScript's `String.prototype.toUpperCase` This `toUpper` function performs slower due to handling non-string values. Instead, use the faster and more modern JavaScript's `String.prototype.toUpperCase`. ::: Converts a value to a string and then to uppercase. ```typescript const uppercased = toUpper(value); ``` ## Usage ### `toUpper(value?)` Use `toUpper` when you want to convert a value to an uppercase string. It first converts any type of value to a string, then converts it to uppercase. ```typescript import { toUpper } from 'es-toolkit/compat'; // Convert string to uppercase toUpper('--foo-bar--'); // Returns: '--FOO-BAR--' toUpper('Hello World'); // Returns: 'HELLO WORLD' // Convert number toUpper(123); // Returns: '123' // Convert array toUpper([1, 2, 3]); // Returns: '1,2,3' ``` `null` and `undefined` are treated as empty strings. ```typescript import { toUpper } from 'es-toolkit/compat'; toUpper(null); // Returns: '' toUpper(undefined); // Returns: '' toUpper(); // Returns: '' ``` #### Parameters * `value` (`unknown`, optional): The value to convert to uppercase. #### Returns (`string`): Returns the uppercase string. --- --- url: /reference/compat/object/transform.md --- # transform (Lodash Compatibility) ::: warning Use `reduce` or `Object.entries` instead This `transform` function operates slowly due to complex internal logic. In most cases, it can be implemented more simply using JavaScript's built-in methods. Use faster and more modern `reduce` or `Object.entries` instead. ::: Iterates over an array or object, accumulating values in an accumulator to create a new value. ```typescript const result = transform(object, iteratee, accumulator); ``` ## Usage ### `transform(object, iteratee, accumulator)` Use `transform` when you want to iterate over each element of an array or object, accumulating values in an accumulator. The iteration stops when the `iteratee` function returns `false`. ```typescript import { transform } from 'es-toolkit/compat'; // Transform an array const numbers = [2, 3, 4]; const doubled = transform( numbers, (acc, value) => { acc.push(value * 2); }, [] ); // Returns: [4, 6, 8] // Transform an object const obj = { a: 1, b: 2, c: 1 }; const grouped = transform( obj, (result, value, key) => { (result[value] || (result[value] = [])).push(key); }, {} ); // Returns: { '1': ['a', 'c'], '2': ['b'] } ``` If accumulator is omitted, an empty array or empty object is automatically created. ```typescript import { transform } from 'es-toolkit/compat'; // Empty array is created for arrays const result1 = transform([1, 2, 3], (acc, value) => { acc.push(value * 2); }); // Returns: [2, 4, 6] // Empty object is created for objects const result2 = transform({ a: 1, b: 2 }, (acc, value, key) => { acc[key] = value * 2; }); // Returns: { a: 2, b: 4 } ``` You can stop the iteration by returning `false` in the `iteratee` function. ```typescript import { transform } from 'es-toolkit/compat'; const numbers = [1, 2, 3, 4, 5]; const result = transform( numbers, (acc, value) => { if (value > 3) { return false; // Stop iteration } acc.push(value * 2); }, [] ); // Returns: [2, 4, 6] (4 and 5 are not processed) ``` If the `iteratee` function is omitted, it returns an empty object or array. ```typescript import { transform } from 'es-toolkit/compat'; const array = [1, 2, 3]; const copy1 = transform(array); // Returns: [] const obj = { a: 1, b: 2 }; const copy2 = transform(obj); // Returns: {} ``` #### Parameters * `object` (`readonly T[] | T`, optional): The array or object to iterate over. * `iteratee` (`(accumulator: U, value: T | T[keyof T], key: any, object: readonly T[] | T) => unknown`, optional): The function to execute for each element. Returning `false` stops the iteration. Default is the `identity` function. * `accumulator` (`U`, optional): The initial value. If omitted, an empty array is created for arrays, and an empty object for objects. #### Returns (`U | any[] | Record`): Returns the accumulated result. --- --- url: /reference/string/trim.md --- # trim Removes whitespace or specified characters from the beginning and end of a string. ```typescript const trimmed = trim(str, chars); ``` ## Usage ### `trim(str, chars?)` Use `trim` when you want to remove unnecessary characters from the start and end of a string. If no specific characters are specified, it removes whitespace characters. ```typescript import { trim } from 'es-toolkit/string'; // Basic whitespace removal trim(' hello '); // 'hello' trim('\t\n hello \r\n'); // 'hello' // Removing specific characters trim('--hello--', '-'); // 'hello' trim('***hello***', '*'); // 'hello' // Removing if any of multiple characters match trim('##hello##world##', ['#', 'd']); // 'hello##worl' ``` When you specify multiple characters as an array, all characters that match any of them are removed. ```typescript import { trim } from 'es-toolkit/string'; // Specifying multiple characters as an array trim('!!@@hello@@!!', ['!', '@']); // 'hello' // Removing numbers and special characters trim('123abc123', ['1', '2', '3']); // 'abc' // Removing characters and spaces together trim(' __hello__ ', ['_', ' ']); // 'hello' ``` #### Parameters * `str` (`string`): The string to remove characters from the beginning and end. * `chars` (`string | string[]`, optional): The characters to remove. Can use a string or character array. Defaults to whitespace characters. #### Returns (`string`): Returns a new string with the specified characters removed from the beginning and end. --- --- url: /reference/compat/string/trim.md --- # trim (Lodash Compatibility) ::: warning Use `trim` from `es-toolkit` This `trim` function operates slowly due to handling `null` or `undefined` and array-type `chars`. Use the faster and more modern [trim](../../string/trim.md) from `es-toolkit` instead. ::: Removes leading and trailing whitespace or specified characters from a string. ```typescript const trimmed = trim(str, chars); ``` ## Usage ### `trim(str, chars)` Use `trim` when you want to remove whitespace or specific characters from the beginning and end of a string. If `chars` is not specified, only leading and trailing whitespace will be removed. ```typescript import { trim } from 'es-toolkit/compat'; // Remove leading and trailing whitespace trim(' hello '); // Returns: 'hello' // Remove specified characters trim('--hello--', '-'); // Returns: 'hello' // Remove multiple characters with an array trim('##hello##', ['#', 'o']); // Returns: 'hell' ``` `null` or `undefined` is treated as an empty string. ```typescript import { trim } from 'es-toolkit/compat'; trim(null); // '' trim(undefined); // '' ``` #### Parameters * `str` (`string`, optional): The string to trim. * `chars` (`string`, optional): The characters to remove. If not specified, whitespace will be removed. #### Returns (`string`): Returns the string with specified characters removed from the beginning and end. --- --- url: /reference/string/trimEnd.md --- # trimEnd Removes whitespace or specified characters from the end of a string. ```typescript const trimmed = trimEnd(str, chars); ``` ## Usage ### `trimEnd(str, chars?)` Use `trimEnd` when you want to remove unnecessary characters from the end of a string. If no specific characters are specified, it removes whitespace characters. ```typescript import { trimEnd } from 'es-toolkit/string'; // Basic whitespace removal trimEnd('hello '); // 'hello' trimEnd('hello\t\n '); // 'hello' // Removing specific characters trimEnd('hello---', '-'); // 'hello' trimEnd('123000', '0'); // '123' trimEnd('abcabcabc', 'c'); // 'abcabcab' ``` When you specify multiple characters as an array, all characters that match any of them will be removed. ```typescript import { trimEnd } from 'es-toolkit/string'; // Specifying multiple characters as an array trimEnd('hello!!@@', ['!', '@']); // 'hello' // Removing numbers and special characters trimEnd('abc123', ['1', '2', '3']); // 'abc' // Removing characters and whitespace together trimEnd('hello__ ', ['_', ' ']); // 'hello' ``` #### Parameters * `str` (`string`): The string from which to remove characters from the end. * `chars` (`string | string[]`, optional): The characters to remove. Can be a string or an array of characters. Defaults to whitespace characters. #### Returns (`string`): Returns a new string with the specified characters removed from the end. #### Errors Throws an error if `chars` is a string with a length other than 1. --- --- url: /reference/compat/string/trimEnd.md --- # trimEnd (Lodash Compatibility) ::: warning Use `trimEnd` from `es-toolkit` This `trimEnd` function operates slowly due to handling `null` or `undefined` and parameter order changes. Use the faster and more modern [trimEnd](../../string/trimEnd.md) from `es-toolkit` instead. ::: Removes trailing whitespace or specified characters from a string. ```typescript const trimmed = trimEnd(str, chars); ``` ## Usage ### `trimEnd(str, chars)` Use `trimEnd` when you want to remove whitespace or specific characters from the end of a string. If `chars` is not specified, only trailing whitespace will be removed. ```typescript import { trimEnd } from 'es-toolkit/compat'; // Remove trailing whitespace trimEnd(' abc '); // Returns: ' abc' // Remove specified characters trimEnd('-_-abc-_-', '_-'); // Returns: '-_-abc' // Only applies to the end of the string trimEnd('abc', 'a'); // Returns: 'abc' ``` `null` or `undefined` is treated as an empty string. ```typescript import { trimEnd } from 'es-toolkit/compat'; trimEnd(null); // '' trimEnd(undefined); // '' ``` #### Parameters * `str` (`string`, optional): The string to trim from the end. * `chars` (`string`, optional): The characters to remove. If not specified, whitespace will be removed. #### Returns (`string`): Returns the string with specified characters removed from the end. --- --- url: /reference/string/trimStart.md --- # trimStart Removes whitespace or specified characters from the start of a string. ```typescript const trimmed = trimStart(str, chars); ``` ## Usage ### `trimStart(str, chars?)` Use `trimStart` when you want to remove unnecessary characters from the beginning of a string. If no specific characters are specified, it removes whitespace characters. ```typescript import { trimStart } from 'es-toolkit/string'; // Remove default whitespace trimStart(' hello'); // 'hello' trimStart('\t\n hello'); // 'hello' // Remove specific characters trimStart('---hello', '-'); // 'hello' trimStart('000123', '0'); // '123' trimStart('abcabcabc', 'a'); // 'bcabcabc' ``` If you specify multiple characters as an array, all characters matching any of them will be removed. ```typescript import { trimStart } from 'es-toolkit/string'; // Specify multiple characters as an array trimStart('!!@@hello', ['!', '@']); // 'hello' // Remove numbers and special characters trimStart('123abc', ['1', '2', '3']); // 'abc' // Remove characters and whitespace together trimStart(' __hello', ['_', ' ']); // 'hello' ``` #### Parameters * `str` (`string`): The string to remove characters from the start. * `chars` (`string | string[]`, optional): The characters to remove. Can be a string or an array of characters. Defaults to whitespace characters. #### Returns (`string`): Returns a new string with the specified characters removed from the start. --- --- url: /reference/compat/string/trimStart.md --- # trimStart (Lodash Compatibility) ::: warning Use `trimStart` from `es-toolkit` This `trimStart` function operates slowly due to handling `null` or `undefined` and parameter order changes. Use the faster and more modern [trimStart](../../string/trimStart.md) from `es-toolkit` instead. ::: Removes leading whitespace or specified characters from a string. ```typescript const trimmed = trimStart(str, chars); ``` ## Usage ### `trimStart(str, chars)` Use `trimStart` when you want to remove whitespace or specific characters from the beginning of a string. If `chars` is not specified, only leading whitespace will be removed. ```typescript import { trimStart } from 'es-toolkit/compat'; // Remove leading whitespace trimStart(' abc '); // Returns: 'abc ' // Remove specified characters trimStart('-_-abc-_-', '_-'); // Returns: 'abc-_-' // Only applies to the beginning of the string trimStart('abc', 'c'); // Returns: 'abc' ``` `null` or `undefined` is treated as an empty string. ```typescript import { trimStart } from 'es-toolkit/compat'; trimStart(null); // '' trimStart(undefined); // '' ``` #### Parameters * `str` (`string`, optional): The string to trim from the beginning. * `chars` (`string`, optional): The characters to remove. If not specified, whitespace will be removed. #### Returns (`string`): Returns the string with specified characters removed from the beginning. --- --- url: /reference/compat/string/truncate.md --- # truncate (Lodash Compatibility) ::: warning Use JavaScript's `String.prototype.slice` This `truncate` function operates slowly due to complex Unicode handling and regex checking. Use the faster and more modern JavaScript's `String.prototype.slice` instead. ::: Truncates a string if it's longer than the specified maximum length and appends an omission string. ```typescript const truncated = truncate(str, options); ``` ## Usage ### `truncate(string, options?)` Use `truncate` when you want to cut a long string to a specified length. The truncated part is replaced with an omission string (default: `"..."`). ```typescript import { truncate } from 'es-toolkit/compat'; // Basic usage (max 30 characters) truncate('hi-diddly-ho there, neighborino'); // Returns: 'hi-diddly-ho there, neighbo...' // Specify length truncate('hi-diddly-ho there, neighborino', { length: 24 }); // Returns: 'hi-diddly-ho there, n...' // Change omission string truncate('hi-diddly-ho there, neighborino', { omission: ' [...]' }); // Returns: 'hi-diddly-ho there, neig [...]' ``` You can specify a separator to truncate at that position. ```typescript import { truncate } from 'es-toolkit/compat'; // Truncate at word boundaries with space separator truncate('hi-diddly-ho there, neighborino', { length: 24, separator: ' ', }); // Returns: 'hi-diddly-ho there,...' // Specify separator with regex truncate('hi-diddly-ho there, neighborino', { length: 24, separator: /,? +/, }); // Returns: 'hi-diddly-ho there...' ``` Unicode characters are also handled correctly. ```typescript import { truncate } from 'es-toolkit/compat'; truncate('¥§✈✉🤓', { length: 5 }); // Returns: '¥§✈✉🤓' truncate('¥§✈✉🤓', { length: 4, omission: '…' }); // Returns: '¥§✈…' ``` #### Parameters * `string` (`string`, optional): The string to truncate. * `options` (`object`, optional): The options object. * `options.length` (`number`, optional): The maximum string length. Defaults to `30`. * `options.omission` (`string`, optional): The string to indicate text is omitted. Defaults to `'...'`. * `options.separator` (`RegExp | string`, optional): The separator pattern to truncate to. #### Returns (`string`): Returns the truncated string. --- --- url: /reference/function/unary.md --- # unary Creates a new function that limits a function to accept only the first parameter. ```typescript const unaryFunc = unary(func); ``` ## Usage ### `unary(func)` Use `unary` when you want to limit a function to accept only one parameter. Any additional parameters passed are ignored. This is useful for preventing callback functions from receiving more parameters than expected in array methods like `map`, `filter`, and `forEach`. ```typescript import { unary } from 'es-toolkit/function'; // Basic usage function greet(name: string, age?: number, city?: string) { console.log(`Hello, ${name}!`); if (age) console.log(`Age: ${age}`); if (city) console.log(`City: ${city}`); } const greetOnlyName = unary(greet); greetOnlyName('Cheolsu', 25, 'Seoul'); // Only logs 'Hello, Cheolsu!' // Using with array methods const numbers = ['1', '2', '3', '4', '5']; // parseInt accepts radix as a second parameter, // but map's callback passes (value, index, array) console.log(numbers.map(parseInt)); // [1, NaN, NaN, NaN, NaN] (unexpected result) // Use unary to pass only the first parameter console.log(numbers.map(unary(parseInt))); // [1, 2, 3, 4, 5] (expected result) // Another example: when a function accepts multiple parameters but you want to use only one function logValue(value: any, prefix: string = 'Value:', suffix: string = '') { console.log(`${prefix} ${value} ${suffix}`); } const data = ['apple', 'banana', 'cherry']; // When you want to log only the value without prefix and suffix data.forEach(unary(logValue)); // Value: apple // Value: banana // Value: cherry ``` It's also useful in function composition. ```typescript import { unary } from 'es-toolkit/function'; // Function that accepts multiple parameters function multiply(a: number, b: number = 1, c: number = 1) { return a * b * c; } // Limit to use only the first parameter const multiplyOne = unary(multiply); const numbers = [1, 2, 3, 4, 5]; const doubled = numbers.map(x => multiplyOne(x, 2, 3)); // b and c are ignored console.log(doubled); // [1, 2, 3, 4, 5] (result of 1 * 1 * 1) ``` #### Parameters * `func` (`F`): The function to limit to accept only the first parameter. #### Returns (`(...args: any[]) => ReturnType`): Returns a new function that passes only the first parameter to the original function. --- --- url: /reference/compat/function/unary.md --- # unary (Lodash Compatibility) ::: warning Use `ary` from `es-toolkit` instead This `unary` function is implemented as a special case of the `ary` function. If you need more control, it's more efficient to use [ary](../../function/ary.md) from `es-toolkit` directly. Use faster, more modern [ary](../../function/ary.md) from `es-toolkit` instead. ::: Limits a function to accept at most one argument. ```typescript const limitedFunc = unary(func); ``` ## Usage ### `unary(func)` Use `unary` when you want to limit a function to accept at most one argument. Any additional arguments passed will be ignored. ```typescript import { unary } from 'es-toolkit/compat'; function greet(name, greeting, punctuation) { return `${greeting} ${name}${punctuation}`; } // Convert to a function that accepts only the first argument const greetOne = unary(greet); greetOne('Alice', 'Hello', '!'); // Works the same as greet('Alice') // Useful when used with array's map function const numbers = ['1', '2', '3']; numbers.map(parseInt); // [1, NaN, NaN] - unexpected result numbers.map(unary(parseInt)); // [1, 2, 3] - correct result ``` #### Parameters * `func` (`(...args: any[]) => any`): The function to limit arguments for. #### Returns (`(...args: any[]) => any`): Returns a new function that accepts at most one argument. --- --- url: /reference/string/unescape.md --- # unescape Converts HTML entity characters to their original characters. ```typescript const result = unescape(str); ``` ## Usage ### `unescape(str)` Use `unescape` when you want to convert HTML entity characters back to their original characters. It converts HTML entities like `&`, `<`, `>`, `"`, `'` to `&`, `<`, `>`, `"`, `'` characters. This is the inverse operation of the [`escape`](./escape.md) function. ```typescript import { unescape } from 'es-toolkit/string'; // Convert HTML tag entities to original characters unescape('This is a <div> element.'); // Returns: 'This is a
    element.' // Convert quote entities to original characters unescape('This is a "quote"'); // Returns: 'This is a "quote"' // Convert single quote entities to original characters unescape('This is a 'quote''); // Returns: 'This is a 'quote'' // Convert ampersand entities to original characters unescape('This is a & symbol'); // Returns: 'This is a & symbol' ``` Useful when processing data from HTML forms or URLs: ```typescript // Convert HTML entities from user input const userInput = 'My favorite tag is <button>'; const converted = unescape(userInput); console.log(converted); // 'My favorite tag is