### Get Started with es-toolkit Guide Skill Source: https://github.com/toss/es-toolkit/blob/main/es-toolkit-plugin/README.md Use the guide skill to get installation, import patterns, and setup instructions for various environments. ```bash /es-toolkit:guide install /es-toolkit:guide How do I use es-toolkit in Deno? /es-toolkit:guide What import style is best for tree shaking? ``` -------------------------------- ### Interactive startCase Example Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/string/startCase.md An interactive example demonstrating the startCase function with a sample input. ```typescript import { startCase } from 'es-toolkit/string'; console.log(startCase('startCase')); ``` -------------------------------- ### Install es-toolkit for Bun Source: https://github.com/toss/es-toolkit/blob/main/docs/usage.md Use this command to install es-toolkit in your Bun project. ```sh bun add es-toolkit ``` -------------------------------- ### Usage Examples Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/predicate/isPromise.md Illustrative examples demonstrating how to use the `isPromise` function in various scenarios. ```APIDOC ## Usage Examples ### Basic Usage ```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 ``` ### Conditional Logic in Async Functions ```typescript 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; } ``` ### Handling API Responses ```typescript 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 }; } ``` ### Utility Function `toPromise` ```typescript function toPromise(value: T | Promise): Promise { if (isPromise(value)) { return value; } return Promise.resolve(value); } ``` ### Distinguishing Promises from Thenable Objects ```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 ``` ### Error Handling with `isPromise` ```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 with `isPromise` ```typescript 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]); } ``` ``` -------------------------------- ### es-toolkit Agent Skills Usage Examples Source: https://github.com/toss/es-toolkit/blob/main/docs/ai-integration.md Examples of how to invoke es-toolkit Agent Skills for guidance, recommendations, and code migration. ```shell /es-toolkit:guide How do I use es-toolkit in Deno? ``` ```shell /es-toolkit:recommend I need to deeply merge two objects ``` ```shell /es-toolkit:migrate _.chunk(users, 10) ``` -------------------------------- ### Interactive String Reversal Example Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/string/reverseString.md An interactive example demonstrating the reverseString function using a Sandpack environment. ```typescript import { reverseString } from 'es-toolkit'; console.log(reverseString('hello')); ``` -------------------------------- ### Install Dependencies and Run Tests with Yarn Source: https://github.com/toss/es-toolkit/blob/main/AGENTS.md Set up the development environment by enabling Corepack, installing dependencies with Yarn, and running common commands like tests, linting, and type checking. ```bash corepack enable yarn install ``` ```bash yarn vitest run yarn vitest run src/array/chunk yarn lint tsc --noEmit ``` -------------------------------- ### Install es-toolkit with yarn Source: https://github.com/toss/es-toolkit/blob/main/docs/usage.md Use this command to install es-toolkit in your Node.js project via yarn. ```sh yarn add es-toolkit ``` -------------------------------- ### Example function import and usage Source: https://github.com/toss/es-toolkit/blob/main/es-toolkit-plugin/skills/recommend/SKILL.md Demonstrates the standard import path for es-toolkit functions and provides a placeholder for a code example. This structure is used when recommending a specific function. ```javascript import { fn } from 'es-toolkit'; ``` -------------------------------- ### Install es-toolkit with npm/yarn/pnpm/bun Source: https://github.com/toss/es-toolkit/blob/main/es-toolkit-plugin/skills/guide/SKILL.md Install es-toolkit using the appropriate command for your package manager. The command varies based on whether you are using npm, yarn, pnpm, or bun. ```bash npm install es-toolkit ``` ```bash yarn add es-toolkit ``` ```bash pnpm install es-toolkit ``` ```bash bun add es-toolkit ``` -------------------------------- ### Interactive Chunk Example Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/array/chunk.md Demonstrates the `chunk` function with an example array and chunk size. Requires importing `chunk` from 'es-toolkit/array'. ```typescript import { chunk } from 'es-toolkit/array'; console.log(chunk([1, 2, 3, 4, 5], 2)); ``` -------------------------------- ### Interactive mergeWith example Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/object/mergeWith.md An interactive example to experiment with mergeWith, demonstrating number addition. ```typescript 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); ``` -------------------------------- ### Install es-toolkit with npm Source: https://github.com/toss/es-toolkit/blob/main/docs/usage.md Use this command to install es-toolkit in your Node.js project via npm. ```sh npm install es-toolkit ``` -------------------------------- ### Interactive Combinations Example Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/array/combinations.md An interactive example to test the combinations function with custom inputs. ```typescript import { combinations } from 'es-toolkit/array'; console.log(combinations(['A', 'B', 'C', 'D'], 2)); ``` -------------------------------- ### Install es-toolkit for Deno Source: https://github.com/toss/es-toolkit/blob/main/docs/usage.md Use this command to add es-toolkit to your Deno project from JSR. ```sh deno add jsr:@es-toolkit/es-toolkit ``` -------------------------------- ### Install es-toolkit with pnpm Source: https://github.com/toss/es-toolkit/blob/main/docs/usage.md Use this command to install es-toolkit in your Node.js project via pnpm. ```sh pnpm add es-toolkit ``` -------------------------------- ### Interactive Cartesian Product Example Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/array/cartesianProduct.md An interactive example demonstrating the `cartesianProduct` function with sample inputs. Requires importing `cartesianProduct` from 'es-toolkit/array'. ```ts import { cartesianProduct } from 'es-toolkit/array'; console.log(cartesianProduct([1, 2], ['a', 'b'])); ``` -------------------------------- ### Install es-toolkit Agent Skills Source: https://github.com/toss/es-toolkit/blob/main/docs/ai-integration.md Use npx to add the es-toolkit Agent Skill for most AI tools, or use the Claude Code plugin commands for specific installation. ```sh npx skills add toss/es-toolkit ``` ```sh /plugin marketplace add toss/es-toolkit /plugin install es-toolkit@es-toolkit-plugin ``` -------------------------------- ### Basic Usage Examples Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/function/retry.md Illustrates various ways to use the retry function. ```APIDOC ```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), } ); ``` ``` -------------------------------- ### Basic nthArg usage example Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/function/nthArg.md This example demonstrates the basic creation of a wrapper function using nthArg to retrieve a specific argument. ```typescript const getNthArg = nthArg(n); ``` -------------------------------- ### Interactive Object Merge Example Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/object/merge.md An interactive example using Sandpack to demonstrate the `merge` function. It allows for live experimentation with object merging. ```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); ``` -------------------------------- ### Basic Shuffle Example Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/array/shuffle.md Demonstrates the basic usage of the shuffle function with an array. ```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) ``` -------------------------------- ### Project Setup and Testing Commands Source: https://github.com/toss/es-toolkit/blob/main/CLAUDE.md Essential bash commands for setting up the project, running tests, linting, and type-checking. ```bash corepack enable && yarn install # Setup ``` ```bash yarn vitest run # Tests ``` ```bash yarn vitest run src/array/chunk # Test specific function ``` ```bash yarn lint # ESLint ``` ```bash tsc --noEmit # Typecheck ``` -------------------------------- ### Get a random element from an array or object Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/array/sample.md This is a basic usage example demonstrating how to get a random item from a collection. ```typescript const randomItem = sample(collection); ``` -------------------------------- ### Get First Element of Array Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/array/head.md Retrieves the first element from a given array. This is a basic usage example. ```typescript const firstElement = head(array); ``` -------------------------------- ### Filter properties by key name Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/object/omitBy.md Excludes properties from an object where the key starts with a specified prefix, 'admin' in this example. ```typescript import { omitBy } from 'es-toolkit/compat'; // 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 } ``` -------------------------------- ### Local Development Setup for es-toolkit Plugin Source: https://github.com/toss/es-toolkit/blob/main/es-toolkit-plugin/README.md Run this command to set up the es-toolkit plugin for local development with Claude. ```bash claude --plugin-dir ./es-toolkit-plugin ``` -------------------------------- ### dropWhile Example with pipe Source: https://github.com/toss/es-toolkit/blob/main/docs/fp/reference/dropWhile.md Demonstrates how `dropWhile` removes elements from the start of an array until the predicate returns false. This variant is lazy-capable when used inside `pipe`. ```typescript import { dropWhile, pipe } from 'es-toolkit/fp'; pipe( [1, 2, 3, 1], dropWhile(value => value < 3) ); // => [3, 1] ``` -------------------------------- ### startsWith with Position Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/string/startsWith.md You can specify a starting position to check if the string begins with the target from that point onwards. This example shows how to use the optional `position` parameter. ```typescript import { startsWith } from 'es-toolkit/compat'; // Check from a specific position startsWith('fooBar', 'Bar', 3); // Returns: true (checks if it starts with 'Bar' from position 3) ``` -------------------------------- ### keysIn Basic Usage Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/object/keysIn.md Use keysIn to get all property names of an object, including inherited properties. This example shows basic object keys. ```typescript import { keysIn } from 'es-toolkit/compat'; // Keys of a basic object const object = { a: 1, b: 2 }; keysIn(object); // => ['a', 'b'] ``` -------------------------------- ### Understand es-toolkit Strict vs Compat API Source: https://github.com/toss/es-toolkit/blob/main/es-toolkit-plugin/README.md Use the migrate skill with specific keywords to understand the strict vs compat API strategies in es-toolkit. ```bash /es-toolkit:migrate get /es-toolkit:migrate migration strategy ``` -------------------------------- ### Basic startsWith Usage Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/string/startsWith.md Use `startsWith` to check if a string begins with a target string. This example demonstrates basic usage and a case where the string does not start with the target. ```typescript import { startsWith } from 'es-toolkit/compat'; // Check if string starts with target startsWith('fooBar', 'foo'); // Returns: true startsWith('fooBar', 'bar'); // Returns: false ``` -------------------------------- ### Basic startCase Usage Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/string/startCase.md Demonstrates the basic usage of the `startCase` function to convert a string to start case. ```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' ``` -------------------------------- ### Get function names including inherited properties Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/object/functionsIn.md This example shows how `functionsIn` includes inherited functions from the prototype chain. Note that non-enumerable properties are not included. ```typescript import { functionsIn } from 'es-toolkit/compat'; // 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) ``` -------------------------------- ### Basic nth Function Usage Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/array/nth.md Demonstrates how to get an element from an array using a positive index. This is a basic example of the nth function's core functionality. ```typescript import { nth } from 'es-toolkit/compat'; const array = [1, 2, 3, 4, 5]; // Positive index nth(array, 1); // => 2 ``` -------------------------------- ### rangeRight with three arguments (positive step) Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/math/rangeRight.md Generates an array of numbers from start to end, incrementing by the specified step, then reverses the order. This example uses a positive step. ```typescript import { rangeRight } from 'es-toolkit/compat'; rangeRight(0, 8, 2); // Returns: [6, 4, 2, 0] ``` -------------------------------- ### Check if all keys match a pattern Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/map/every.md This example demonstrates using `every` to check if all keys in a settings Map start with a specific prefix. The predicate function utilizes both the value and the key. ```typescript import { every } from 'es-toolkit/map'; // 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 ``` -------------------------------- ### Get all property values from an object Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/object/valuesIn.md Use `valuesIn` to retrieve all property values from an object, including inherited ones. This example shows basic usage with a simple object and an array. ```typescript import { valuesIn } from 'es-toolkit/compat'; const obj = { a: 1, b: 2, c: 3 }; valuesIn(obj); // [1, 2, 3] // Also handles arrays valuesIn([1, 2, 3]); // [1, 2, 3] ``` -------------------------------- ### Check if any key in a Map starts with a specific prefix Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/map/some.md This example shows how to use `some` with a predicate that checks the key of a Map entry. The predicate function `key.startsWith('admin_')` is used to find if any key begins with the specified prefix. ```typescript import { some } from 'es-toolkit/map'; // 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 ``` -------------------------------- ### Basic Color and Style Application Source: https://github.com/toss/es-toolkit/blob/main/docs/server/reference/colors.md Demonstrates how to import and use basic color and style functions from the 'colors' utility to wrap strings. ```typescript import { colors } from 'es-toolkit/server'; console.log(colors.red('error')); console.log(colors.bold(colors.cyan('hello'))); ``` -------------------------------- ### padStart Function Signature Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/string/padStart.md The `padStart` function is used to pad the beginning of a string to a specified length using a given character set. It handles `null` and `undefined` inputs by treating them as empty strings. ```APIDOC ## padStart(str, length?, chars?) ### Description Pads the start of a string to extend it to the specified length. ::: 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`. ::: `null` or `undefined` are treated as empty strings. ### 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. ### Usage Examples ```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' padStart(null, 5, '*'); // Returns: '*****' padStart(undefined, 3); // Returns: ' ' ``` ``` -------------------------------- ### Currying a Sum Function with curryRight Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/function/curryRight.md 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. This example shows how to curry a sum function. ```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 ``` -------------------------------- ### Interactive pascalCase Example Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/string/pascalCase.md Demonstrates the pascalCase function in an interactive environment. This is useful for quick testing and understanding its output. ```typescript import { pascalCase } from 'es-toolkit/string'; console.log(pascalCase('pascalCase')); ``` -------------------------------- ### range(start, end) Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/math/range.md Creates an array of numbers from start to end, incrementing by 1. If start is greater than end, it decrements by -1. ```APIDOC ## range(start, end) ### Description Creates an array of numbers from start to end, incrementing by 1. ### Parameters #### Path Parameters - **start** (number) - Required - The start value of the range. - **end** (number) - Required - The end value of the range. ### Returns (`number[]`): Returns an array of numbers in the specified range. ``` -------------------------------- ### Range with Start and End Values Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/math/range.md Creates an array of numbers from a start value up to (but not including) an end value, incrementing by 1. Automatically decrements if the start value is greater than the end value. ```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] ``` -------------------------------- ### Using Placeholders with Partial Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/function/partial.md Demonstrates how to use `partial.placeholder` to specify which arguments should be applied later, allowing for more flexible argument ordering. ```APIDOC ## Using Placeholders with partial ### Description Adjust the argument order using placeholders. `partial.placeholder` allows you to specify arguments that should be passed later. ### Method N/A (Utility function) ### Endpoint N/A (Utility function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```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] ``` ### Response #### Success Response (200) N/A (Returns a new function) #### Response Example N/A ``` -------------------------------- ### Practical once Function for Initialization Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/function/once.md Illustrates a practical use case for 'once' with an initialization function. The initialization logic runs only on the first call to 'initialize', ensuring that expensive setup operations are performed just once. ```typescript import { once } from 'es-toolkit/compat'; // 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 ``` -------------------------------- ### Initialize app logic once Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/function/once.md Use `once` for initialization functions that should run only one time. This example shows how to initialize an app and ensures the initialization logic runs just once. ```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 ``` -------------------------------- ### differenceBy initial usage with pipe Source: https://github.com/toss/es-toolkit/blob/main/docs/fp/reference/differenceBy.md Shows the initial setup for using `differenceBy` with `pipe` before importing specific functions. This illustrates the conceptual integration. ```typescript const result = pipe(array, differenceBy(secondArray, mapper)); ``` -------------------------------- ### Basic Partial Application Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/function/partial.md Use `partial` to pre-apply arguments to a function. Pre-provided arguments are placed at the front, and later arguments are appended. This example demonstrates creating a `sayHello` function from `greet`. ```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!' ``` -------------------------------- ### MergeWith with array concatenation example Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/object/mergeWith.md An example showing how to concatenate arrays using mergeWith. ```typescript 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] }) ``` -------------------------------- ### Basic ConformsTo Usage Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/predicate/conformsTo.md Demonstrates the basic usage of conformsTo with an object and a set of conditions. Ensure the 'es-toolkit/compat' module is imported. ```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) ``` -------------------------------- ### Basic noop usage Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/function/noop.md Demonstrates the basic usage of the noop function, showing that it accepts arguments but performs no operation. ```typescript import { noop } from 'es-toolkit/compat'; // Basic usage oop(); // Does nothing oop(1, 2, 3); // Accepts arguments but does nothing ``` -------------------------------- ### Basic Partition Usage Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/array/partition.md Demonstrates the fundamental usage of the partition function to split a collection into truthy and falsy groups based on a predicate. ```typescript const [truthy, falsy] = partition(collection, predicate); ``` -------------------------------- ### Basic Array Take Example Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/array/take.md Demonstrates the basic usage of the `take` function to extract a specified number of elements from an array. ```typescript const result = take([1, 2, 3, 4, 5], 3); // result becomes [1, 2, 3]. ``` -------------------------------- ### rangeRight(start, end) Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/math/rangeRight.md Creates an array of numbers from start to end, incrementing by 1, then reverses the order. ```APIDOC ## rangeRight(start, end) ### Description Creates an array of numbers from `start` up to (but not including) `end`, incrementing by 1, and then reverses the order of the elements. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **start** (`number`): The start value of the range (inclusive). - **end** (`number`): The end value of the range (exclusive). ### Returns (`number[]`): Returns an array of numbers in the specified range in reverse order. ### Example ```javascript 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] ``` ``` -------------------------------- ### Practical Placeholder Example for API Requests Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/function/bind.md Shows a practical use case of `bind` with placeholders for creating partially applied functions for API requests. ```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" }); ``` -------------------------------- ### MergeWith with number addition example Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/object/mergeWith.md A simple example demonstrating mergeWith for adding numbers from source to target. ```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 } ``` -------------------------------- ### rangeRight(start, end, step) Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/math/rangeRight.md Creates an array of numbers from start to end, incrementing by step, then reverses the order. ```APIDOC ## rangeRight(start, end, step) ### Description Creates an array of numbers from `start` up to (but not including) `end`, incrementing by `step`, and then reverses the order of the elements. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **start** (`number`): The start value of the range (inclusive). - **end** (`number`): The end value of the range (exclusive). - **step** (`number`, optional): The increment step. Defaults to 1 if `start` < `end`, or -1 if `start` > `end`. ### Returns (`number[]`): Returns an array of numbers in the specified range in reverse order. ### Example ```javascript 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 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] ``` ``` -------------------------------- ### Range with Start, End, and Step Values Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/math/range.md Creates an array of numbers from a start value up to (but not including) an end value, incrementing by a specified step. Handles positive and negative steps, including a step of 0 which results in an array of repeated start values. ```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] ``` -------------------------------- ### rest Function with Different Start Index Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/function/rest.md Shows how to use the 'rest' function with a different 'start' index to group arguments. ```typescript import { rest } from 'es-toolkit/compat'; // 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: [] } ``` -------------------------------- ### Run FP Pipe Benchmarks with Vitest Source: https://github.com/toss/es-toolkit/blob/main/docs/fp/performance.md Execute performance benchmarks for the fp pipe module using Vitest. Ensure you have Vitest installed and the benchmark file is correctly located. ```bash yarn vitest bench performance/fp/pipe.bench.ts --run ``` -------------------------------- ### Importing and Using Color Functions Source: https://github.com/toss/es-toolkit/blob/main/docs/server/reference/colors.md Shows the import statement and examples of applying different color and style functions like red, bold, underline, and cyan. ```typescript import { colors } from 'es-toolkit/server'; colors.red('error'); colors.bold('emphasized'); colors.underline(colors.cyan('link')); ``` -------------------------------- ### Find Last Element with Starting Index Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/array/findLast.md Specify a starting index to begin the reverse search from a particular point in the array. ```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 ``` -------------------------------- ### Import and Use `head` from `es-toolkit/compat` Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/array/head.md Demonstrates how to import and use the `head` function for number arrays, string arrays, and array-like objects. Ensure the `es-toolkit/compat` module is imported. ```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' ``` -------------------------------- ### take(array, count) Usage Examples Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/array/take.md Illustrates various scenarios for the `take` function, including requesting more elements than available, requesting zero elements, handling empty arrays, and using negative counts. Ensure `take` is imported from `es-toolkit/compat`. ```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: [] ``` -------------------------------- ### Slice with negative start and end indices Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/array/slice.md Demonstrates using negative indices for both start and end positions to slice an array from the end. ```typescript import { slice } from 'es-toolkit/compat'; slice([1, 2, 3, 4, 5], -3, -1); // Returns: [3, 4] ``` -------------------------------- ### One-time initialization with before Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/function/before.md This example shows how `before` can be used for tasks that should only run once, like initialization. The function is set to execute a maximum of 1 time (2-1). ```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(); ``` -------------------------------- ### Merge Example with Console Output Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/object/merge.md A practical example of merging objects, showing the final state of the merged object logged to the console. ```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 } ``` -------------------------------- ### Semaphore Usage Example Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/promise/Semaphore.md Demonstrates how to use Semaphore for API rate limiting and file download control. Ensure to import Semaphore from 'es-toolkit'. The acquire method waits for a permit, and release returns it. ```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 ``` -------------------------------- ### Direct argument reversal (recommended alternative) Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/function/flip.md Illustrates the recommended modern approach using spread syntax to reverse arguments, which is generally faster and more readable than using `flip`. ```typescript const flippedFunc = (...args) => func(...args.reverse()) ``` -------------------------------- ### Get Current Time with now() Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/util/now.md Demonstrates how to get the current time in milliseconds using the `now` function. This is useful for time measurement and generating timestamps. ```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`; ``` -------------------------------- ### range(start, end, step) Source: https://github.com/toss/es-toolkit/blob/main/docs/compat/reference/math/range.md Creates an array of numbers from start to end, incrementing by step. Handles positive, negative, and decimal steps. ```APIDOC ## range(start, end, step) ### Description Creates an array of numbers from start to end, incrementing by step. ### Parameters #### Path Parameters - **start** (number) - Required - The start value of the range. - **end** (number) - Required - The end value of the range. - **step** (number) - Optional - The increment step. Defaults to 1 or -1 based on start and end values. ### Returns (`number[]`): Returns an array of numbers in the specified range. ``` -------------------------------- ### Using pick with pipe Source: https://github.com/toss/es-toolkit/blob/main/docs/fp/reference/pick.md Demonstrates the basic usage of `pick` within a `pipe` function composition. ```typescript const result = pipe(obj, pick(keys)); ``` -------------------------------- ### Partial Application with Multiple Arguments Source: https://github.com/toss/es-toolkit/blob/main/docs/reference/function/partial.md You can pre-apply multiple arguments using `partial`. This example shows creating `double` and `doubleAndTriple` functions from `multiply`. ```typescript import { partial } from 'es-toolkit/function'; // 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 ```