# VDL Plugin SDK > SDK to build plugins for VDL using TypeScript # Documentation # VDL Plugin SDK Build VDL plugins in TypeScript with a simple CLI, typed IR access, utility helpers, and test builders for plugin unit tests. [Documentation](https://vdl-plugin-sdk.varavel.com) ยท [API Reference](https://vdl-plugin-sdk.varavel.com/api/core/) ยท [Plugin Template](https://github.com/varavelio/vdl-plugin-template) ## Install In most cases you do not install this manually. The official [`vdl-plugin-template`](https://github.com/varavelio/vdl-plugin-template) already includes the SDK and the recommended project setup. If you are setting up a plugin project from scratch: ``` npm install --save-dev --save-exact @varavel/vdl-plugin-sdk@latest ``` ## Quick Start A VDL plugin exports a `generate` handler created with `definePlugin(...)` from `src/index.ts`. Create `src/index.ts` in your plugin project: ``` import { definePlugin } from "@varavel/vdl-plugin-sdk"; export const generate = definePlugin((input) => { // Your plugin logic goes here // Feel free to explore the plugin input console.log(input.version); // The VDL version without the v prefix console.log(input.options); // Plugin options from vdl.config.vdl console.log(input.ir); // Typed VDL intermediate representation return { files: [ { path: "hello.txt", content: "Hello from VDL Plugin SDK", }, ], }; }); ``` Then run: ``` npx vdl-plugin check npx vdl-plugin build ``` - `check` validates your TypeScript during development. - `build` generates the release-ready plugin bundle at `dist/index.js`. If you want the full API surface while you read, the reference docs live at [vdl-plugin-sdk.varavel.com](https://vdl-plugin-sdk.varavel.com). ## What This Package Includes Think of the SDK as four pieces that work together: - The main package for authoring a plugin handler and working with the typed VDL IR. - A separate `utils` entry point for reusable helper namespaces used in plugin logic. - A separate `testing` entry point for building realistic IR fixtures in unit tests. - A small CLI plus shared `tsconfig` presets for the normal plugin build workflow. The README focuses on how these surfaces fit together. A fuller API reference lives at [vdl-plugin-sdk.varavel.com](https://vdl-plugin-sdk.varavel.com). ## Entry Points | Import | Use for | | --------------------------------- | -------------------------------------------------------------------------------------------------- | | `@varavel/vdl-plugin-sdk` | Main plugin authoring surface: define your plugin, receive typed input, and return generated files | | `@varavel/vdl-plugin-sdk/utils` | Helper namespaces for deterministic transformations and VDL-specific utility work | | `@varavel/vdl-plugin-sdk/testing` | Test-only builders for creating plugin input and IR fixtures quickly | ### `@varavel/vdl-plugin-sdk` Use `@varavel/vdl-plugin-sdk` in your plugin runtime code. This is the package surface you start from when writing `src/index.ts`. It is the home for the plugin definition flow and the generated VDL types that describe the input your plugin receives. ### `@varavel/vdl-plugin-sdk/utils` Use `@varavel/vdl-plugin-sdk/utils` when your plugin code needs reusable transformations, string and object helpers, option helpers, or IR-oriented convenience functions. The utilities are organized into namespaces such as `arrays`, `functions`, `maps`, `math`, `misc`, `objects`, `options`, `predicates`, `sets`, `strings`, and `ir`, so plugin code can stay explicit without pulling everything from the main SDK entry point. ### `@varavel/vdl-plugin-sdk/testing` Use `@varavel/vdl-plugin-sdk/testing` only in tests. It exposes `irb`, a compact IR builder for creating realistic plugin input and schema fixtures without hand-writing large object graphs. This keeps test helpers separate from runtime imports and makes unit tests easier to read. ## Recommended Mental Model - Reach for `@varavel/vdl-plugin-sdk` when you are writing the plugin itself. - Reach for `@varavel/vdl-plugin-sdk/utils` when your plugin logic needs shared helper functions. - Reach for `@varavel/vdl-plugin-sdk/testing` when you are constructing test fixtures. - Treat the CLI and `tsconfig` presets as project scaffolding around those imports, not as part of your runtime code. ## CLI Use the bundled binary in scripts or with `npx`: ``` npx vdl-plugin check npx vdl-plugin build ``` - `check` runs TypeScript without emitting files. If a `tsconfig.vitest.json` is present, it also type-checks test code. - `build` bundles the required `src/index.ts` entry into `dist/index.js`. For a fuller walkthrough, use this page together with the hosted documentation: [vdl-plugin-sdk.varavel.com](https://vdl-plugin-sdk.varavel.com). ## Plugin Workflow Most plugins follow the same path: 1. Author the plugin in `src/index.ts` with the main SDK entry point. 1. Use `@varavel/vdl-plugin-sdk/utils` only where helper namespaces make the implementation clearer. 1. Add unit tests with `@varavel/vdl-plugin-sdk/testing` when you need realistic IR input. 1. Run `vdl-plugin check` during development. 1. Run `vdl-plugin build` to produce `dist/index.js` for release. 1. Commit `dist/index.js` to GitHub and create a new release (tag). When a plugin is published, VDL consumes the built `dist/index.js` artifact rather than the TypeScript source. Example `package.json` scripts: ``` { "scripts": { "check": "vdl-plugin check", "build": "vdl-plugin build" } } ``` ## TypeScript Setup You can extend the shared base config exported by the SDK in your `tsconfig.json` file: ``` { "extends": "@varavel/vdl-plugin-sdk/tsconfig.base.json", "include": ["src/**/*.ts"], "exclude": ["src/**/*.test.ts"] } ``` ## Testing `irb` stands for IR builder. It is a small factory API for tests that need realistic VDL input without hand-writing the full IR shape every time. Import it from the dedicated testing entry point: ``` import { irb } from "@varavel/vdl-plugin-sdk/testing"; ``` Example: ``` import { irb } from "@varavel/vdl-plugin-sdk/testing"; const input = irb.pluginInput({ options: { prefix: "Api" }, ir: irb.schema({ types: [ irb.typeDef( "User", irb.objectType([ irb.field("id", irb.primitiveType("string")), ]), ), ], }), }); ``` Pass `input` to your plugin handler in a unit test and assert on the generated files or errors. Because `irb` lives under `@varavel/vdl-plugin-sdk/testing`, you can keep test helpers separate from your plugin runtime imports. To add tests to your plugin, install [Vitest](https://vitest.dev): ``` npm install --save-dev vitest ``` Then create a `tsconfig.vitest.json` in the root of your project: ``` { "extends": "@varavel/vdl-plugin-sdk/tsconfig.vitest.base.json", "include": [ "src/**/*.test.ts", "tests/**/*.ts", "e2e/**/*.ts", "vitest.config.ts" ] } ``` This config extends the base provided by the SDK and includes Node.js types exclusively for test files, keeping them out of your main plugin compilation. Once the file is in place, `vdl-plugin check` will automatically type-check your test code as well. ## License This project is released under the MIT License. See the [LICENSE](https://github.com/varavelio/vdl-plugin-sdk/blob/main/LICENSE). # core ## Type Aliases ### Annotation ``` type Annotation = object; ``` Annotation Annotation metadata preserved in IR. `name` is the annotation identifier without the `@` prefix. `argument`, when present, is fully resolved as a LiteralValue. #### Properties ##### argument? ``` optional argument: LiteralValue; ``` ##### name ``` name: string; ``` ##### position ``` position: Position; ``` ______________________________________________________________________ ### ConstantDef ``` type ConstantDef = object; ``` ConstantDef Fully resolved constant definition. `typeRef` is explicit or inferred by analysis. `value` contains the fully resolved literal payload. #### Properties ##### annotations ``` annotations: Annotation[]; ``` ##### doc? ``` optional doc: string; ``` ##### name ``` name: string; ``` ##### position ``` position: Position; ``` ##### typeRef ``` typeRef: TypeRef; ``` ##### value ``` value: LiteralValue; ``` ______________________________________________________________________ ### EnumDef ``` type EnumDef = object; ``` EnumDef Flattened enum definition. All enum spreads are already expanded into `members`. #### Properties ##### annotations ``` annotations: Annotation[]; ``` ##### doc? ``` optional doc: string; ``` ##### enumType ``` enumType: EnumValueType; ``` ##### members ``` members: EnumMember[]; ``` ##### name ``` name: string; ``` ##### position ``` position: Position; ``` ______________________________________________________________________ ### EnumMember ``` type EnumMember = object; ``` EnumMember Enum member definition #### Properties ##### annotations ``` annotations: Annotation[]; ``` ##### doc? ``` optional doc: string; ``` ##### name ``` name: string; ``` ##### position ``` position: Position; ``` ##### value ``` value: LiteralValue; ``` ______________________________________________________________________ ### EnumValueType ``` type EnumValueType = "string" | "int"; ``` Underlying storage kind used by an enum ______________________________________________________________________ ### Field ``` type Field = object; ``` Field Flattened object/type field definition #### Properties ##### annotations ``` annotations: Annotation[]; ``` ##### doc? ``` optional doc: string; ``` ##### name ``` name: string; ``` ##### optional ``` optional: boolean; ``` ##### position ``` position: Position; ``` ##### typeRef ``` typeRef: TypeRef; ``` ______________________________________________________________________ ### IrSchema ``` type IrSchema = object; ``` IrSchema IrSchema is the generator-facing representation of a VDL program. This model is intentionally "flat" and "resolved": - spreads are already expanded - references are already resolved - collections are in deterministic order A code generator should be able to consume IrSchema directly, without needing to re-run parser or semantic-analysis logic. #### Properties ##### constants ``` constants: ConstantDef[]; ``` ##### docs ``` docs: TopLevelDoc[]; ``` ##### entryPoint ``` entryPoint: string; ``` ##### enums ``` enums: EnumDef[]; ``` ##### types ``` types: TypeDef[]; ``` ______________________________________________________________________ ### LiteralKind ``` type LiteralKind = "string" | "int" | "float" | "bool" | "object" | "array"; ``` Kind discriminator for LiteralValue. LiteralValue is used for fully resolved literal data in: - constant values - annotation arguments ______________________________________________________________________ ### LiteralValue ``` type LiteralValue = object; ``` LiteralValue Fully resolved literal value. The selected payload is determined by `kind`: - `string` -> `stringValue` - `int` -> `intValue` - `float` -> `floatValue` - `bool` -> `boolValue` - `object` -> `objectEntries` - `array` -> `arrayItems` #### Properties ##### arrayItems? ``` optional arrayItems: LiteralValue[]; ``` ##### boolValue? ``` optional boolValue: boolean; ``` ##### floatValue? ``` optional floatValue: number; ``` ##### intValue? ``` optional intValue: number; ``` ##### kind ``` kind: LiteralKind; ``` ##### objectEntries? ``` optional objectEntries: ObjectEntry[]; ``` ##### position ``` position: Position; ``` ##### stringValue? ``` optional stringValue: string; ``` ______________________________________________________________________ ### ObjectEntry ``` type ObjectEntry = object; ``` ObjectEntry Key/value pair inside an object LiteralValue payload #### Properties ##### key ``` key: string; ``` ##### position ``` position: Position; ``` ##### value ``` value: LiteralValue; ``` ______________________________________________________________________ ### PluginInput ``` type PluginInput = object; ``` PluginInput PluginInput represents the data payload sent to a plugin. The plugin receives this as a single argument containing the complete Intermediate Representation of the VDL schema along with any user-defined configuration options from `vdl.config.vdl`. #### Properties ##### ir ``` ir: IrSchema; ``` ##### options ``` options: Record; ``` ##### version ``` version: string; ``` ______________________________________________________________________ ### PluginOutput ``` type PluginOutput = object; ``` PluginOutput PluginOutput represents the response payload returned by the `plugin` function. After processing the input schema, the plugin outputs this object containing all files to be generated or errors to be displayed to the user. If there are no errors and at least one file is returned, VDL will write each file to the specified path within the output directory. If there are errors, VDL will display them to the user and not write any files. #### Properties ##### errors? ``` optional errors: PluginOutputError[]; ``` ##### files? ``` optional files: PluginOutputFile[]; ``` ______________________________________________________________________ ### PluginOutputError ``` type PluginOutputError = object; ``` PluginOutputError A structured error reported by the plugin. #### Properties ##### message ``` message: string; ``` ##### position? ``` optional position: Position; ``` ______________________________________________________________________ ### PluginOutputFile ``` type PluginOutputFile = object; ``` PluginOutputFile PluginOutputFile represents a single generated file produced by the plugin. This abstraction allows plugins to generate multiple files from a single invocation, enabling patterns like one-file-per-type or splitting large outputs across multiple modules. #### Properties ##### content ``` content: string; ``` ##### path ``` path: string; ``` ______________________________________________________________________ ### Position ``` type Position = object; ``` Position It represents a position within a file and is used for error reporting, diagnostics, plugins, and tooling support. #### Properties ##### column ``` column: number; ``` ##### file ``` file: string; ``` ##### line ``` line: number; ``` ______________________________________________________________________ ### PrimitiveType ``` type PrimitiveType = "string" | "int" | "float" | "bool" | "datetime"; ``` Primitive scalar type names ______________________________________________________________________ ### TopLevelDoc ``` type TopLevelDoc = object; ``` TopLevelDoc Standalone documentation block. Used for top-level docstrings that are not attached to a type/enum/constant. #### Properties ##### content ``` content: string; ``` ##### position ``` position: Position; ``` ______________________________________________________________________ ### TypeDef ``` type TypeDef = object; ``` TypeDef Flattened type definition. All spreads are already expanded. The unified `typeRef` describes what this type IS, a primitive, custom reference, map, array, or object with fields. #### Properties ##### annotations ``` annotations: Annotation[]; ``` ##### doc? ``` optional doc: string; ``` ##### name ``` name: string; ``` ##### position ``` position: Position; ``` ##### typeRef ``` typeRef: TypeRef; ``` ______________________________________________________________________ ### TypeKind ``` type TypeKind = "primitive" | "type" | "enum" | "array" | "map" | "object"; ``` Kind discriminator for TypeRef ______________________________________________________________________ ### TypeRef ``` type TypeRef = object; ``` TypeRef Normalized type reference used by fields and constants. `kind` selects which payload fields are meaningful. Generators should inspect `kind` first, then read the related payload fields. #### Properties ##### arrayDims? ``` optional arrayDims: number; ``` ##### arrayType? ``` optional arrayType: TypeRef; ``` ##### enumName? ``` optional enumName: string; ``` ##### enumType? ``` optional enumType: EnumValueType; ``` ##### kind ``` kind: TypeKind; ``` ##### mapType? ``` optional mapType: TypeRef; ``` ##### objectFields? ``` optional objectFields: Field[]; ``` ##### primitiveName? ``` optional primitiveName: PrimitiveType; ``` ##### typeName? ``` optional typeName: string; ``` ______________________________________________________________________ ### VdlPluginHandler() ``` type VdlPluginHandler = (input) => PluginOutput; ``` Function signature implemented by every VDL plugin entry point. The handler receives the typed plugin input produced by VDL and returns the generated files and any diagnostics for the current run. #### Parameters ##### input [`PluginInput`](#plugininput) The plugin invocation context, including version, options, and IR. #### Returns [`PluginOutput`](#pluginoutput) The files and errors produced by the plugin. #### Example ``` const generate: VdlPluginHandler = (input) => { return { files: [{ path: "hello.txt", content: input.version }], }; }; ``` ## Variables ### EnumValueTypeList ``` const EnumValueTypeList: EnumValueType[]; ``` ______________________________________________________________________ ### LiteralKindList ``` const LiteralKindList: LiteralKind[]; ``` ______________________________________________________________________ ### PrimitiveTypeList ``` const PrimitiveTypeList: PrimitiveType[]; ``` ______________________________________________________________________ ### TypeKindList ``` const TypeKindList: TypeKind[]; ``` ## Functions ### definePlugin() ``` function definePlugin(handler): VdlPluginHandler; ``` Wraps a plugin handler so it can be exported as the canonical VDL entry point. `definePlugin` is intentionally minimal. It preserves the handler's type information and gives plugin projects a single, explicit pattern for exporting `generate` from `src/index.ts`. #### Parameters ##### handler [`VdlPluginHandler`](#vdlpluginhandler) The plugin implementation to expose as the runtime entry point. #### Returns [`VdlPluginHandler`](#vdlpluginhandler) The same handler function, unchanged. #### Example ``` import { definePlugin } from "@varavel/vdl-plugin-sdk"; export const generate = definePlugin((input) => { return { files: [ { path: "schema-summary.txt", content: `VDL ${input.version}`, }, ], }; }); ``` ______________________________________________________________________ ### hydrateAnnotation() ``` function hydrateAnnotation(input): Annotation; ``` #### Parameters ##### input [`Annotation`](#annotation) #### Returns [`Annotation`](#annotation) ______________________________________________________________________ ### hydrateConstantDef() ``` function hydrateConstantDef(input): ConstantDef; ``` #### Parameters ##### input [`ConstantDef`](#constantdef) #### Returns [`ConstantDef`](#constantdef) ______________________________________________________________________ ### hydrateEnumDef() ``` function hydrateEnumDef(input): EnumDef; ``` #### Parameters ##### input [`EnumDef`](#enumdef) #### Returns [`EnumDef`](#enumdef) ______________________________________________________________________ ### hydrateEnumMember() ``` function hydrateEnumMember(input): EnumMember; ``` #### Parameters ##### input [`EnumMember`](#enummember) #### Returns [`EnumMember`](#enummember) ______________________________________________________________________ ### hydrateField() ``` function hydrateField(input): Field; ``` #### Parameters ##### input [`Field`](#field) #### Returns [`Field`](#field) ______________________________________________________________________ ### hydrateIrSchema() ``` function hydrateIrSchema(input): IrSchema; ``` #### Parameters ##### input [`IrSchema`](#irschema) #### Returns [`IrSchema`](#irschema) ______________________________________________________________________ ### hydrateLiteralValue() ``` function hydrateLiteralValue(input): LiteralValue; ``` #### Parameters ##### input [`LiteralValue`](#literalvalue) #### Returns [`LiteralValue`](#literalvalue) ______________________________________________________________________ ### hydrateObjectEntry() ``` function hydrateObjectEntry(input): ObjectEntry; ``` #### Parameters ##### input [`ObjectEntry`](#objectentry) #### Returns [`ObjectEntry`](#objectentry) ______________________________________________________________________ ### hydratePluginInput() ``` function hydratePluginInput(input): PluginInput; ``` #### Parameters ##### input [`PluginInput`](#plugininput) #### Returns [`PluginInput`](#plugininput) ______________________________________________________________________ ### hydratePluginOutput() ``` function hydratePluginOutput(input): PluginOutput; ``` #### Parameters ##### input [`PluginOutput`](#pluginoutput) #### Returns [`PluginOutput`](#pluginoutput) ______________________________________________________________________ ### hydratePluginOutputError() ``` function hydratePluginOutputError(input): PluginOutputError; ``` #### Parameters ##### input [`PluginOutputError`](#pluginoutputerror) #### Returns [`PluginOutputError`](#pluginoutputerror) ______________________________________________________________________ ### hydratePluginOutputFile() ``` function hydratePluginOutputFile(input): PluginOutputFile; ``` #### Parameters ##### input [`PluginOutputFile`](#pluginoutputfile) #### Returns [`PluginOutputFile`](#pluginoutputfile) ______________________________________________________________________ ### hydratePosition() ``` function hydratePosition(input): Position; ``` #### Parameters ##### input [`Position`](#position-8) #### Returns [`Position`](#position-8) ______________________________________________________________________ ### hydrateTopLevelDoc() ``` function hydrateTopLevelDoc(input): TopLevelDoc; ``` #### Parameters ##### input [`TopLevelDoc`](#topleveldoc) #### Returns [`TopLevelDoc`](#topleveldoc) ______________________________________________________________________ ### hydrateTypeDef() ``` function hydrateTypeDef(input): TypeDef; ``` #### Parameters ##### input [`TypeDef`](#typedef) #### Returns [`TypeDef`](#typedef) ______________________________________________________________________ ### hydrateTypeRef() ``` function hydrateTypeRef(input): TypeRef; ``` #### Parameters ##### input [`TypeRef`](#typeref-3) #### Returns [`TypeRef`](#typeref-3) ______________________________________________________________________ ### isEnumValueType() ``` function isEnumValueType(value): value is EnumValueType; ``` #### Parameters ##### value `unknown` #### Returns `value is EnumValueType` ______________________________________________________________________ ### isLiteralKind() ``` function isLiteralKind(value): value is LiteralKind; ``` #### Parameters ##### value `unknown` #### Returns `value is LiteralKind` ______________________________________________________________________ ### isPrimitiveType() ``` function isPrimitiveType(value): value is PrimitiveType; ``` #### Parameters ##### value `unknown` #### Returns `value is PrimitiveType` ______________________________________________________________________ ### isTypeKind() ``` function isTypeKind(value): value is TypeKind; ``` #### Parameters ##### value `unknown` #### Returns `value is TypeKind` ______________________________________________________________________ ### validateAnnotation() ``` function validateAnnotation(input, path?): string | null; ``` #### Parameters ##### input `unknown` ##### path? `string` = `"Annotation"` #### Returns `string` | `null` ______________________________________________________________________ ### validateConstantDef() ``` function validateConstantDef(input, path?): string | null; ``` #### Parameters ##### input `unknown` ##### path? `string` = `"ConstantDef"` #### Returns `string` | `null` ______________________________________________________________________ ### validateEnumDef() ``` function validateEnumDef(input, path?): string | null; ``` #### Parameters ##### input `unknown` ##### path? `string` = `"EnumDef"` #### Returns `string` | `null` ______________________________________________________________________ ### validateEnumMember() ``` function validateEnumMember(input, path?): string | null; ``` #### Parameters ##### input `unknown` ##### path? `string` = `"EnumMember"` #### Returns `string` | `null` ______________________________________________________________________ ### validateField() ``` function validateField(input, path?): string | null; ``` #### Parameters ##### input `unknown` ##### path? `string` = `"Field"` #### Returns `string` | `null` ______________________________________________________________________ ### validateIrSchema() ``` function validateIrSchema(input, path?): string | null; ``` #### Parameters ##### input `unknown` ##### path? `string` = `"IrSchema"` #### Returns `string` | `null` ______________________________________________________________________ ### validateLiteralValue() ``` function validateLiteralValue(input, path?): string | null; ``` #### Parameters ##### input `unknown` ##### path? `string` = `"LiteralValue"` #### Returns `string` | `null` ______________________________________________________________________ ### validateObjectEntry() ``` function validateObjectEntry(input, path?): string | null; ``` #### Parameters ##### input `unknown` ##### path? `string` = `"ObjectEntry"` #### Returns `string` | `null` ______________________________________________________________________ ### validatePluginInput() ``` function validatePluginInput(input, path?): string | null; ``` #### Parameters ##### input `unknown` ##### path? `string` = `"PluginInput"` #### Returns `string` | `null` ______________________________________________________________________ ### validatePluginOutput() ``` function validatePluginOutput(input, path?): string | null; ``` #### Parameters ##### input `unknown` ##### path? `string` = `"PluginOutput"` #### Returns `string` | `null` ______________________________________________________________________ ### validatePluginOutputError() ``` function validatePluginOutputError(input, path?): string | null; ``` #### Parameters ##### input `unknown` ##### path? `string` = `"PluginOutputError"` #### Returns `string` | `null` ______________________________________________________________________ ### validatePluginOutputFile() ``` function validatePluginOutputFile(_input, _path?): string | null; ``` #### Parameters ##### \_input `unknown` ##### \_path? `string` = `"PluginOutputFile"` #### Returns `string` | `null` ______________________________________________________________________ ### validatePosition() ``` function validatePosition(_input, _path?): string | null; ``` #### Parameters ##### \_input `unknown` ##### \_path? `string` = `"Position"` #### Returns `string` | `null` ______________________________________________________________________ ### validateTopLevelDoc() ``` function validateTopLevelDoc(input, path?): string | null; ``` #### Parameters ##### input `unknown` ##### path? `string` = `"TopLevelDoc"` #### Returns `string` | `null` ______________________________________________________________________ ### validateTypeDef() ``` function validateTypeDef(input, path?): string | null; ``` #### Parameters ##### input `unknown` ##### path? `string` = `"TypeDef"` #### Returns `string` | `null` ______________________________________________________________________ ### validateTypeRef() ``` function validateTypeRef(input, path?): string | null; ``` #### Parameters ##### input `unknown` ##### path? `string` = `"TypeRef"` #### Returns `string` | `null` # testing ## Variables ### irb ``` const irb: object; ``` Intermediate Representation Builder โ€” a collection of test factory functions for constructing well-formed IR nodes with sensible defaults. Use `irb` in unit tests to create `IrSchema`, `TypeDef`, `EnumDef`, `ConstantDef`, `Field`, `TypeRef`, `LiteralValue`, `Annotation`, and other IR structures without manually supplying every required property. #### Type Declaration ##### annotation() ``` annotation(name, argument?): Annotation; ``` Creates an `Annotation` with the given name and an optional literal argument. ###### Parameters ###### name `string` Annotation name without the `@` prefix. ###### argument? [`LiteralValue`](https://vdl-plugin-sdk.varavel.com/api/core/#literalvalue) Optional literal argument attached to the annotation. ###### Returns [`Annotation`](https://vdl-plugin-sdk.varavel.com/api/core/#annotation) An `Annotation` with a default position. ###### Example ``` irb.annotation("minLength", irb.intLiteral(3)); // returns an annotation named "minLength" with an int literal argument ``` ##### arrayLiteral() ``` arrayLiteral(items): LiteralValue; ``` Creates an array `LiteralValue` from a list of literal items. ###### Parameters ###### items [`LiteralValue`](https://vdl-plugin-sdk.varavel.com/api/core/#literalvalue)[] Literal items to include. ###### Returns [`LiteralValue`](https://vdl-plugin-sdk.varavel.com/api/core/#literalvalue) An array literal node. ###### Example ``` irb.arrayLiteral([irb.stringLiteral("a"), irb.stringLiteral("b")]); // returns a LiteralValue with kind "array" ``` ##### arrayType() ``` arrayType(type, dims?): TypeRef; ``` Creates an array `TypeRef` wrapping the given element type. ###### Parameters ###### type [`TypeRef`](https://vdl-plugin-sdk.varavel.com/api/core/#typeref-3) Element type stored inside the array. ###### dims? `number` = `1` Number of array dimensions (defaults to 1). ###### Returns [`TypeRef`](https://vdl-plugin-sdk.varavel.com/api/core/#typeref-3) An array `TypeRef`. ###### Example ``` irb.arrayType(irb.primitiveType("string"), 2); // returns a two-dimensional array TypeRef ``` ##### boolLiteral() ``` boolLiteral(value): LiteralValue; ``` Creates a boolean `LiteralValue`. ###### Parameters ###### value `boolean` Boolean value to store. ###### Returns [`LiteralValue`](https://vdl-plugin-sdk.varavel.com/api/core/#literalvalue) A boolean literal node. ###### Example ``` irb.boolLiteral(true); // returns a LiteralValue with kind "bool" ``` ##### constantDef() ``` constantDef( name, typeRef, value, overrides?): ConstantDef; ``` Creates a `ConstantDef` with the given name, type, and literal value. Pass `overrides` to set `annotations` or `doc`. ###### Parameters ###### name `string` Constant name. ###### typeRef [`TypeRef`](https://vdl-plugin-sdk.varavel.com/api/core/#typeref-3) Constant type reference. ###### value [`LiteralValue`](https://vdl-plugin-sdk.varavel.com/api/core/#literalvalue) Constant literal value. ###### overrides? `Partial`\<`Omit`\<[`ConstantDef`](https://vdl-plugin-sdk.varavel.com/api/core/#constantdef), `"position"` | `"annotations"` | `"typeRef"` | `"value"` | `"name"`>> & `object` = `{}` Optional constant overrides. ###### Returns [`ConstantDef`](https://vdl-plugin-sdk.varavel.com/api/core/#constantdef) A `ConstantDef` with defaults applied. ###### Example ``` irb.constantDef("ApiVersion", irb.primitiveType("string"), irb.stringLiteral("v1")); // returns a constant definition named "ApiVersion" ``` ##### enumDef() ``` enumDef( name, enumValueType, members, overrides?): EnumDef; ``` Creates an `EnumDef` with the given name, value type, and members. Pass `overrides` to set `annotations` or `doc`. ###### Parameters ###### name `string` Enum name. ###### enumValueType [`EnumValueType`](https://vdl-plugin-sdk.varavel.com/api/core/#enumvaluetype) Underlying enum storage type. ###### members [`EnumMember`](https://vdl-plugin-sdk.varavel.com/api/core/#enummember)[] Enum members. ###### overrides? `Partial`\<`Omit`\<[`EnumDef`](https://vdl-plugin-sdk.varavel.com/api/core/#enumdef), `"position"` | `"annotations"` | `"enumType"` | `"members"` | `"name"`>> & `object` = `{}` Optional enum overrides. ###### Returns [`EnumDef`](https://vdl-plugin-sdk.varavel.com/api/core/#enumdef) An `EnumDef` with defaults applied. ###### Example ``` irb.enumDef("Role", "string", [ irb.enumMember("ADMIN", irb.stringLiteral("admin")), ]); // returns an enum definition named "Role" ``` ##### enumMember() ``` enumMember( name, value, overrides?): EnumMember; ``` Creates an `EnumMember` with the given name and literal value. Pass `overrides` to set `annotations` or `doc`. ###### Parameters ###### name `string` Enum member name. ###### value [`LiteralValue`](https://vdl-plugin-sdk.varavel.com/api/core/#literalvalue) Enum member literal value. ###### overrides? `Partial`\<`Omit`\<[`EnumMember`](https://vdl-plugin-sdk.varavel.com/api/core/#enummember), `"position"` | `"annotations"` | `"value"` | `"name"`>> & `object` = `{}` Optional member overrides. ###### Returns [`EnumMember`](https://vdl-plugin-sdk.varavel.com/api/core/#enummember) An `EnumMember` with defaults applied. ###### Example ``` irb.enumMember("ADMIN", irb.stringLiteral("admin")); // returns an enum member named "ADMIN" ``` ##### enumType() ``` enumType(name, enumType): TypeRef; ``` Creates a `TypeRef` that references a named enum type. ###### Parameters ###### name `string` Referenced enum name. ###### enumType [`EnumValueType`](https://vdl-plugin-sdk.varavel.com/api/core/#enumvaluetype) Underlying enum storage type. ###### Returns [`TypeRef`](https://vdl-plugin-sdk.varavel.com/api/core/#typeref-3) An enum type reference. ###### Example ``` irb.enumType("Role", "string"); // returns a TypeRef with kind "enum" ``` ##### field() ``` field( name, typeRef, overrides?): Field; ``` Creates a `Field` with the given name and type. Pass `overrides` to set `optional`, `annotations`, or `doc`. ###### Parameters ###### name `string` Field name. ###### typeRef [`TypeRef`](https://vdl-plugin-sdk.varavel.com/api/core/#typeref-3) Field type reference. ###### overrides? `Partial`\<`Omit`\<[`Field`](https://vdl-plugin-sdk.varavel.com/api/core/#field), `"position"` | `"annotations"` | `"typeRef"` | `"name"` | `"optional"`>> & `object` = `{}` Optional field overrides. ###### Returns [`Field`](https://vdl-plugin-sdk.varavel.com/api/core/#field) A `Field` with defaults applied. ###### Example ``` irb.field("id", irb.primitiveType("string"), { optional: true }); // returns a Field named "id" marked as optional ``` ##### floatLiteral() ``` floatLiteral(value): LiteralValue; ``` Creates a float `LiteralValue`. ###### Parameters ###### value `number` Floating-point value to store. ###### Returns [`LiteralValue`](https://vdl-plugin-sdk.varavel.com/api/core/#literalvalue) A float literal node. ###### Example ``` irb.floatLiteral(3.14); // returns a LiteralValue with kind "float" ``` ##### intLiteral() ``` intLiteral(value): LiteralValue; ``` Creates an integer `LiteralValue`. ###### Parameters ###### value `number` Integer value to store. ###### Returns [`LiteralValue`](https://vdl-plugin-sdk.varavel.com/api/core/#literalvalue) An integer literal node. ###### Example ``` irb.intLiteral(42); // returns a LiteralValue with kind "int" ``` ##### mapType() ``` mapType(type): TypeRef; ``` Creates a map `TypeRef` whose value type is `type`. ###### Parameters ###### type [`TypeRef`](https://vdl-plugin-sdk.varavel.com/api/core/#typeref-3) Value type stored in the map. ###### Returns [`TypeRef`](https://vdl-plugin-sdk.varavel.com/api/core/#typeref-3) A map `TypeRef`. ###### Example ``` irb.mapType(irb.namedType("User")); // returns a TypeRef with kind "map" ``` ##### namedType() ``` namedType(name): TypeRef; ``` Creates a `TypeRef` that references a named user-defined type. ###### Parameters ###### name `string` Referenced type name. ###### Returns [`TypeRef`](https://vdl-plugin-sdk.varavel.com/api/core/#typeref-3) A named type reference. ###### Example ``` irb.namedType("User"); // returns a TypeRef with kind "type" ``` ##### objectLiteral() ``` objectLiteral(entries): LiteralValue; ``` Creates an object `LiteralValue` from a plain key/value record. ###### Parameters ###### entries `Record`\<`string`, [`LiteralValue`](https://vdl-plugin-sdk.varavel.com/api/core/#literalvalue)> Object entries keyed by property name. ###### Returns [`LiteralValue`](https://vdl-plugin-sdk.varavel.com/api/core/#literalvalue) An object literal node. ###### Example ``` irb.objectLiteral({ enabled: irb.boolLiteral(true) }); // returns a LiteralValue with kind "object" ``` ##### objectType() ``` objectType(fields): TypeRef; ``` Creates an inline object `TypeRef` with the given fields. ###### Parameters ###### fields [`Field`](https://vdl-plugin-sdk.varavel.com/api/core/#field)[] Inline object fields. ###### Returns [`TypeRef`](https://vdl-plugin-sdk.varavel.com/api/core/#typeref-3) An object `TypeRef`. ###### Example ``` irb.objectType([irb.field("id", irb.primitiveType("string"))]); // returns a TypeRef with kind "object" ``` ##### pluginInput() ``` pluginInput(overrides?): PluginInput; ``` Creates a `PluginInput` with a default version, empty options, and an empty schema. Pass `overrides` to customize any field. ###### Parameters ###### overrides? `Partial`\<[`PluginInput`](https://vdl-plugin-sdk.varavel.com/api/core/#plugininput)> = `{}` Plugin input fields to override. ###### Returns [`PluginInput`](https://vdl-plugin-sdk.varavel.com/api/core/#plugininput) A ready-to-use `PluginInput` for tests. ###### Example ``` irb.pluginInput({ options: { prefix: "Api" }, }); // returns a PluginInput with default version and schema ``` ##### position() ``` position(overrides?): Position; ``` Creates a `Position` with sensible defaults. Pass `overrides` to customize specific fields. ###### Parameters ###### overrides? `Partial`\<[`Position`](https://vdl-plugin-sdk.varavel.com/api/core/#position-8)> = `{}` Position fields to override. ###### Returns [`Position`](https://vdl-plugin-sdk.varavel.com/api/core/#position-8) A fully populated `Position`. ###### Example ``` irb.position({ file: "user.vdl", line: 10 }); // returns { file: "user.vdl", line: 10, column: 1 } ``` ##### primitiveType() ``` primitiveType(name): TypeRef; ``` Creates a primitive `TypeRef` (e.g. `string`, `int`, `bool`). ###### Parameters ###### name [`PrimitiveType`](https://vdl-plugin-sdk.varavel.com/api/core/#primitivetype) Primitive type name. ###### Returns [`TypeRef`](https://vdl-plugin-sdk.varavel.com/api/core/#typeref-3) A primitive `TypeRef`. ###### Example ``` irb.primitiveType("string"); // returns a TypeRef with kind "primitive" ``` ##### schema() ``` schema(overrides?): IrSchema; ``` Creates an `IrSchema` with empty collections. Pass `overrides` to populate `constants`, `enums`, `types`, or `docs`. ###### Parameters ###### overrides? `Partial`\<[`IrSchema`](https://vdl-plugin-sdk.varavel.com/api/core/#irschema)> = `{}` Schema fields to override. ###### Returns [`IrSchema`](https://vdl-plugin-sdk.varavel.com/api/core/#irschema) An `IrSchema` with sensible defaults. ###### Example ``` irb.schema({ types: [irb.typeDef("UserId", irb.primitiveType("string"))], }); // returns a schema containing one typedef ``` ##### stringLiteral() ``` stringLiteral(value): LiteralValue; ``` Creates a string `LiteralValue`. ###### Parameters ###### value `string` String content to store. ###### Returns [`LiteralValue`](https://vdl-plugin-sdk.varavel.com/api/core/#literalvalue) A string literal node. ###### Example ``` irb.stringLiteral("hello"); // returns a LiteralValue with kind "string" ``` ##### typeDef() ``` typeDef( name, typeRef, overrides?): TypeDef; ``` Creates a `TypeDef` with the given name and underlying type. Pass `overrides` to set `annotations` or `doc`. ###### Parameters ###### name `string` Type definition name. ###### typeRef [`TypeRef`](https://vdl-plugin-sdk.varavel.com/api/core/#typeref-3) Underlying type reference. ###### overrides? `Partial`\<`Omit`\<[`TypeDef`](https://vdl-plugin-sdk.varavel.com/api/core/#typedef), `"position"` | `"annotations"` | `"typeRef"` | `"name"`>> & `object` = `{}` Optional typedef overrides. ###### Returns [`TypeDef`](https://vdl-plugin-sdk.varavel.com/api/core/#typedef) A `TypeDef` with defaults applied. ###### Example ``` irb.typeDef("UserId", irb.primitiveType("string")); // returns a typedef named "UserId" ``` #### Example ``` const input = irb.pluginInput({ ir: irb.schema({ types: [ irb.typeDef("MyType", irb.primitiveType("string")) ], }), }); ``` # arrays ## Variables ### at ``` const at: typeof esToolkit_at = esToolkit_at; ``` Retrieves elements from an array at the specified indices. This function supports negative indices, which count from the end of the array. #### Template #### Param The array to retrieve elements from. #### Param An array of indices specifying the positions of elements to retrieve. #### Returns A new array containing the elements at the specified indices. #### Example ``` const numbers = [10, 20, 30, 40, 50]; const result = at(numbers, [1, 3, 4]); console.log(result); // [20, 40, 50] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### chunk ``` const chunk: typeof esToolkit_chunk = esToolkit_chunk; ``` Splits an array into smaller arrays of a specified length. This function takes an input array and divides it into multiple smaller arrays, each of a specified length. If the input array cannot be evenly divided, the final sub-array will contain the remaining elements. #### Template The type of elements in the array. #### Param The array to be chunked into smaller arrays. #### Param The size of each smaller array. Must be a positive integer. #### Returns A two-dimensional array where each sub-array has a maximum length of `size`. #### Throws Throws an error if `size` is not a positive integer. #### Examples ``` // Splits an array of numbers into sub-arrays of length 2 chunk([1, 2, 3, 4, 5], 2); // Returns: [[1, 2], [3, 4], [5]] ``` ``` // Splits an array of strings into sub-arrays of length 3 chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3); // Returns: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### compact ``` const compact: typeof esToolkit_compact = esToolkit_compact; ``` Removes falsey values (false, null, 0, -0, 0n, '', undefined, NaN) from an array. #### Template The type of elements in the array. #### Param The input array to remove falsey values. #### Returns - A new array with all falsey values removed. #### Example ``` compact([0, -0, 0n, 1, false, 2, '', 3, null, undefined, 4, NaN, 5]); Returns: [1, 2, 3, 4, 5] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### countBy ``` const countBy: typeof esToolkit_countBy = esToolkit_countBy; ``` Count the occurrences of each item in an array based on a transformation function. This function takes an array and a transformation function that converts each item in the array to a key. It then counts the occurrences of each transformed item and returns an object with the transformed items as keys and the counts as values. #### Template The type of the items in the input array. #### Template The type of keys. #### Param The input array to count occurrences. #### Param The transformation function that maps each item, its index, and the array to a key. #### Returns An object containing the transformed items as keys and the counts as values. #### Examples ``` const array = ['a', 'b', 'c', 'a', 'b', 'a']; const result = countBy(array, x => x); // result will be { a: 3, b: 2, c: 1 } ``` ``` const array = [1, 2, 3, 4, 5]; const result = countBy(array, item => item % 2 === 0 ? 'even' : 'odd'); // result will be { odd: 3, even: 2 } ``` ``` // Using index parameter const array = ['a', 'b', 'c', 'd']; const result = countBy(array, (item, index) => index < 2 ? 'first' : 'rest'); // result will be { first: 2, rest: 2 } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### difference ``` const difference: typeof esToolkit_difference = esToolkit_difference; ``` Computes the difference between two arrays. This function takes two arrays and returns a new array containing the elements that are present in the first array but not in the second array. It effectively filters out any elements from the first array that also appear in the second array. #### Template #### Param The array from which to derive the difference. This is the primary array from which elements will be compared and filtered. #### Param The array containing elements to be excluded from the first array. Each element in this array will be checked against the first array, and if a match is found, that element will be excluded from the result. #### Returns A new array containing the elements that are present in the first array but not in the second array. #### Example ``` const array1 = [1, 2, 3, 4, 5]; const array2 = [2, 4]; const result = difference(array1, array2); // result will be [1, 3, 5] since 2 and 4 are in both arrays and are excluded from the result. ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### differenceBy ``` const differenceBy: typeof esToolkit_differenceBy = esToolkit_differenceBy; ``` Computes the difference between two arrays after mapping their elements through a provided function. This function takes two arrays and a mapper function. It returns a new array containing the elements that are present in the first array but not in the second array, based on the identity calculated by the mapper function. Essentially, it filters out any elements from the first array that, when mapped, match an element in the mapped version of the second array. #### Template U #### Param The primary array from which to derive the difference. #### Param The array containing elements to be excluded from the first array. #### Param The function to map the elements of both arrays. This function is applied to each element in both arrays, and the comparison is made based on the mapped values. #### Returns A new array containing the elements from the first array that do not have a corresponding mapped identity in the second array. #### Examples ``` const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]; const array2 = [{ id: 2 }, { id: 4 }]; const mapper = item => item.id; const result = differenceBy(array1, array2, mapper); // result will be [{ id: 1 }, { id: 3 }] since the elements with id 2 are in both arrays and are excluded from the result. ``` ``` const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]; const array2 = [2, 4]; const mapper = item => (typeof item === 'object' ? item.id : item); const result = differenceBy(array1, array2, mapper); // result will be [{ id: 1 }, { id: 3 }] since 2 is present in both arrays after mapping, and is excluded from the result. ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### differenceWith ``` const differenceWith: typeof esToolkit_differenceWith = esToolkit_differenceWith; ``` Computes the difference between two arrays based on a custom equality function. This function takes two arrays and a custom comparison function. It returns a new array containing the elements that are present in the first array but not in the second array. The comparison to determine if elements are equal is made using the provided custom function. #### Template U #### Param The array from which to get the difference. #### Param The array containing elements to exclude from the first array. #### Param A function to determine if two items are equal. #### Returns A new array containing the elements from the first array that do not match any elements in the second array according to the custom equality function. #### Examples ``` const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]; const array2 = [{ id: 2 }, { id: 4 }]; const areItemsEqual = (a, b) => a.id === b.id; const result = differenceWith(array1, array2, areItemsEqual); // result will be [{ id: 1 }, { id: 3 }] since the elements with id 2 are considered equal and are excluded from the result. ``` ``` const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]; const array2 = [2, 4]; const areItemsEqual = (a, b) => a.id === b; const result = differenceWith(array1, array2, areItemsEqual); // result will be [{ id: 1 }, { id: 3 }] since the element with id 2 is considered equal to the second array's element and is excluded from the result. ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### drop ``` const drop: typeof esToolkit_drop = esToolkit_drop; ``` Removes a specified number of elements from the beginning of an array and returns the rest. This function takes an array and a number, and returns a new array with the specified number of elements removed from the start. #### Template The type of elements in the array. #### Param The array from which to drop elements. #### Param The number of elements to drop from the beginning of the array. #### Returns A new array with the specified number of elements removed from the start. #### Example ``` const array = [1, 2, 3, 4, 5]; const result = drop(array, 2); // result will be [3, 4, 5] since the first two elements are dropped. ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### dropRight ``` const dropRight: typeof esToolkit_dropRight = esToolkit_dropRight; ``` Removes a specified number of elements from the end of an array and returns the rest. This function takes an array and a number, and returns a new array with the specified number of elements removed from the end. #### Template The type of elements in the array. #### Param The array from which to drop elements. #### Param The number of elements to drop from the end of the array. #### Returns A new array with the specified number of elements removed from the end. #### Example ``` const array = [1, 2, 3, 4, 5]; const result = dropRight(array, 2); // result will be [1, 2, 3] since the last two elements are dropped. ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### dropRightWhile ``` const dropRightWhile: typeof esToolkit_dropRightWhile = esToolkit_dropRightWhile; ``` Removes elements from the end of an array until the predicate returns false. This function iterates over an array from the end and drops elements until the provided predicate function returns false. It then returns a new array with the remaining elements. #### Template The type of elements in the array. #### Param The array from which to drop elements. #### Param A predicate function that determines whether to continue dropping elements. The function is called with each element from the end, and dropping continues as long as it returns true. #### Returns A new array with the elements remaining after the predicate returns false. #### Example ``` const array = [1, 2, 3, 4, 5]; const result = dropRightWhile(array, x => x > 3); // result will be [1, 2, 3] since elements greater than 3 are dropped from the end. ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### dropWhile ``` const dropWhile: typeof esToolkit_dropWhile = esToolkit_dropWhile; ``` Removes elements from the beginning of an array until the predicate returns false. This function iterates over an array and drops elements from the start until the provided predicate function returns false. It then returns a new array with the remaining elements. #### Template The type of elements in the array. #### Param The array from which to drop elements. #### Param A predicate function that determines whether to continue dropping elements. The function is called with each element, and dropping continues as long as it returns true. #### Returns A new array with the elements remaining after the predicate returns false. #### Example ``` const array = [1, 2, 3, 4, 5]; const result = dropWhile(array, x => x < 3); // result will be [3, 4, 5] since elements less than 3 are dropped. ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### flatMap ``` const flatMap: typeof esToolkit_flatMap = esToolkit_flatMap; ``` Maps each element in the array using the iteratee function and flattens the result up to the specified depth. #### Template The type of elements within the array. #### Template The type of elements within the returned array from the iteratee function. #### Template The depth to which the array should be flattened. #### Param The array to flatten. #### Param The function that produces the new array elements. It receives the element, its index, and the array. #### Param The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. #### Returns The new array with the mapped and flattened elements. #### Example ``` const arr = [1, 2, 3]; flatMap(arr, (item: number) => [item, item]); // [1, 1, 2, 2, 3, 3] flatMap(arr, (item: number) => [[item, item]], 2); // [1, 1, 2, 2, 3, 3] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### flatMapDeep ``` const flatMapDeep: typeof esToolkit_flatMapDeep = esToolkit_flatMapDeep; ``` Recursively maps each element in an array using a provided iteratee function and then deeply flattens the resulting array. #### Template The type of elements within the array. #### Template The type of elements within the returned array from the iteratee function. #### Param The array to flatten. #### Param The function that produces the new array elements. It receives the element, its index, and the array. #### Returns A new array that has been flattened. #### Example ``` const result = flatMapDeep([1, 2, 3], n => [[n, n]]); // [1, 1, 2, 2, 3, 3] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### flatten ``` const flatten: typeof esToolkit_flatten = esToolkit_flatten; ``` Flattens an array up to the specified depth. #### Template The type of elements within the array. #### Template The depth to which the array should be flattened. #### Param The array to flatten. #### Param The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. #### Returns A new array that has been flattened. #### Example ``` const arr = flatten([1, [2, 3], [4, [5, 6]]], 1); // Returns: [1, 2, 3, 4, [5, 6]] const arr = flatten([1, [2, 3], [4, [5, 6]]], 2); // Returns: [1, 2, 3, 4, 5, 6] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### flattenDeep ``` const flattenDeep: typeof esToolkit_flattenDeep = esToolkit_flattenDeep; ``` Utility type for recursively unpacking nested array types to extract the type of the innermost element #### Example ``` ExtractNestedArrayType<(number | (number | number[])[])[]> // number ExtractNestedArrayType<(boolean | (string | number[])[])[]> // string | number | boolean ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### groupBy ``` const groupBy: typeof esToolkit_groupBy = esToolkit_groupBy; ``` Groups the elements of an array based on a provided key-generating function. This function takes an array and a function that generates a key from each element. It returns an object where the keys are the generated keys and the values are arrays of elements that share the same key. #### Template The type of elements in the array. #### Template The type of keys. #### Param The array to group. #### Param A function that generates a key from an element, its index, and the array. #### Returns An object where each key is associated with an array of elements that share that key. #### Examples ``` const array = [ { category: 'fruit', name: 'apple' }, { category: 'fruit', name: 'banana' }, { category: 'vegetable', name: 'carrot' } ]; const result = groupBy(array, item => item.category); // result will be: // { // fruit: [ // { category: 'fruit', name: 'apple' }, // { category: 'fruit', name: 'banana' } // ], // vegetable: [ // { category: 'vegetable', name: 'carrot' } // ] // } ``` ``` // Using index parameter const items = ['a', 'b', 'c', 'd']; const result = groupBy(items, (item, index) => index % 2 === 0 ? 'even' : 'odd'); // result will be: { even: ['a', 'c'], odd: ['b', 'd'] } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### head ``` const head: typeof esToolkit_head = esToolkit_head; ``` Returns the first element of an array. This function takes an array and returns the first element of the array. If the array is empty, the function returns `undefined`. #### Template The type of elements in the array. #### Param A non-empty array from which to get the first element. #### Returns The first element of the array. #### Example ``` const arr = [1, 2, 3]; const firstElement = head(arr); // firstElement will be 1 ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### initial ``` const initial: typeof esToolkit_initial = esToolkit_initial; ``` Returns an empty array when the input is a tuple containing exactly one element. #### Template The type of the single element. #### Param A tuple containing exactly one element. #### Returns An empty array since there is only one element. #### Example ``` const array = [100] as const; const result = initial(array); // result will be [] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### intersection ``` const intersection: typeof esToolkit_intersection = esToolkit_intersection; ``` Returns the intersection of two arrays. This function takes two arrays and returns a new array containing the elements that are present in both arrays. It effectively filters out any elements from the first array that are not found in the second array. #### Template The type of elements in the array. #### Param The first array to compare. #### Param The second array to compare. #### Returns A new array containing the elements that are present in both arrays. #### Example ``` const array1 = [1, 2, 3, 4, 5]; const array2 = [3, 4, 5, 6, 7]; const result = intersection(array1, array2); // result will be [3, 4, 5] since these elements are in both arrays. ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### intersectionBy ``` const intersectionBy: typeof esToolkit_intersectionBy = esToolkit_intersectionBy; ``` Returns the intersection of two arrays based on a mapping function. This function takes two arrays and a mapping function. It returns a new array containing the elements from the first array that, when mapped using the provided function, have matching mapped elements in the second array. It effectively filters out any elements from the first array that do not have corresponding mapped values in the second array. #### Template The type of elements in the first array. #### Template The type of elements in the second array. #### Param The first array to compare. #### Param The second array to compare. #### Param A function to map the elements of both arrays for comparison. #### Returns A new array containing the elements from the first array that have corresponding mapped values in the second array. #### Examples ``` const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]; const array2 = [{ id: 2 }, { id: 4 }]; const mapper = item => item.id; const result = intersectionBy(array1, array2, mapper); // result will be [{ id: 2 }] since only this element has a matching id in both arrays. ``` ``` const array1 = [ { id: 1, name: 'jane' }, { id: 2, name: 'amy' }, { id: 3, name: 'michael' }, ]; const array2 = [2, 4]; const mapper = item => (typeof item === 'object' ? item.id : item); const result = intersectionBy(array1, array2, mapper); // result will be [{ id: 2, name: 'amy' }] since only this element has a matching id that is equal to seconds array's element. ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### intersectionWith ``` const intersectionWith: typeof esToolkit_intersectionWith = esToolkit_intersectionWith; ``` Returns the intersection of two arrays based on a custom equality function. This function takes two arrays and a custom equality function. It returns a new array containing the elements from the first array that have matching elements in the second array, as determined by the custom equality function. It effectively filters out any elements from the first array that do not have corresponding matches in the second array according to the equality function. #### Template The type of elements in the first array. #### Template The type of elements in the second array. #### Param The first array to compare. #### Param The second array to compare. #### Param A custom function to determine if two elements are equal. This function takes two arguments, one from each array, and returns `true` if the elements are considered equal, and `false` otherwise. #### Returns A new array containing the elements from the first array that have corresponding matches in the second array according to the custom equality function. #### Examples ``` const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]; const array2 = [{ id: 2 }, { id: 4 }]; const areItemsEqual = (a, b) => a.id === b.id; const result = intersectionWith(array1, array2, areItemsEqual); // result will be [{ id: 2 }] since this element has a matching id in both arrays. ``` ``` const array1 = [ { id: 1, name: 'jane' }, { id: 2, name: 'amy' }, { id: 3, name: 'michael' }, ]; const array2 = [2, 4]; const areItemsEqual = (a, b) => a.id === b; const result = intersectionWith(array1, array2, areItemsEqual); // result will be [{ id: 2, name: 'amy' }] since this element has a matching id that is equal to seconds array's element. ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isSubset ``` const isSubset: typeof esToolkit_isSubset = esToolkit_isSubset; ``` Checks if the `subset` array is entirely contained within the `superset` array. #### Template The type of elements contained in the arrays. #### Param The array that may contain all elements of the subset. #### Param The array to check against the superset. #### Returns - Returns `true` if all elements of the `subset` are present in the `superset`, otherwise returns `false`. #### Examples ``` const superset = [1, 2, 3, 4, 5]; const subset = [2, 3, 4]; isSubset(superset, subset); // true ``` ``` const superset = ['a', 'b', 'c']; const subset = ['a', 'd']; isSubset(superset, subset); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isSubsetWith ``` const isSubsetWith: typeof esToolkit_isSubsetWith = esToolkit_isSubsetWith; ``` Checks if the `subset` array is entirely contained within the `superset` array based on a custom equality function. This function takes two arrays and a custom comparison function. It returns a boolean indicating whether all elements in the subset array are present in the superset array, as determined by the provided custom equality function. #### Template The type of elements contained in the arrays. #### Param The array that may contain all elements of the subset. #### Param The array to check against the superset. #### Param A function to determine if two items are equal. #### Returns - Returns `true` if all elements of the subset are present in the superset according to the custom equality function, otherwise returns `false`. #### Examples ``` const superset = [{ id: 1 }, { id: 2 }, { id: 3 }]; const subset = [{ id: 2 }, { id: 1 }]; const areItemsEqual = (a, b) => a.id === b.id; isSubsetWith(superset, subset, areItemsEqual); // true ``` ``` const superset = [{ id: 1 }, { id: 2 }, { id: 3 }]; const subset = [{ id: 4 }]; const areItemsEqual = (a, b) => a.id === b.id; isSubsetWith(superset, subset, areItemsEqual); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### keyBy ``` const keyBy: typeof esToolkit_keyBy = esToolkit_keyBy; ``` Maps each element of an array based on a provided key-generating function. This function takes an array and a function that generates a key from each element. It returns an object where the keys are the generated keys and the values are the corresponding elements. If there are multiple elements generating the same key, the last element among them is used as the value. #### Template The type of elements in the array. #### Template The type of keys. #### Param The array of elements to be mapped. #### Param A function that generates a key from an element, its index, and the array. #### Returns An object where keys are mapped to each element of an array. #### Examples ``` const array = [ { category: 'fruit', name: 'apple' }, { category: 'fruit', name: 'banana' }, { category: 'vegetable', name: 'carrot' } ]; const result = keyBy(array, item => item.category); // result will be: // { // fruit: { category: 'fruit', name: 'banana' }, // vegetable: { category: 'vegetable', name: 'carrot' } // } ``` ``` // Using index parameter const items = ['a', 'b', 'c']; const result = keyBy(items, (item, index) => index); // result will be: { 0: 'a', 1: 'b', 2: 'c' } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### last ``` const last: typeof esToolkit_last = esToolkit_last; ``` Returns the last element of an array. This function takes an array and returns the last element of the array. If the array is empty, the function returns `undefined`. Unlike some implementations, this function is optimized for performance by directly accessing the last index of the array. #### Template The type of elements in the array. #### Param The array from which to get the last element. #### Returns The last element of the array, or `undefined` if the array is empty. #### Example ``` const arr = [1, 2, 3]; const lastElement = last(arr); // lastElement will be 3 const emptyArr: number[] = []; const noElement = last(emptyArr); // noElement will be undefined ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### maxBy ``` const maxBy: typeof esToolkit_maxBy = esToolkit_maxBy; ``` Finds the element in an array that has the maximum value when applying the `getValue` function to each element. #### Template The type of elements in the array. #### Param The nonempty array of elements to search. #### Param A function that selects a numeric value from each element. #### Returns The element with the maximum value as determined by the `getValue` function. #### Example ``` maxBy([{ a: 1 }, { a: 2 }, { a: 3 }], x => x.a); // Returns: { a: 3 } maxBy([], x => x.a); // Returns: undefined maxBy( [ { name: 'john', age: 30 }, { name: 'jane', age: 28 }, { name: 'joe', age: 26 }, ], x => x.age ); // Returns: { name: 'john', age: 30 } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### minBy ``` const minBy: typeof esToolkit_minBy = esToolkit_minBy; ``` Finds the element in an array that has the minimum value when applying the `getValue` function to each element. #### Template The type of elements in the array. #### Param The nonempty array of elements to search. #### Param A function that selects a numeric value from each element. #### Returns The element with the minimum value as determined by the `getValue` function. #### Example ``` minBy([{ a: 1 }, { a: 2 }, { a: 3 }], x => x.a); // Returns: { a: 1 } minBy([], x => x.a); // Returns: undefined minBy( [ { name: 'john', age: 30 }, { name: 'jane', age: 28 }, { name: 'joe', age: 26 }, ], x => x.age ); // Returns: { name: 'joe', age: 26 } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### orderBy ``` const orderBy: typeof esToolkit_orderBy = esToolkit_orderBy; ``` Sorts an array of objects based on the given `criteria` and their corresponding order directions. - If you provide keys, it sorts the objects by the values of those keys. - If you provide functions, it sorts based on the values returned by those functions. The function returns the array of objects sorted in corresponding order directions. If two objects have the same value for the current criterion, it uses the next criterion to determine their order. If the number of orders is less than the number of criteria, it uses the last order for the rest of the criteria. #### Template The type of elements in the array. #### Param The array of objects to be sorted. #### Param The criteria for sorting. This can be an array of object keys or functions that return values used for sorting. #### Param An array of order directions ('asc' for ascending or 'desc' for descending). #### Returns - The sorted array. #### Example ``` // Sort an array of objects by 'user' in ascending order and 'age' in descending order. const users = [ { user: 'fred', age: 48 }, { user: 'barney', age: 34 }, { user: 'fred', age: 40 }, { user: 'barney', age: 36 }, ]; const result = orderBy(users, [obj => obj.user, 'age'], ['asc', 'desc']); // result will be: // [ // { user: 'barney', age: 36 }, // { user: 'barney', age: 34 }, // { user: 'fred', age: 48 }, // { user: 'fred', age: 40 }, // ] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### partition ``` const partition: typeof esToolkit_partition = esToolkit_partition; ``` Splits an array into two groups based on a predicate function. This function takes an array and a predicate function. It returns a tuple of two arrays: the first array contains elements for which the predicate function returns true, and the second array contains elements for which the predicate function returns false. #### Template The type of elements in the array. #### Template The type being filtered for. #### Param The array to partition. #### Param A type guard that determines whether an element should be placed in the truthy array. The function is called with each element of the array and its index. #### Returns A tuple containing two arrays: the first array contains elements for which the predicate returned true, and the second array contains elements for which the predicate returned false. #### Example ``` const array = [1, 2, 3, 4] as const; const isEven = (x: number): x is 2 | 4 => x % 2 === 0; const [even, odd]: [(2 | 4)[], (2 | 4)[]] = partition(array, isEven); // even will be [2, 4], and odd will be [1, 3] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### sortBy ``` const sortBy: typeof esToolkit_sortBy = esToolkit_sortBy; ``` Sorts an array of objects based on the given `criteria`. - If you provide keys, it sorts the objects by the values of those keys. - If you provide functions, it sorts based on the values returned by those functions. The function returns the array of objects sorted in ascending order. If two objects have the same value for the current criterion, it uses the next criterion to determine their order. #### Template The type of the objects in the array. #### Param The array of objects to be sorted. #### Param The criteria for sorting. This can be an array of object keys or functions that return values used for sorting. #### Returns - The sorted array. #### Example ``` const users = [ { user: 'foo', age: 24 }, { user: 'bar', age: 7 }, { user: 'foo', age: 8 }, { user: 'bar', age: 29 }, ]; sortBy(users, ['user', 'age']); sortBy(users, [obj => obj.user, 'age']); // results will be: // [ // { user : 'bar', age: 7 }, // { user : 'bar', age: 29 }, // { user : 'foo', age: 8 }, // { user : 'foo', age: 24 }, // ] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### tail ``` const tail: typeof esToolkit_tail = esToolkit_tail; ``` Returns an empty array when the input is a single-element array. #### Template The type of the single element in the array. #### Param The single-element array to process. #### Returns An empty array. #### Example ``` const arr = [1]; const result = tail(arr); // result will be [] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### take ``` const take: typeof esToolkit_take = esToolkit_take; ``` Returns a new array containing the first `count` elements from the input array `arr`. If `count` is greater than the length of `arr`, the entire array is returned. #### Template Type of elements in the input array. #### Param The array to take elements from. #### Param The number of elements to take. #### Param If truthy, ignores `count` and defaults to 1. #### Returns A new array containing the first `count` elements from `arr`. #### Examples ``` // Returns [1, 2, 3] take([1, 2, 3, 4, 5], 3); ``` ``` // Returns ['a', 'b'] take(['a', 'b', 'c'], 2); ``` ``` // Returns [1, 2, 3] take([1, 2, 3], 5); ``` ``` // Returns [[1], [1], [1]] const arr = [1, 2, 3]; const result = arr.map((v, i, array) => take(array, i, true)); ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### takeRight ``` const takeRight: typeof esToolkit_takeRight = esToolkit_takeRight; ``` Returns a new array containing the last `count` elements from the input array `arr`. If `count` is greater than the length of `arr`, the entire array is returned. #### Template The type of elements in the array. #### Param The array to take elements from. #### Param The number of elements to take. #### Returns A new array containing the last `count` elements from `arr`. #### Examples ``` // Returns [4, 5] takeRight([1, 2, 3, 4, 5], 2); ``` ``` // Returns ['b', 'c'] takeRight(['a', 'b', 'c'], 2); ``` ``` // Returns [1, 2, 3] takeRight([1, 2, 3], 5); ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### takeRightWhile ``` const takeRightWhile: typeof esToolkit_takeRightWhile = esToolkit_takeRightWhile; ``` Takes elements from the end of the array while the predicate function returns `true`. #### Template Type of elements in the input array. #### Param The array to take elements from. #### Param The function invoked per element with the item, its index, and the array. #### Returns A new array containing the elements taken from the end while the predicate returns `true`. #### Examples ``` // Returns [3, 2, 1] takeRightWhile([5, 4, 3, 2, 1], n => n < 4); ``` ``` // Returns [] takeRightWhile([1, 2, 3], n => n > 3); ``` ``` // Using index parameter takeRightWhile([10, 20, 30, 40], (x, index) => index > 1); // Returns: [30, 40] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### takeWhile ``` const takeWhile: typeof esToolkit_takeWhile = esToolkit_takeWhile; ``` Returns a new array containing the leading elements of the provided array that satisfy the provided predicate function. It stops taking elements as soon as an element does not satisfy the predicate. #### Template The type of elements in the array. #### Param The array to process. #### Param The predicate function that is called with each element, its index, and the array. Elements are included in the result as long as this function returns true. #### Returns A new array containing the leading elements that satisfy the predicate. #### Examples ``` // Returns [1, 2] takeWhile([1, 2, 3, 4], x => x < 3); ``` ``` // Returns [] takeWhile([1, 2, 3, 4], x => x > 3); ``` ``` // Using index parameter takeWhile([10, 20, 30, 40], (x, index) => index < 2); // Returns: [10, 20] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### toFilled ``` const toFilled: typeof esToolkit_toFilled = esToolkit_toFilled; ``` Creates a new array filled with the specified value from the start position up to, but not including, the end position. This function does not mutate the original array. #### Template The type of elements in the original array. #### Template The type of the value to fill the new array with. #### Param The array to base the new array on. #### Param The value to fill the new array with. #### Returns The new array with the filled values. #### Example ``` const array = [1, 2, 3, 4, 5]; let result = toFilled(array, '*', 2); console.log(result); // [1, 2, '*', '*', '*'] console.log(array); // [1, 2, 3, 4, 5] result = toFilled(array, '*', 1, 4); console.log(result); // [1, '*', '*', '*', 5] console.log(array); // [1, 2, 3, 4, 5] result = toFilled(array, '*'); console.log(result); // ['*', '*', '*', '*', '*'] console.log(array); // [1, 2, 3, 4, 5] result = toFilled(array, '*', -4, -1); console.log(result); // [1, '*', '*', '*', 5] console.log(array); // [1, 2, 3, 4, 5] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### union ``` const union: typeof esToolkit_union = esToolkit_union; ``` Creates an array of unique values from all given arrays. This function takes two arrays, merges them into a single array, and returns a new array containing only the unique values from the merged array. #### Template The type of elements in the array. #### Param The first array to merge and filter for unique values. #### Param The second array to merge and filter for unique values. #### Returns A new array of unique values. #### Example ``` const array1 = [1, 2, 3]; const array2 = [3, 4, 5]; const result = union(array1, array2); // result will be [1, 2, 3, 4, 5] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### unionBy ``` const unionBy: typeof esToolkit_unionBy = esToolkit_unionBy; ``` Creates an array of unique values, in order, from all given arrays using a provided mapping function to determine equality. #### Template The type of elements in the array. #### Template The type of mapped elements. #### Param The first array. #### Param The second array. #### Param The function to map array elements to comparison values. #### Returns A new array containing the union of unique elements from `arr1` and `arr2`, based on the values returned by the mapping function. #### Examples ``` // Custom mapping function for numbers (modulo comparison) const moduloMapper = (x) => x % 3; unionBy([1, 2, 3], [4, 5, 6], moduloMapper); // Returns [1, 2, 3] ``` ``` // Custom mapping function for objects with an 'id' property const idMapper = (obj) => obj.id; unionBy([{ id: 1 }, { id: 2 }], [{ id: 2 }, { id: 3 }], idMapper); // Returns [{ id: 1 }, { id: 2 }, { id: 3 }] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### unionWith ``` const unionWith: typeof esToolkit_unionWith = esToolkit_unionWith; ``` Creates an array of unique values from two given arrays based on a custom equality function. This function takes two arrays and a custom equality function, merges the arrays, and returns a new array containing only the unique values as determined by the custom equality function. #### Template The type of elements in the array. #### Param The first array to merge and filter for unique values. #### Param The second array to merge and filter for unique values. #### Param A custom function to determine if two elements are equal. It takes two arguments and returns `true` if the elements are considered equal, and `false` otherwise. #### Returns A new array of unique values based on the custom equality function. #### Example ``` const array1 = [{ id: 1 }, { id: 2 }]; const array2 = [{ id: 2 }, { id: 3 }]; const areItemsEqual = (a, b) => a.id === b.id; const result = unionWith(array1, array2, areItemsEqual); // result will be [{ id: 1 }, { id: 2 }, { id: 3 }] since { id: 2 } is considered equal in both arrays ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### uniq ``` const uniq: typeof esToolkit_uniq = esToolkit_uniq; ``` Creates a duplicate-free version of an array. This function takes an array and returns a new array containing only the unique values from the original array, preserving the order of first occurrence. #### Template The type of elements in the array. #### Param The array to process. #### Returns A new array with only unique values from the original array. #### Example ``` const array = [1, 2, 2, 3, 4, 4, 5]; const result = uniq(array); // result will be [1, 2, 3, 4, 5] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### uniqBy ``` const uniqBy: typeof esToolkit_uniqBy = esToolkit_uniqBy; ``` Returns a new array containing only the unique elements from the original array, based on the values returned by the mapper function. When duplicates are found, the first occurrence is kept and the rest are discarded. #### Template The type of elements in the array. #### Template The type of mapped elements. #### Param The array to process. #### Param The function used to convert the array elements. #### Returns A new array containing only the unique elements from the original array, based on the values returned by the mapper function. #### Examples ``` uniqBy([1.2, 1.5, 2.1, 3.2, 5.7, 5.3, 7.19], Math.floor); // [1.2, 2.1, 3.2, 5.7, 7.19] ``` const array = [ { category: 'fruit', name: 'apple' }, { category: 'fruit', name: 'banana' }, { category: 'vegetable', name: 'carrot' }, ]; uniqBy(array, item => item.category).length // 2 ```` @see Powered by `es-toolkit` (MIT License): [https://github.com/toss/es-toolkit](https://github.com/toss/es-toolkit) *** ### uniqWith ```ts const uniqWith: typeof esToolkit_uniqWith = esToolkit_uniqWith; ```` Returns a new array containing only the unique elements from the original array, based on the values returned by the comparator function. #### Template The type of elements in the array. #### Param The array to process. #### Param The function used to compare the array elements. #### Returns A new array containing only the unique elements from the original array, based on the values returned by the comparator function. #### Example ``` uniqWith([1.2, 1.5, 2.1, 3.2, 5.7, 5.3, 7.19], (a, b) => Math.abs(a - b) < 1); // [1.2, 3.2, 5.7, 7.19] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### unzip ``` const unzip: typeof esToolkit_unzip = esToolkit_unzip; ``` Gathers elements in the same position in an internal array from a grouped array of elements and returns them as a new array. #### Template The type of elements in the nested array. #### Param The nested array to unzip. #### Returns A new array of unzipped elements. #### Example ``` const zipped = [['a', true, 1],['b', false, 2]]; const result = unzip(zipped); // result will be [['a', 'b'], [true, false], [1, 2]] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### unzipWith ``` const unzipWith: typeof esToolkit_unzipWith = esToolkit_unzipWith; ``` Unzips an array of arrays, applying an `iteratee` function to regrouped elements. #### Template R #### Param The nested array to unzip. This is an array of arrays, where each inner array contains elements to be unzipped. #### Param A function to transform the unzipped elements. #### Returns A new array of unzipped and transformed elements. #### Example ``` const nestedArray = [[1, 2], [3, 4], [5, 6]]; const result = unzipWith(nestedArray, (item, item2, item3) => item + item2 + item3); // result will be [9, 12] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### windowed ``` const windowed: typeof esToolkit_windowed = esToolkit_windowed; ``` **`Interface`** Options for the windowed function. WindowedOptions #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### without ``` const without: typeof esToolkit_without = esToolkit_without; ``` Creates an array that excludes all specified values. It correctly excludes `NaN`, as it compares values using [SameValueZero](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-samevaluezero). #### Template The type of elements in the array. #### Param The array to filter. #### Param The values to exclude. #### Returns A new array without the specified values. #### Examples ``` // Removes the specified values from the array without([1, 2, 3, 4, 5], 2, 4); // Returns: [1, 3, 5] ``` ``` // Removes specified string values from the array without(['a', 'b', 'c', 'a'], 'a'); // Returns: ['b', 'c'] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### xor ``` const xor: typeof esToolkit_xor = esToolkit_xor; ``` Computes the symmetric difference between two arrays. The symmetric difference is the set of elements which are in either of the arrays, but not in their intersection. #### Template The type of elements in the array. #### Param The first array. #### Param The second array. #### Returns An array containing the elements that are present in either `arr1` or `arr2` but not in both. #### Examples ``` // Returns [1, 2, 5, 6] xor([1, 2, 3, 4], [3, 4, 5, 6]); ``` ``` // Returns ['a', 'c'] xor(['a', 'b'], ['b', 'c']); ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### xorBy ``` const xorBy: typeof esToolkit_xorBy = esToolkit_xorBy; ``` Computes the symmetric difference between two arrays using a custom mapping function. The symmetric difference is the set of elements which are in either of the arrays, but not in their intersection, determined by the result of the mapping function. #### Template Type of elements in the input arrays. #### Template Type of the values returned by the mapping function. #### Param The first array. #### Param The second array. #### Param The function to map array elements to comparison values. #### Returns An array containing the elements that are present in either `arr1` or `arr2` but not in both, based on the values returned by the mapping function. #### Example ``` // Custom mapping function for objects with an 'id' property const idMapper = obj => obj.id; xorBy([{ id: 1 }, { id: 2 }], [{ id: 2 }, { id: 3 }], idMapper); // Returns [{ id: 1 }, { id: 3 }] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### xorWith ``` const xorWith: typeof esToolkit_xorWith = esToolkit_xorWith; ``` Computes the symmetric difference between two arrays using a custom equality function. The symmetric difference is the set of elements which are in either of the arrays, but not in their intersection. #### Template Type of elements in the input arrays. #### Param The first array. #### Param The second array. #### Param The custom equality function to compare elements. #### Returns An array containing the elements that are present in either `arr1` or `arr2` but not in both, based on the custom equality function. #### Example ``` // Custom equality function for objects with an 'id' property const areObjectsEqual = (a, b) => a.id === b.id; xorWith([{ id: 1 }, { id: 2 }], [{ id: 2 }, { id: 3 }], areObjectsEqual); // Returns [{ id: 1 }, { id: 3 }] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### zip ``` const zip: typeof esToolkit_zip = esToolkit_zip; ``` Combines multiple arrays into a single array of tuples. This function takes multiple arrays and returns a new array where each element is a tuple containing the corresponding elements from the input arrays. If the input arrays are of different lengths, the resulting array will have the length of the longest input array, with undefined values for missing elements. #### Template #### Param The first array to zip. #### Returns A new array of tuples containing the corresponding elements from the input arrays. #### Example ``` const arr1 = [1, 2, 3]; const result = zip(arr1); // result will be [[1], [2], [3]] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### zipObject ``` const zipObject: typeof esToolkit_zipObject = esToolkit_zipObject; ``` Combines two arrays, one of property names and one of corresponding values, into a single object. This function takes two arrays: one containing property names and another containing corresponding values. It returns a new object where the property names from the first array are keys, and the corresponding elements from the second array are values. If the `keys` array is longer than the `values` array, the remaining keys will have `undefined` as their values. #### Template The type of elements in the array. #### Template The type of elements in the array. #### Param An array of property names. #### Param An array of values corresponding to the property names. #### Returns - A new object composed of the given property names and values. #### Example ``` const keys = ['a', 'b', 'c']; const values = [1, 2, 3]; const result = zipObject(keys, values); // result will be { a: 1, b: 2, c: 3 } const keys2 = ['a', 'b', 'c']; const values2 = [1, 2]; const result2 = zipObject(keys2, values2); // result2 will be { a: 1, b: 2, c: undefined } const keys2 = ['a', 'b']; const values2 = [1, 2, 3]; const result2 = zipObject(keys2, values2); // result2 will be { a: 1, b: 2 } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### zipWith ``` const zipWith: typeof esToolkit_zipWith = esToolkit_zipWith; ``` Combines multiple arrays into a single array using a custom combiner function. This function takes multiple arrays and a combiner function, and returns a new array where each element is the result of applying the combiner function to the corresponding elements of the input arrays. #### Template The type of elements in the first array. #### Template The type of elements in the resulting array. #### Param The first array to zip. #### Param The combiner function that takes corresponding elements from each array, their index, and returns a single value. #### Returns A new array where each element is the result of applying the combiner function to the corresponding elements of the input arrays. #### Examples ``` // Example usage with two arrays: const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const result = zipWith(arr1, arr2, (a, b) => a + b); // result will be [5, 7, 9] ``` ``` // Example usage with three arrays: const arr1 = [1, 2]; const arr2 = [3, 4]; const arr3 = [5, 6]; const result = zipWith(arr1, arr2, arr3, (a, b, c) => `${a}${b}${c}`); // result will be [`135`, `246`] ``` #### See Powered by `es-toolkit` (MIT License): # crypto ## Functions ### hash() ``` function hash(input): string; ``` Hashes any JavaScript value into a deterministic string. The value is serialized first and then hashed, which makes this helper useful for cache keys, content fingerprints, and change detection inside plugins. This helper is not intended for password hashing or other security-sensitive cryptographic workflows. #### Parameters ##### input `unknown` Any JavaScript value to hash. #### Returns `string` A stable hash string for the provided input. #### Example ``` hash({ foo: "bar" }); // returns a deterministic hash string such as "g82Nh7Lh3CUR..." ``` #### See Powered by `ohash` (MIT): # functions ## Variables ### after ``` const after: typeof esToolkit_after = esToolkit_after; ``` Creates a function that only executes starting from the `n`-th call. The provided function will be invoked starting from the `n`-th call. This is particularly useful for scenarios involving events or asynchronous operations where an action should occur only after a certain number of invocations. #### Template The type of the function to be invoked. #### Param The number of calls required for `func` to execute. #### Param The function to be invoked. #### Returns - A new function that: - Tracks the number of calls. - Invokes `func` starting from the `n`-th call. - Returns `undefined` if fewer than `n` calls have been made. #### Throws - Throws an error if `n` is negative. #### Example ``` const afterFn = after(3, () => { console.log("called") }); // Will not log anything. afterFn() // Will not log anything. afterFn() // Will log 'called'. afterFn() ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### ary ``` const ary: typeof esToolkit_ary = esToolkit_ary; ``` Creates a function that invokes func, with up to n arguments, ignoring any additional arguments. #### Template The type of the function. #### Param The function to cap arguments for. #### Param The arity cap. #### Returns Returns the new capped function. #### Example ``` function fn(a: number, b: number, c: number) { return Array.from(arguments); } ary(fn, 0)(1, 2, 3) // [] ary(fn, 1)(1, 2, 3) // [1] ary(fn, 2)(1, 2, 3) // [1, 2] ary(fn, 3)(1, 2, 3) // [1, 2, 3] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### before ``` const before: typeof esToolkit_before = esToolkit_before; ``` Creates a function that limits the number of times the given function (`func`) can be called. #### Template The type of the function to be invoked. #### Param The number of times the returned function is allowed to call `func` before stopping. - If `n` is 0, `func` will never be called. - If `n` is a positive integer, `func` will be called up to `n-1` times. #### Param The function to be called with the limit applied. #### Returns - A new function that: - Tracks the number of calls. - Invokes `func` until the `n-1`-th call. - Returns `undefined` if the number of calls reaches or exceeds `n`, stopping further calls. #### Throws - Throw an error if `n` is negative. #### Example ``` const beforeFn = before(3, () => { console.log("called"); }) // Will log 'called'. beforeFn(); // Will log 'called'. beforeFn(); // Will not log anything. beforeFn(); ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### curry ``` const curry: typeof esToolkit_curry = esToolkit_curry; ``` Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. #### Param The function to curry. #### Returns A curried function. #### Example ``` function noArgFunc() { return 42; } const curriedNoArgFunc = curry(noArgFunc); console.log(curriedNoArgFunc()); // 42 ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### curryRight ``` const curryRight: typeof esToolkit_curryRight = esToolkit_curryRight; ``` Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. Unlike `curry`, this function curries the function from right to left. #### Param The function to curry. #### Returns A curried function. #### Example ``` function noArgFunc() { return 42; } const curriedNoArgFunc = curryRight(noArgFunc); console.log(curriedNoArgFunc()); // 42 ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### flow ``` const flow: typeof esToolkit_flow = esToolkit_flow; ``` Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. The `this` context of the returned function is also passed to the functions provided as parameters. #### Param The function to invoke. #### Returns Returns the new composite function. #### Example ``` function noArgFunc() { return 42; } const combined = flow(noArgFunc); console.log(combined()); // 42 ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### flowRight ``` const flowRight: typeof esToolkit_flowRight = esToolkit_flowRight; ``` Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. The `this` context of the returned function is also passed to the functions provided as parameters. This method is like `flow` except that it creates a function that invokes the given functions from right to left. #### Param The function to invoke. #### Returns Returns the new composite function. #### Example ``` function noArgFunc() { return 42; } const combined = flowRight(noArgFunc); console.log(combined()); // 42 ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### identity ``` const identity: typeof esToolkit_identity = esToolkit_identity; ``` Returns the input value unchanged. #### Template The type of the input value. #### Param The value to be returned. #### Returns The input value. #### Examples ``` // Returns 5 identity(5); ``` ``` // Returns 'hello' identity('hello'); ``` ``` // Returns { key: 'value' } identity({ key: 'value' }); ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### memoize ``` const memoize: typeof esToolkit_memoize = esToolkit_memoize; ``` Creates a memoized version of the provided function. The memoized function caches results based on the argument it receives, so if the same argument is passed again, it returns the cached result instead of recomputing it. This function works with functions that take zero or just one argument. If your function originally takes multiple arguments, you should refactor it to take a single object or array that combines those arguments. If the argument is not primitive (e.g., arrays or objects), provide a `getCacheKey` function to generate a unique cache key for proper caching. #### Template The type of the function to be memoized. #### Param The function to be memoized. It should accept a single argument and return a value. #### Param Optional configuration for the memoization. #### Param The cache object used to store results. Defaults to a new `Map`. #### Param An optional function to generate a unique cache key for each argument. #### Returns The memoized function with an additional `cache` property that exposes the internal cache. #### Examples ``` // Example using the default cache const add = (x: number) => x + 10; const memoizedAdd = memoize(add); console.log(memoizedAdd(5)); // 15 console.log(memoizedAdd(5)); // 15 (cached result) console.log(memoizedAdd.cache.size); // 1 ``` ``` // Example using a custom resolver const sum = (arr: number[]) => arr.reduce((x, y) => x + y, 0); const memoizedSum = memoize(sum, { getCacheKey: (arr: number[]) => arr.join(',') }); console.log(memoizedSum([1, 2])); // 3 console.log(memoizedSum([1, 2])); // 3 (cached result) console.log(memoizedSum.cache.size); // 1 ``` ``` // Example using a custom cache implementation class CustomCache implements MemoizeCache { private cache = new Map(); set(key: K, value: T): void { this.cache.set(key, value); } get(key: K): T | 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 CustomCache(); const memoizedSumWithCustomCache = memoize(sum, { cache: customCache }); console.log(memoizedSumWithCustomCache([1, 2])); // 3 console.log(memoizedSumWithCustomCache([1, 2])); // 3 (cached result) console.log(memoizedAddWithCustomCache.cache.size); // 1 ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### negate ``` const negate: typeof esToolkit_negate = esToolkit_negate; ``` Creates a function that negates the result of the predicate function. #### Template The type of the function to negate. #### Param The function to negate. #### Returns The new negated function, which negates the boolean result of `func`. #### Example ``` const array = [1, 2, 3, 4, 5, 6]; const isEven = (n: number) => n % 2 === 0; const result = array.filter(negate(isEven)); // result will be [1, 3, 5] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### noop ``` const noop: typeof esToolkit_noop = esToolkit_noop; ``` A no-operation function that does nothing. This can be used as a placeholder or default function. #### Example ``` noop(); // Does nothing ``` #### Returns This function does not return anything. #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### once ``` const once: typeof esToolkit_once = esToolkit_once; ``` Creates a function that is restricted to invoking func once. Repeat calls to the function return the value of the first invocation. #### Template The type of the function. #### Param The function to restrict. #### Returns Returns the new restricted function. #### Example ``` const initialize = once(createApplication); initialize(); initialize(); // => `createApplication` is invoked once ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### partial ``` const partial: typeof esToolkit_partial = esToolkit_partial; ``` Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. Note: This method doesn't set the `length` property of partially applied functions. #### Template The type of the first argument. #### Template The return type of the function. #### Param The function to partially apply. #### Param The first argument to apply. #### Returns A new function that takes no arguments and returns the result of the original function. #### Example ``` const addOne = (x: number) => x + 1; const addOneToFive = partial(addOne, 5); console.log(addOneToFive()); // => 6 ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### partialRight ``` const partialRight: typeof esToolkit_partialRight = esToolkit_partialRight; ``` This method is like `partial` except that partially applied arguments are appended to the arguments it receives. The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. Note: This method doesn't set the `length` property of partially applied functions. #### Template The return type of the function. #### Param The function to invoke. #### Returns Returns the new function. #### Example ``` const getValue = () => 42; const getValueFunc = partialRight(getValue); console.log(getValueFunc()); // => 42 ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### rest ``` const rest: typeof esToolkit_rest = esToolkit_rest; ``` Creates a function that transforms the arguments of the provided function `func`. The transformed arguments are passed to `func` such that the arguments starting from a specified index are grouped into an array, while the previous arguments are passed as individual elements. #### Template The type of the function being transformed. #### Param The function whose arguments are to be transformed. #### Param The index from which to start grouping the remaining arguments into an array. Defaults to `func.length - 1`, grouping all arguments after the last parameter. #### Returns A new function that, when called, returns the result of calling `func` with the transformed arguments. The transformed arguments are: - The first `start` arguments as individual elements. - The remaining arguments from index `start` onward grouped into an array. #### Example ``` function fn(a, b, c) { return [a, b, c]; } // Using default start index (func.length - 1, which is 2 in this case) const transformedFn = rest(fn); console.log(transformedFn(1, 2, 3, 4)); // [1, 2, [3, 4]] // Using start index 1 const transformedFnWithStart = rest(fn, 1); console.log(transformedFnWithStart(1, 2, 3, 4)); // [1, [2, 3, 4]] // With fewer arguments than the start index console.log(transformedFn(1)); // [1, undefined, []] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### spread ``` const spread: typeof esToolkit_spread = esToolkit_spread; ``` Creates a new function that spreads elements of an array argument into individual arguments for the original function. #### Template A function type with any number of parameters and any return type. #### Param The function to be transformed. It can be any function with any number of arguments. #### Returns - A new function that takes an array of arguments and returns the result of calling the original function with those arguments. #### Example ``` function add(a, b) { return a + b; } const spreadAdd = spread(add); console.log(spreadAdd([1, 2])); // Output: 3 ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### unary ``` const unary: typeof esToolkit_unary = esToolkit_unary; ``` Creates a function that accepts up to one argument, ignoring any additional arguments. #### Template The type of the function. #### Param The function to cap arguments for. #### Returns Returns the new capped function. #### Example ``` function fn(a, b, c) { console.log(arguments); } unary(fn)(1, 2, 3); // [Arguments] { '0': 1 } ``` #### See Powered by `es-toolkit` (MIT License): # ir ## Functions ### getAnnotation() ``` function getAnnotation(annotations, name): Annotation | undefined; ``` Returns the first annotation that matches the provided name. Annotation names are compared exactly as stored in the IR, without adding or removing an `@` prefix. #### Parameters ##### annotations Annotation list to search. [`Annotation`](https://vdl-plugin-sdk.varavel.com/api/core/#annotation)[] | `undefined` ##### name `string` Annotation name to match. #### Returns [`Annotation`](https://vdl-plugin-sdk.varavel.com/api/core/#annotation) | `undefined` The matching annotation, or `undefined` when it is not present. #### Example ``` const annotation = getAnnotation(field.annotations, "deprecated"); // returns the first `deprecated` annotation or undefined ``` ______________________________________________________________________ ### getAnnotationArg() ``` function getAnnotationArg(annotations, name): LiteralValue | undefined; ``` Returns the raw literal argument stored in an annotation. VDL annotations currently expose a single literal argument. Pair this helper with `unwrapLiteral` when you need a plain JavaScript value. #### Parameters ##### annotations Annotation list to search. [`Annotation`](https://vdl-plugin-sdk.varavel.com/api/core/#annotation)[] | `undefined` ##### name `string` Annotation name whose argument should be returned. #### Returns [`LiteralValue`](https://vdl-plugin-sdk.varavel.com/api/core/#literalvalue) | `undefined` The annotation argument as a `LiteralValue`, or `undefined` when the annotation or argument is missing. #### Example ``` const arg = getAnnotationArg(field.annotations, "length"); // returns the raw annotation literal, such as { kind: "int", intValue: 64, ... } ``` ______________________________________________________________________ ### unwrapLiteral() ``` function unwrapLiteral(value): T; ``` Resolves a `LiteralValue` into its native JavaScript representation. Pass a generic when you already know the expected shape. Omit it to get `unknown` and narrow the result yourself. The generic only affects TypeScript types. It does not validate the runtime value. #### Type Parameters ##### T `T` = `unknown` #### Parameters ##### value [`LiteralValue`](https://vdl-plugin-sdk.varavel.com/api/core/#literalvalue) The VDL literal to convert. #### Returns `T` The recursively unwrapped JavaScript value. #### Examples ``` const raw = unwrapLiteral({ position: { file: "schema.vdl", line: 1, column: 1 }, kind: "string", stringValue: "hello", }); // returns "hello" ``` ``` const value = unwrapLiteral<{ enabled: boolean }>( { position: { file: "schema.vdl", line: 1, column: 1 }, kind: "object", objectEntries: [ { position: { file: "schema.vdl", line: 1, column: 1 }, key: "enabled", value: { position: { file: "schema.vdl", line: 1, column: 1 }, kind: "bool", boolValue: true, }, }, ], }, ); // returns { enabled: true } ``` # maps ## Variables ### every ``` const every: typeof esToolkit_every = esToolkit_every; ``` Tests whether all entries in a Map satisfy the provided predicate function. This function iterates through all entries of the Map and checks if the predicate function returns true for every entry. It returns true if the predicate is satisfied for all entries, and false otherwise. #### Template The type of keys in the Map. #### Template The type of values in the Map. #### Param The Map to test. #### Param A predicate function that tests each entry. #### Returns true if all entries satisfy the predicate, false otherwise. #### Example ``` const map = new Map([ ['a', 10], ['b', 20], ['c', 30] ]); const result = every(map, (value) => value > 5); // result will be: true const result2 = every(map, (value) => value > 15); // result2 will be: false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### filter ``` const filter: typeof esToolkit_filter = esToolkit_filter; ``` Filters a Map based on a predicate function. This function takes a Map and a predicate function, and returns a new Map containing only the entries for which the predicate function returns true. #### Template The type of keys in the Map. #### Template The type of values in the Map. #### Param The Map to filter. #### Param A predicate function that tests each entry. #### Returns A new Map containing only the entries that satisfy the predicate. #### Example ``` const map = new Map([ ['a', 1], ['b', 2], ['c', 3], ['d', 4] ]); const result = filter(map, (value) => value > 2); // result will be: // Map(2) { // 'c' => 3, // 'd' => 4 // } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### findKey ``` const findKey: typeof esToolkit_findKey = esToolkit_findKey; ``` Finds the first key in a Map for which the predicate function returns true. This function iterates through the entries of the Map and returns the key of the first entry for which the predicate function returns true. If no entry satisfies the predicate, it returns undefined. #### Template The type of keys in the Map. #### Template The type of values in the Map. #### Param The Map to search. #### Param A predicate function that tests each entry. #### Returns The key of the first entry that satisfies the predicate, or undefined if none found. #### Example ``` 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 will be: 'grape' ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### findValue ``` const findValue: typeof esToolkit_findValue = esToolkit_findValue; ``` Finds the first value in a Map for which the predicate function returns true. This function iterates through the entries of the Map and returns the value of the first entry for which the predicate function returns true. If no entry satisfies the predicate, it returns undefined. #### Template The type of keys in the Map. #### Template The type of values in the Map. #### Param The Map to search. #### Param A predicate function that tests each entry. #### Returns The value of the first entry that satisfies the predicate, or undefined if none found. #### Example ``` 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 will be: { color: 'purple', quantity: 15 } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### hasValue ``` const hasValue: typeof esToolkit_hasValue = esToolkit_hasValue; ``` Checks if a Map contains a specific value. This function iterates through all values in the Map and checks if any value is equal to the search element using SameValueZero comparison (similar to Array.prototype.includes). This means that NaN is considered equal to NaN. #### Template The type of keys in the Map. #### Template The type of values in the Map. #### Param The Map to search. #### Param The value to search for. #### Returns true if the Map contains the value, false otherwise. #### Example ``` const map = new Map([ ['a', 1], ['b', 2], ['c', 3] ]); const result = hasValue(map, 2); // result will be: true const result2 = hasValue(map, 5); // result2 will be: false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### mapKeys ``` const mapKeys: typeof esToolkit_mapKeys = esToolkit_mapKeys; ``` Creates a new Map with the same values but with keys transformed by the provided function. This function takes a Map and a function that generates a new key from each value-key pair. It returns a new Map where the keys are the result of applying the function to each entry, while the values remain the same. #### Template The type of keys in the Map. #### Template The type of values in the Map. #### Param The Map to transform. #### Param A function that generates a new key from a value-key pair. #### Returns A new Map with transformed keys and the same values. #### Example ``` const map = new Map([ ['a', 1], ['b', 2], ['c', 3] ]); const result = mapKeys(map, (value, key) => key.toUpperCase()); // result will be: // Map(3) { // 'A' => 1, // 'B' => 2, // 'C' => 3 // } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### mapValues ``` const mapValues: typeof esToolkit_mapValues = esToolkit_mapValues; ``` Creates a new Map with the same keys but with values transformed by the provided function. This function takes a Map and a function that generates a new value from each value-key pair. It returns a new Map where the values are the result of applying the function to each entry, while the keys remain the same. #### Template The type of keys in the Map. #### Template The type of values in the Map. #### Param The Map to transform. #### Param A function that generates a new value from a value-key pair. #### Returns A new Map with the same keys and transformed values. #### Example ``` const map = new Map([ ['a', 1], ['b', 2], ['c', 3] ]); const result = mapValues(map, (value) => value * 2); // result will be: // Map(3) { // 'a' => 2, // 'b' => 4, // 'c' => 6 // } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### reduce ``` const reduce: typeof esToolkit_reduce = esToolkit_reduce; ``` Reduces a Map to a single value by iterating through its entries and applying a callback function. This function iterates through all entries of the Map and applies the callback function to each entry, accumulating the result. 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. #### Template The type of keys in the Map. #### Template The type of values in the Map. #### Param The Map to reduce. #### Param A function that processes each entry and updates the accumulator. #### Param The initial value for the accumulator. If not provided, the first value in the Map is used. #### Returns The final accumulated value. #### Throws If the Map is empty and no initial value is provided. #### Examples ``` const map = new Map([ ['a', 1], ['b', 2], ['c', 3] ]); const result = reduce(map, (acc, value) => acc + value, 0); // result will be: 6 ``` ``` const map = new Map([ ['a', 10], ['b', 20] ]); const result = reduce(map, (acc, value) => acc + value); // result will be: 30 (starts with first value 10) ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### some ``` const some: typeof esToolkit_some = esToolkit_some; ``` Tests whether at least one entry in a Map satisfies the provided predicate function. This function iterates through the entries of the Map and checks if the predicate function returns true for at least one entry. It returns true if any entry satisfies the predicate, and false otherwise. #### Template The type of keys in the Map. #### Template The type of values in the Map. #### Param The Map to test. #### Param A predicate function that tests each entry. #### Returns true if at least one entry satisfies the predicate, false otherwise. #### Example ``` const map = new Map([ ['a', 1], ['b', 2], ['c', 3] ]); const result = some(map, (value) => value > 2); // result will be: true const result2 = some(map, (value) => value > 5); // result2 will be: false ``` #### See Powered by `es-toolkit` (MIT License): # math ## Variables ### clamp ``` const clamp: typeof esToolkit_clamp = esToolkit_clamp; ``` Clamps a number within the inclusive upper bound. This function takes a number and a maximum bound, and returns the number clamped within the specified upper bound. If only one bound is provided, it returns the minimum of the value and the bound. #### Param The number to clamp. #### Param The maximum bound to clamp the number. #### Returns The clamped number within the specified upper bound. #### Example ``` const result1 = clamp(10, 5); // result1 will be 5, as 10 is clamped to the bound 5 ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### inRange ``` const inRange: typeof esToolkit_inRange = esToolkit_inRange; ``` Checks if the value is less than the maximum. #### Param The value to check. #### Param The upper bound of the range (exclusive). #### Returns `true` if the value is less than the maximum, otherwise `false`. #### Example ``` const result = inRange(3, 5); // result will be true. const result2 = inRange(5, 5); // result2 will be false. ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### mean ``` const mean: typeof esToolkit_mean = esToolkit_mean; ``` Calculates the average of an array of numbers. If the array is empty, this function returns `NaN`. #### Param An array of numbers to calculate the average. #### Returns The average of all the numbers in the array. #### Example ``` const numbers = [1, 2, 3, 4, 5]; const result = mean(numbers); // result will be 3 ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### meanBy ``` const meanBy: typeof esToolkit_meanBy = esToolkit_meanBy; ``` Calculates the average of an array of numbers when applying the `getValue` function to each element. If the array is empty, this function returns `NaN`. #### Template The type of elements in the array. #### Param An array to calculate the average. #### Param A function that selects a numeric value from each element. #### Returns The average of all the numbers as determined by the `getValue` function. #### Example ``` meanBy([{ a: 1 }, { a: 2 }, { a: 3 }], x => x.a); // Returns: 2 meanBy([], x => x.a); // Returns: NaN ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### median ``` const median: typeof esToolkit_median = esToolkit_median; ``` Calculates the median of an array of numbers. The median is the middle value of a sorted array. If the array has an odd number of elements, the median is the middle value. If the array has an even number of elements, it returns the average of the two middle values. If the array is empty, this function returns `NaN`. #### Param An array of numbers to calculate the median. #### Returns The median of all the numbers in the array. #### Examples ``` const arrayWithOddNumberOfElements = [1, 2, 3, 4, 5]; const result = median(arrayWithOddNumberOfElements); // result will be 3 ``` ``` const arrayWithEvenNumberOfElements = [1, 2, 3, 4]; const result = median(arrayWithEvenNumberOfElements); // result will be 2.5 ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### medianBy ``` const medianBy: typeof esToolkit_medianBy = esToolkit_medianBy; ``` Calculates the median of an array of elements when applying the `getValue` function to each element. The median is the middle value of a sorted array. If the array has an odd number of elements, the median is the middle value. If the array has an even number of elements, it returns the average of the two middle values. If the array is empty, this function returns `NaN`. #### Template The type of elements in the array. #### Param An array to calculate the median. #### Param A function that selects a numeric value from each element. #### Returns The median of all the numbers as determined by the `getValue` function. #### Example ``` medianBy([{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }, { a: 5 }], x => x.a); // Returns: 3 medianBy([{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }], x => x.a); // Returns: 2.5 medianBy([], x => x.a); // Returns: NaN ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### range ``` const range: typeof esToolkit_range = esToolkit_range; ``` Returns an array of numbers from `0` (inclusive) to `end` (exclusive), incrementing by `1`. #### Param The end number of the range (exclusive). #### Returns An array of numbers from `0` (inclusive) to `end` (exclusive) with a step of `1`. #### Example ``` // Returns [0, 1, 2, 3] range(4); ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### rangeRight ``` const rangeRight: typeof esToolkit_rangeRight = esToolkit_rangeRight; ``` Returns an array of numbers from `end` (exclusive) to `0` (inclusive), decrementing by `1`. #### Param The end number of the range (exclusive). #### Returns An array of numbers from `end` (exclusive) to `0` (inclusive) with a step of `1`. #### Example ``` // Returns [3, 2, 1, 0] rangeRight(4); ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### round ``` const round: typeof esToolkit_round = esToolkit_round; ``` Rounds a number to a specified precision. This function takes a number and an optional precision value, and returns the number rounded to the specified number of decimal places. #### Param The number to round. #### Param The number of decimal places to round to. Defaults to 0. #### Returns The rounded number. #### Throws Throws an error if `Precision` is not integer. #### Example ``` const result1 = round(1.2345); // result1 will be 1 const result2 = round(1.2345, 2); // result2 will be 1.23 const result3 = round(1.2345, 3); // result3 will be 1.235 const result4 = round(1.2345, 3.1); // This will throw an error ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### sum ``` const sum: typeof esToolkit_sum = esToolkit_sum; ``` Calculates the sum of an array of numbers. This function takes an array of numbers and returns the sum of all the elements in the array. #### Param An array of numbers to be summed. #### Returns The sum of all the numbers in the array. #### Example ``` const numbers = [1, 2, 3, 4, 5]; const result = sum(numbers); // result will be 15 ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### sumBy ``` const sumBy: typeof esToolkit_sumBy = esToolkit_sumBy; ``` Calculates the sum of an array of numbers when applying the `getValue` function to each element. If the array is empty, this function returns `0`. #### Template The type of elements in the array. #### Param An array to calculate the sum. #### Param A function that selects a numeric value from each element. It receives the element and its zeroโ€‘based index in the array. #### Returns The sum of all the numbers as determined by the `getValue` function. #### Example ``` sumBy([{ a: 1 }, { a: 2 }, { a: 3 }], (x, i) => x.a * i); // Returns: 8 sumBy([], () => 1); // Returns: 0 ``` #### See Powered by `es-toolkit` (MIT License): # misc ## Variables ### assert ``` const assert: typeof esToolkit_assert = esToolkit_assert; ``` Asserts that a given condition is true. If the condition is false, an error is thrown with the provided message. #### Param The condition to evaluate. #### Param The error message to throw if the condition is false. #### Returns Returns void if the condition is true. #### Throws Throws an error if the condition is false. #### Example ``` // This call will succeed without any errors invariant(true, 'This should not throw'); // This call will fail and throw an error with the message 'This should throw' invariant(false, 'This should throw'); ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### attempt ``` const attempt: typeof esToolkit_attempt = esToolkit_attempt; ``` Attempt to execute a function and return the result or error. Returns a tuple where: - On success: [null, Result] - First element is null, second is the result - On error: [Error, null] - First element is the caught error, second is null #### Template The type of the result of the function. #### Template The type of the error that can be thrown by the function. #### Param The function to execute. #### Returns A tuple containing either [null, result] or [error, null]. #### Example ``` // Successful execution const [error, result] = attempt(() => 42); // [null, 42] // Failed execution const [error, result] = attempt(() => { throw new Error('Something went wrong'); }); // [Error, null] // With type parameter const [error, names] = attempt(() => ['Alice', 'Bob']); // [null, ['Alice', 'Bob']] ``` #### Note Important: This function is not suitable for async functions (functions that return a `Promise`). When passing an async function, it will return `[null, Promise]`, but won't catch any errors if the Promise is rejected later. For handling async functions, use the `attemptAsync` function instead: ``` const [error, data] = await attemptAsync(async () => { const response = await fetch('https://api.example.com/data'); return response.json(); }); ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### invariant ``` const invariant: typeof esToolkit_invariant = esToolkit_invariant; ``` Asserts that a given condition is true. If the condition is false, an error is thrown with the provided message. #### Param The condition to evaluate. #### Param The error message to throw if the condition is false. #### Returns Returns void if the condition is true. #### Throws Throws an error if the condition is false. #### Example ``` // This call will succeed without any errors invariant(true, 'This should not throw'); // This call will fail and throw an error with the message 'This should throw' invariant(false, 'This should throw'); ``` #### See Powered by `es-toolkit` (MIT License): # objects ## Variables ### clone ``` const clone: typeof esToolkit_clone = esToolkit_clone; ``` Creates a shallow clone of the given object. #### Template The type of the object. #### Param The object to clone. #### Returns - A shallow clone of the given object. #### Examples ``` // Clone a primitive values const num = 29; const clonedNum = clone(num); console.log(clonedNum); // 29 console.log(clonedNum === num); // true ``` ``` // Clone an array const arr = [1, 2, 3]; const clonedArr = clone(arr); console.log(clonedArr); // [1, 2, 3] console.log(clonedArr === arr); // false ``` ``` // Clone 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 ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### cloneDeep ``` const cloneDeep: typeof esToolkit_cloneDeep = esToolkit_cloneDeep; ``` Creates a deep clone of the given object. #### Template The type of the object. #### Param The object to clone. #### Returns - A deep clone of the given object. #### Examples ``` // Clone a primitive values const num = 29; const clonedNum = cloneDeep(num); console.log(clonedNum); // 29 console.log(clonedNum === num); // true ``` ``` // Clone an array const arr = [1, 2, 3]; const clonedArr = cloneDeep(arr); console.log(clonedArr); // [1, 2, 3] console.log(clonedArr === arr); // false ``` ``` // Clone an array with nested objects const arr = [1, { a: 1 }, [1, 2, 3]]; const clonedArr = cloneDeep(arr); arr[1].a = 2; console.log(arr); // [1, { a: 2 }, [1, 2, 3]] console.log(clonedArr); // [1, { a: 1 }, [1, 2, 3]] console.log(clonedArr === arr); // false ``` ``` // Clone an object const obj = { a: 1, b: 'es-toolkit', c: [1, 2, 3] }; const clonedObj = cloneDeep(obj); console.log(clonedObj); // { a: 1, b: 'es-toolkit', c: [1, 2, 3] } console.log(clonedObj === obj); // false ``` ``` // Clone an object with nested objects const obj = { a: 1, b: { c: 1 } }; const clonedObj = cloneDeep(obj); obj.b.c = 2; console.log(obj); // { a: 1, b: { c: 2 } } console.log(clonedObj); // { a: 1, b: { c: 1 } } console.log(clonedObj === obj); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### findKey ``` const findKey: typeof esToolkit_findKey = esToolkit_findKey; ``` Finds the key of the first element in the object that satisfies the provided testing function. #### Param The object to search. #### Param The function to execute on each value in the object. It takes three arguments: - value: The current value being processed in the object. - key: The key of the current value being processed in the object. - obj: The object that findKey was called upon. #### Returns The key of the first element in the object that passes the test, or undefined if no element passes. #### Example ``` const users = { 'barney': { 'age': 36, 'active': true }, 'fred': { 'age': 40, 'active': false }, 'pebbles': { 'age': 1, 'active': true } }; findKey(users, function(o) { return o.age < 40; }); => 'barney' ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### flattenObject ``` const flattenObject: typeof esToolkit_flattenObject = esToolkit_flattenObject; ``` The delimiter to use between nested keys. #### Default ``` '.' ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### invert ``` const invert: typeof esToolkit_invert = esToolkit_invert; ``` Inverts the keys and values of an object. The keys of the input object become the values of the output object and vice versa. This function takes an object and creates a new object by inverting its keys and values. If the input object has duplicate values, the key of the last occurrence will be used as the value for the new key in the output object. It effectively creates a reverse mapping of the input object's key-value pairs. #### Template Type of the keys in the input object (string, number, symbol) #### Template Type of the values in the input object (string, number, symbol) #### Param The input object whose keys and values are to be inverted #### Returns - A new object with keys and values inverted #### Example ``` invert({ a: 1, b: 2, c: 3 }); // { 1: 'a', 2: 'b', 3: 'c' } invert({ 1: 'a', 2: 'b', 3: 'c' }); // { a: '1', b: '2', c: '3' } invert({ a: 1, 2: 'b', c: 3, 4: 'd' }); // { 1: 'a', b: '2', 3: 'c', d: '4' } invert({ a: Symbol('sym1'), b: Symbol('sym2') }); // { [Symbol('sym1')]: 'a', [Symbol('sym2')]: 'b' } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### mapKeys ``` const mapKeys: typeof esToolkit_mapKeys = esToolkit_mapKeys; ``` Creates a new object with the same values as the given object, but with keys generated by running each own enumerable property of the object through the iteratee function. #### Template The type of the object. #### Template The type of the new keys generated by the iteratee function. #### Param The object to iterate over. #### Param The function invoked per own enumerable property. #### Returns - Returns the new mapped object. #### Example ``` // Example usage: const obj = { a: 1, b: 2 }; const result = mapKeys(obj, (value, key) => key + value); console.log(result); // { a1: 1, b2: 2 } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### mapValues ``` const mapValues: typeof esToolkit_mapValues = esToolkit_mapValues; ``` Creates a new object with the same keys as the given object, but with values generated by running each own enumerable property of the object through the iteratee function. #### Template The type of the object. #### Template The type of the keys in the object. #### Template The type of the new values generated by the iteratee function. #### Param The object to iterate over. #### Param The function invoked per own enumerable property. #### Returns - Returns the new mapped object. #### Example ``` // Example usage: const obj = { a: 1, b: 2 }; const result = mapValues(obj, (value) => value * 2); console.log(result); // { a: 2, b: 4 } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### merge ``` const merge: typeof esToolkit_merge = esToolkit_merge; ``` Merges the properties of the source object into the target object. This function performs a deep merge, meaning nested objects and arrays are merged recursively. If a property in the source object is an array or an object and the corresponding property in the target object is also an array or object, they will be merged. If a property in the source object is undefined, it will not overwrite a defined property in the target object. Note that this function mutates the target object. #### Param The target object into which the source object properties will be merged. This object is modified in place. #### Param The source object whose properties will be merged into the target object. #### Returns The updated target object with properties from the source object merged in. #### Template Type of the target object. #### Template Type of the source object. #### Examples ``` 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] } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### mergeWith ``` const mergeWith: typeof esToolkit_mergeWith = esToolkit_mergeWith; ``` Merges the properties of the source object into the target object. You can provide a custom `merge` function to control how properties are merged. It should return the value to be set in the target object. If it returns `undefined`, a default deep merge will be applied for arrays and objects: - If a property in the source object is an array or an object and the corresponding property in the target object is also an array or object, they will be merged. - If a property in the source object is undefined, it will not overwrite a defined property in the target object. Note that this function mutates the target object. #### Param The target object into which the source object properties will be merged. This object is modified in place. #### Param The source object whose properties will be merged into the target object. #### Param A custom merge function that defines how properties should be combined. It receives the following arguments: - `targetValue`: The current value of the property in the target object. - `sourceValue`: The value of the property in the source object. - `key`: The key of the property being merged. - `target`: The target object. - `source`: The source object. #### Returns The updated target object with properties from the source object merged in. #### Template Type of the target object. #### Template Type of the source object. #### Examples ``` 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; } }); // Returns { 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); } }); expect(result).toEqual({ a: [1, 3], b: [2, 4] }); ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### omit ``` const omit: typeof esToolkit_omit = esToolkit_omit; ``` Creates a new object with specified keys omitted. This function takes an object and an array of keys, and returns a new object that excludes the properties corresponding to the specified keys. #### Template The type of object. #### Template The type of keys in object. #### Param The object to omit keys from. #### Param An array of keys to be omitted from the object. #### Returns A new object with the specified keys omitted. #### Example ``` const obj = { a: 1, b: 2, c: 3 }; const result = omit(obj, ['b', 'c']); // result will be { a: 1 } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### omitBy ``` const omitBy: typeof esToolkit_omitBy = esToolkit_omitBy; ``` Creates a new object composed of the properties that do not satisfy the predicate function. This function takes an object and a predicate function, and returns a new object that includes only the properties for which the predicate function returns false. #### Template The type of object. #### Param The object to omit properties from. #### Param A predicate function that determines whether a property should be omitted. It takes the property's key and value as arguments and returns `true` if the property should be omitted, and `false` otherwise. #### Returns A new object with the properties that do not satisfy the predicate function. #### Example ``` const obj = { a: 1, b: 'omit', c: 3 }; const shouldOmit = (value) => typeof value === 'string'; const result = omitBy(obj, shouldOmit); // result will be { a: 1, c: 3 } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### pick ``` const pick: typeof esToolkit_pick = esToolkit_pick; ``` Creates a new object composed of the picked object properties. This function takes an object and an array of keys, and returns a new object that includes only the properties corresponding to the specified keys. #### Template The type of object. #### Template The type of keys in object. #### Param The object to pick keys from. #### Param An array of keys to be picked from the object. #### Returns A new object with the specified keys picked. #### Example ``` const obj = { a: 1, b: 2, c: 3 }; const result = pick(obj, ['a', 'c']); // result will be { a: 1, c: 3 } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### pickBy ``` const pickBy: typeof esToolkit_pickBy = esToolkit_pickBy; ``` Creates a new object composed of the properties that satisfy the predicate function. This function takes an object and a predicate function, and returns a new object that includes only the properties for which the predicate function returns true. #### Template The type of object. #### Param The object to pick properties from. #### Param A predicate function that determines whether a property should be picked. It takes the property's key and value as arguments and returns `true` if the property should be picked, and `false` otherwise. #### Returns A new object with the properties that satisfy the predicate function. #### Example ``` const obj = { a: 1, b: 'pick', c: 3 }; const shouldPick = (value) => typeof value === 'string'; const result = pickBy(obj, shouldPick); // result will be { b: 'pick' } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### toMerged ``` const toMerged: typeof esToolkit_toMerged = esToolkit_toMerged; ``` Merges the properties of the source object into a deep clone of the target object. Unlike `merge`, This function does not modify the original target object. This function performs a deep merge, meaning nested objects and arrays are merged recursively. - If a property in the source object is an array or object and the corresponding property in the target object is also an array or object, they will be merged. - If a property in the source object is undefined, it will not overwrite a defined property in the target object. Note that this function does not mutate the target object. #### Param The target object to be cloned and merged into. This object is not modified directly. #### Param The source object whose properties will be merged into the cloned target object. #### Returns A new object with properties from the source object merged into a deep clone of the target object. #### Template Type of the target object. #### Template Type of the source object. #### Examples ``` 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); // 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 = toMerged(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 = toMerged(target, source); console.log(result); // Output: { a: [1, 2, 3] } ``` #### See Powered by `es-toolkit` (MIT License): # options ## Functions ### getOptionArray() ``` function getOptionArray( options, key, defaultValue?, separator?): string[]; ``` Returns a string array option from a separator-delimited value. Empty items are removed and each entry is trimmed. Missing values return the provided default. #### Parameters ##### options Plugin options record. `Record`\<`string`, `string`> | `undefined` ##### key `string` Option name to read. ##### defaultValue? `string`[] = `[]` Value returned when the option is missing. ##### separator? `string` = `","` Delimiter used to split the raw string. #### Returns `string`[] A trimmed array of non-empty entries, an empty array for blank values, or the default when the key is missing. #### Example ``` // For options: { "features": "feature1, feature2, feature3" } getOptionArray(options, "features", [], ",") // returns ["feature1", "feature2", "feature3"] ``` ______________________________________________________________________ ### getOptionBool() ``` function getOptionBool( options, key, defaultValue): boolean; ``` Returns a boolean option using common truthy and falsy string values. Accepted truthy values: `true`, `1`, `yes`, `on`, `enable`, `enabled`, `y`. Accepted falsy values: `false`, `0`, `no`, `off`, `disable`, `disabled`, `n`. Invalid values fall back to the provided default. #### Parameters ##### options Plugin options record. `Record`\<`string`, `string`> | `undefined` ##### key `string` Option name to read. ##### defaultValue `boolean` Value returned when the option is missing or invalid. #### Returns `boolean` The parsed boolean value, or the default when parsing fails. #### Example ``` getOptionBool({ watch: "yes" }, "watch", false); // returns true ``` ______________________________________________________________________ ### getOptionEnum() ``` function getOptionEnum( options, key, allowedValues, defaultValue): T; ``` Returns a string option constrained to a known set of allowed values. Missing, blank, and unsupported values fall back to the provided default. #### Type Parameters ##### T `T` *extends* `string` #### Parameters ##### options Plugin options record. `Record`\<`string`, `string`> | `undefined` ##### key `string` Option name to read. ##### allowedValues readonly `T`[] Supported string values for the option. ##### defaultValue `T` Value returned when the option is missing or invalid. #### Returns `T` A valid enum-like string from `allowedValues`. #### Example ``` getOptionEnum({ format: "esm" }, "format", ["cjs", "esm"] as const, "cjs"); // returns "esm" ``` ______________________________________________________________________ ### getOptionNumber() ``` function getOptionNumber( options, key, defaultValue): number; ``` Returns a numeric option or the provided fallback when parsing fails. Empty, invalid, and non-finite values fall back to the default. #### Parameters ##### options Plugin options record. `Record`\<`string`, `string`> | `undefined` ##### key `string` Option name to read. ##### defaultValue `number` Value returned when the option is missing or invalid. #### Returns `number` The parsed finite number, or the default when parsing fails. #### Example ``` getOptionNumber({ retries: "3" }, "retries", 0); // returns 3 ``` ______________________________________________________________________ ### getOptionString() ``` function getOptionString( options, key, defaultValue): string; ``` Returns a string option or the provided fallback when the key is missing. Unlike the numeric and enum helpers, this function preserves the raw option value exactly as provided, including empty strings. #### Parameters ##### options Plugin options record. `Record`\<`string`, `string`> | `undefined` ##### key `string` Option name to read. ##### defaultValue `string` Value returned when the option is missing. #### Returns `string` The raw option string, or the default when the key is missing. #### Example ``` getOptionString({ prefix: "Api" }, "prefix", "Model"); // returns "Api" ``` # paths ## Functions ### basename() ``` function basename(path, extension?): string; ``` Returns the last path segment, optionally removing a known extension suffix. #### Parameters ##### path `string` Path to inspect. ##### extension? `string` Optional extension suffix to remove from the result. #### Returns `string` The basename of `path`. #### Example ``` basename("generated/models/user.ts"); // returns "user.ts" ``` #### See Powered by `pathe` (MIT License): ______________________________________________________________________ ### dirname() ``` function dirname(path): string; ``` Returns the parent directory portion of a path. #### Parameters ##### path `string` Path to inspect. #### Returns `string` The directory name portion of `path`. #### Example ``` dirname("generated/models/user.ts"); // returns "generated/models" ``` #### See Powered by `pathe` (MIT License): ______________________________________________________________________ ### extname() ``` function extname(path): string; ``` Returns the file extension of a path, including the leading dot. #### Parameters ##### path `string` Path to inspect. #### Returns `string` The extension portion of `path`, or an empty string when none exists. #### Example ``` extname("generated/models/user.ts"); // returns ".ts" ``` #### See Powered by `pathe` (MIT License): ______________________________________________________________________ ### filename() ``` function filename(path): string | undefined; ``` Returns the filename without its extension. This is useful for deriving stable artifact names without manually stripping directory segments or extensions. #### Parameters ##### path `string` Path to inspect. #### Returns `string` | `undefined` The filename without its extension, or `undefined` when it cannot be derived. #### Example ``` filename("generated/models/user.ts"); // returns "user" ``` #### See Powered by `pathe` (MIT License): ______________________________________________________________________ ### isAbsolute() ``` function isAbsolute(path): boolean; ``` Checks whether a path is absolute. #### Parameters ##### path `string` Path to inspect. #### Returns `boolean` `true` when `path` is absolute, otherwise `false`. #### Example ``` isAbsolute("/generated/models/user.ts"); // returns true ``` #### See Powered by `pathe` (MIT License): ______________________________________________________________________ ### join() ``` function join(...parts): string; ``` Joins path segments using deterministic forward-slash normalization. This is a thin wrapper around `pathe.join`, which keeps behavior consistent across platforms and normalizes path separators to `/`. #### Parameters ##### parts ...`string`[] Path segments to join. #### Returns `string` The normalized joined path. #### Example ``` join("generated", "models", "user.ts"); // returns "generated/models/user.ts"z ``` #### See Powered by `pathe` (MIT License): ______________________________________________________________________ ### normalize() ``` function normalize(path): string; ``` Normalizes a path by collapsing redundant separators and dot segments. This is helpful when plugin code receives mixed Windows and POSIX-style path input and needs a single predictable format. #### Parameters ##### path `string` Path to normalize. #### Returns `string` The normalized path using `/` separators. #### Example ``` normalize("generated\\models/../types/user.ts"); // returns "generated/types/user.ts" ``` #### See Powered by `pathe` (MIT License): ______________________________________________________________________ ### relative() ``` function relative(from, to): string; ``` Computes the relative path from one location to another. #### Parameters ##### from `string` Starting path. ##### to `string` Destination path. #### Returns `string` The normalized relative path from `from` to `to`. #### Example ``` relative("generated/models", "generated/types/user.ts"); // returns "../types/user.ts" ``` #### See Powered by `pathe` (MIT License): ______________________________________________________________________ ### resolve() ``` function resolve(...parts): string; ``` Resolves one or more path segments into a normalized absolute or rooted path. This is useful when plugin code needs stable path resolution without relying on platform-specific separators. #### Parameters ##### parts ...`string`[] Path segments to resolve. #### Returns `string` The resolved normalized path. #### Example ``` resolve("/workspace/plugin", "src", "../dist/index.js"); // returns "/workspace/plugin/dist/index.js" ``` #### See Powered by `pathe` (MIT License): # predicates ## Variables ### isBoolean ``` const isBoolean: typeof esToolkit_isBoolean = esToolkit_isBoolean; ``` Checks if the given value is boolean. This function tests whether the provided value is strictly `boolean`. It returns `true` if the value is `boolean`, and `false` otherwise. This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `boolean`. #### Param The Value to test if it is boolean. #### Returns True if the value is boolean, false otherwise. #### Example ``` const value1 = true; const value2 = 0; const value3 = 'abc'; console.log(isBoolean(value1)); // true console.log(isBoolean(value2)); // false console.log(isBoolean(value3)); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isDate ``` const isDate: typeof esToolkit_isDate = esToolkit_isDate; ``` Checks if `value` is a Date object. #### Param The value to check. #### Returns Returns `true` if `value` is a Date object, `false` otherwise. #### Example ``` const value1 = new Date(); const value2 = '2024-01-01'; console.log(isDate(value1)); // true console.log(isDate(value2)); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isEmptyObject ``` const isEmptyObject: typeof esToolkit_isEmptyObject = esToolkit_isEmptyObject; ``` Checks if a value is an empty plain object. #### Param The value to check. #### Returns - True if the value is an empty plain object, otherwise false. #### Example ``` isEmptyObject({}); // true isEmptyObject({ a: 1 }); // false isEmptyObject([]); // false isEmptyObject(null); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isEqual ``` const isEqual: typeof esToolkit_isEqual = esToolkit_isEqual; ``` Checks if two values are equal, including support for `Date`, `RegExp`, and deep object comparison. #### Param The first value to compare. #### Param The second value to compare. #### Returns `true` if the values are equal, otherwise `false`. #### Example ``` isEqual(1, 1); // true isEqual({ a: 1 }, { a: 1 }); // true isEqual(/abc/g, /abc/g); // true isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true isEqual([1, 2, 3], [1, 2, 3]); // true ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isError ``` const isError: typeof esToolkit_isError = esToolkit_isError; ``` Checks if `value` is an Error object. #### Param The value to check. #### Returns Returns `true` if `value` is an Error object, `false` otherwise. #### Example ``` console.log(isError(new Error())); // true console.log(isError('Error')); // false console.log(isError({ name: 'Error', message: '' })); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isFunction ``` const isFunction: typeof esToolkit_isFunction = esToolkit_isFunction; ``` Checks if `value` is a function. #### Param The value to check. #### Returns Returns `true` if `value` is a function, else `false`. #### Example ``` isFunction(Array.prototype.slice); // true isFunction(async function () {}); // true isFunction(function* () {}); // true isFunction(Proxy); // true isFunction(Int8Array); // true ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isJSON ``` const isJSON: typeof esToolkit_isJSON = esToolkit_isJSON; ``` Checks if a given value is a valid JSON string. A valid JSON string is one that can be successfully parsed using `JSON.parse()`. According to JSON specifications, valid JSON can represent: - Objects (with string keys and valid JSON values) - Arrays (containing valid JSON values) - Strings - Numbers - Booleans - null String values like `"null"`, `"true"`, `"false"`, and numeric strings (e.g., `"42"`) are considered valid JSON and will return true. This function serves as a type guard in TypeScript, narrowing the type of the argument to `string`. #### Param The value to check. #### Returns Returns `true` if `value` is a valid JSON string, else `false`. #### Example ``` isJSON('{"name":"John","age":30}'); // true isJSON('[1,2,3]'); // true isJSON('true'); // true isJSON('invalid json'); // false isJSON({ name: 'John' }); // false (not a string) isJSON(null); // false (not a string) ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isJSONArray ``` const isJSONArray: typeof esToolkit_isJSONArray = esToolkit_isJSONArray; ``` Checks if a given value is a valid JSON value. A valid JSON value can be: - null - a JSON object (an object with string keys and valid JSON values) - a JSON array (an array of valid JSON values) - a string - a number - a boolean #### Param The value to check. #### Returns - True if the value is a valid JSON value, otherwise false. #### Example ``` console.log(isJSONValue(null)); // true console.log(isJSONValue({ key: "value" })); // true console.log(isJSONValue([1, 2, 3])); // true console.log(isJSONValue("Hello")); // true console.log(isJSONValue(42)); // true console.log(isJSONValue(true)); // true console.log(isJSONValue(undefined)); // false console.log(isJSONValue(() => {})); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isJSONObject ``` const isJSONObject: typeof esToolkit_isJSONObject = esToolkit_isJSONObject; ``` Checks if a given value is a valid JSON value. A valid JSON value can be: - null - a JSON object (an object with string keys and valid JSON values) - a JSON array (an array of valid JSON values) - a string - a number - a boolean #### Param The value to check. #### Returns - True if the value is a valid JSON value, otherwise false. #### Example ``` console.log(isJSONValue(null)); // true console.log(isJSONValue({ key: "value" })); // true console.log(isJSONValue([1, 2, 3])); // true console.log(isJSONValue("Hello")); // true console.log(isJSONValue(42)); // true console.log(isJSONValue(true)); // true console.log(isJSONValue(undefined)); // false console.log(isJSONValue(() => {})); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isJSONValue ``` const isJSONValue: typeof esToolkit_isJSONValue = esToolkit_isJSONValue; ``` Checks if a given value is a valid JSON value. A valid JSON value can be: - null - a JSON object (an object with string keys and valid JSON values) - a JSON array (an array of valid JSON values) - a string - a number - a boolean #### Param The value to check. #### Returns - True if the value is a valid JSON value, otherwise false. #### Example ``` console.log(isJSONValue(null)); // true console.log(isJSONValue({ key: "value" })); // true console.log(isJSONValue([1, 2, 3])); // true console.log(isJSONValue("Hello")); // true console.log(isJSONValue(42)); // true console.log(isJSONValue(true)); // true console.log(isJSONValue(undefined)); // false console.log(isJSONValue(() => {})); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isMap ``` const isMap: typeof esToolkit_isMap = esToolkit_isMap; ``` Checks if a given value is `Map`. This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Map`. #### Param The value to check if it is a `Map`. #### Returns Returns `true` if `value` is a `Map`, else `false`. #### Example ``` const value1 = new Map(); const value2 = new Set(); const value3 = new WeakMap(); console.log(isMap(value1)); // true console.log(isMap(value2)); // false console.log(isMap(value3)); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isNil ``` const isNil: typeof esToolkit_isNil = esToolkit_isNil; ``` Checks if a given value is null or undefined. This function tests whether the provided value is either `null` or `undefined`. It returns `true` if the value is `null` or `undefined`, and `false` otherwise. This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `null` or `undefined`. #### Param The value to test for null or undefined. #### Returns `true` if the value is null or undefined, `false` otherwise. #### Example ``` const value1 = null; const value2 = undefined; const value3 = 42; const result1 = isNil(value1); // true const result2 = isNil(value2); // true const result3 = isNil(value3); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isNotNil ``` const isNotNil: typeof esToolkit_isNotNil = esToolkit_isNotNil; ``` Checks if the given value is not null nor undefined. The main use of this function is to be used with TypeScript as a type predicate. #### Template The type of value. #### Param The value to test if it is not null nor undefined. #### Returns True if the value is not null nor undefined, false otherwise. #### Example ``` // Here the type of `arr` is (number | undefined)[] const arr = [1, undefined, 3]; // Here the type of `result` is number[] const result = arr.filter(isNotNil); // result will be [1, 3] ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isNull ``` const isNull: typeof esToolkit_isNull = esToolkit_isNull; ``` Checks if the given value is null. This function tests whether the provided value is strictly equal to `null`. It returns `true` if the value is `null`, and `false` otherwise. This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `null`. #### Param The value to test if it is null. #### Returns True if the value is null, false otherwise. #### Example ``` const value1 = null; const value2 = undefined; const value3 = 42; console.log(isNull(value1)); // true console.log(isNull(value2)); // false console.log(isNull(value3)); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isNumber ``` const isNumber: typeof esToolkit_isNumber = esToolkit_isNumber; ``` Checks if the given value is a number. This function tests whether the provided value is strictly a `number`. It returns `true` if the value is a `number`, and `false` otherwise. This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `number`. #### Param The value to test if it is a number. #### Returns True if the value is a number, false otherwise. #### Example ``` const value1 = 123; const value2 = 'abc'; const value3 = true; console.log(isNumber(value1)); // true console.log(isNumber(value2)); // false console.log(isNumber(value3)); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isPlainObject ``` const isPlainObject: typeof esToolkit_isPlainObject = esToolkit_isPlainObject; ``` Checks if a given value is a plain object. #### Param The value to check. #### Returns - True if the value is a plain object, otherwise false. #### Example ``` // โœ…๐Ÿ‘‡ True isPlainObject({ }); // โœ… isPlainObject({ key: 'value' }); // โœ… isPlainObject({ key: new Date() }); // โœ… isPlainObject(new Object()); // โœ… isPlainObject(Object.create(null)); // โœ… isPlainObject({ nested: { key: true} }); // โœ… isPlainObject(new Proxy({}, {})); // โœ… isPlainObject({ [Symbol('tag')]: 'A' }); // โœ… // โœ…๐Ÿ‘‡ (cross-realms, node context, workers, ...) const runInNewContext = await import('node:vm').then( (mod) => mod.runInNewContext ); isPlainObject(runInNewContext('({})')); // โœ… // โŒ๐Ÿ‘‡ False class Test { }; isPlainObject(new Test()) // โŒ isPlainObject(10); // โŒ isPlainObject(null); // โŒ isPlainObject('hello'); // โŒ isPlainObject([]); // โŒ isPlainObject(new Date()); // โŒ isPlainObject(new Uint8Array([1])); // โŒ isPlainObject(Buffer.from('ABC')); // โŒ isPlainObject(Promise.resolve({})); // โŒ isPlainObject(Object.create({})); // โŒ isPlainObject(new (class Cls {})); // โŒ isPlainObject(globalThis); // โŒ, ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isPrimitive ``` const isPrimitive: typeof esToolkit_isPrimitive = esToolkit_isPrimitive; ``` Checks whether a value is a JavaScript primitive. JavaScript primitives include null, undefined, strings, numbers, booleans, symbols, and bigints. #### Param The value to check. #### Returns Returns true if `value` is a primitive, false otherwise. #### Example ``` isPrimitive(null); // true isPrimitive(undefined); // true isPrimitive('123'); // true isPrimitive(false); // true isPrimitive(true); // true isPrimitive(Symbol('a')); // true isPrimitive(123n); // true isPrimitive({}); // false isPrimitive(new Date()); // false isPrimitive(new Map()); // false isPrimitive(new Set()); // false isPrimitive([1, 2, 3]); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isRegExp ``` const isRegExp: typeof esToolkit_isRegExp = esToolkit_isRegExp; ``` Checks if `value` is a RegExp. #### Param The value to check. #### Returns Returns `true` if `value` is a RegExp, `false` otherwise. #### Example ``` const value1 = /abc/; const value2 = '/abc/'; console.log(isRegExp(value1)); // true console.log(isRegExp(value2)); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isSet ``` const isSet: typeof esToolkit_isSet = esToolkit_isSet; ``` Checks if a given value is `Set`. This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Set`. #### Param The value to check if it is a `Set`. #### Returns Returns `true` if `value` is a `Set`, else `false`. #### Example ``` const value1 = new Set(); const value2 = new Map(); const value3 = new WeakSet(); console.log(isSet(value1)); // true console.log(isSet(value2)); // false console.log(isSet(value3)); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isString ``` const isString: typeof esToolkit_isString = esToolkit_isString; ``` Checks if a given value is string. This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `string`. #### Param The value to check if it is string. #### Returns Returns `true` if `value` is a string, else `false`. #### Example ``` const value1 = 'abc'; const value2 = 123; const value3 = true; console.log(isString(value1)); // true console.log(isString(value2)); // false console.log(isString(value3)); // false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### isUndefined ``` const isUndefined: typeof esToolkit_isUndefined = esToolkit_isUndefined; ``` Checks if the given value is undefined. This function tests whether the provided value is strictly equal to `undefined`. It returns `true` if the value is `undefined`, and `false` otherwise. This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `undefined`. #### Param The value to test if it is undefined. #### Returns true if the value is undefined, false otherwise. #### Example ``` const value1 = undefined; const value2 = null; const value3 = 42; console.log(isUndefined(value1)); // true console.log(isUndefined(value2)); // false console.log(isUndefined(value3)); // false ``` #### See Powered by `es-toolkit` (MIT License): # sets ## Variables ### countBy ``` const countBy: typeof esToolkit_countBy = esToolkit_countBy; ``` Counts the occurrences of items in a Set based on a transformation function. This function takes a Set and a function that generates a key from each value. 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. #### Template The type of elements in the Set. #### Template The type of keys produced by the transformation function. #### Param The Set to count occurrences from. #### Param The function to produce a key for counting. #### Returns A Map containing the mapped keys and their counts. #### Examples ``` const set = new Set([1, 2, 3, 4, 5]); const result = countBy(set, (value) => value % 2 === 0 ? 'even' : 'odd'); // result will be Map(2) { 'odd' => 3, 'even' => 2 } ``` ``` const set = new Set(['apple', 'banana', 'cherry']); const result = countBy(set, (value) => value.length); // result will be Map(2) { 5 => 1, 6 => 2 } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### every ``` const every: typeof esToolkit_every = esToolkit_every; ``` Tests whether all elements in a Set satisfy the provided predicate function. This function iterates through all elements of the Set and checks if the predicate function returns true for every element. It returns true if the predicate is satisfied for all elements, and false otherwise. #### Template The type of elements in the Set. #### Param The Set to test. #### Param A predicate function that tests each element. #### Returns true if all elements satisfy the predicate, false otherwise. #### Example ``` const set = new Set([10, 20, 30]); const result = every(set, (value) => value > 5); // result will be: true const result2 = every(set, (value) => value > 15); // result2 will be: false ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### filter ``` const filter: typeof esToolkit_filter = esToolkit_filter; ``` Filters a Set based on a predicate function. This function takes a Set and a predicate function, and returns a new Set containing only the elements for which the predicate function returns true. #### Template The type of elements in the Set. #### Param The Set to filter. #### Param A predicate function that tests each element. #### Returns A new Set containing only the elements that satisfy the predicate. #### Example ``` const set = new Set([1, 2, 3, 4, 5]); const result = filter(set, (value) => value > 2); // result will be: // Set(3) { 3, 4, 5 } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### find ``` const find: typeof esToolkit_find = esToolkit_find; ``` Finds the first element in a Set for which the predicate function returns true. This function iterates through the elements of the Set and returns the first element for which the predicate function returns true. If no element satisfies the predicate, it returns undefined. #### Template The type of elements in the Set. #### Param The Set to search. #### Param A predicate function that tests each element. #### Returns The first element that satisfies the predicate, or undefined if none found. #### Example ``` 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 will be: { name: 'grape', quantity: 15 } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### keyBy ``` const keyBy: typeof esToolkit_keyBy = esToolkit_keyBy; ``` Maps each element of a Set based on a provided key-generating function. This function takes a Set and a function that generates a key from each value. 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. #### Template The type of elements in the Set. #### Template The type of keys to produce in the returned Map. #### Param The set of elements to be mapped. #### Param A function that generates a key from a value. #### Returns A Map where the generated keys are mapped to each element's value. #### Example ``` const set = new Set([ { type: 'fruit', name: 'apple' }, { type: 'fruit', name: 'banana' }, { type: 'vegetable', name: 'carrot' } ]); const result = keyBy(set, item => item.type); // result will be: // Map(2) { // 'fruit' => { type: 'fruit', name: 'banana' }, // 'vegetable' => { type: 'vegetable', name: 'carrot' } // } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### map ``` const map: typeof esToolkit_map = esToolkit_map; ``` Creates a new Set with elements transformed by the provided function. This function takes a Set and a function that generates a new value from each element. It returns a new Set where the elements are the result of applying the function to each element. #### Template The type of elements in the input Set. #### Template The type of elements in the output Set. #### Param The Set to transform. #### Param A function that generates a new value from an element. #### Returns A new Set with transformed elements. #### Example ``` const set = new Set([1, 2, 3]); const result = map(set, (value) => value * 2); // result will be: // Set(3) { 2, 4, 6 } ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### reduce ``` const reduce: typeof esToolkit_reduce = esToolkit_reduce; ``` Reduces a Set to a single value by iterating through its elements and applying a callback function. This function iterates through all elements of the Set and applies the callback function to each element, accumulating the result. 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. #### Template The type of elements in the Set. #### Template The type of the accumulator. #### Param The Set to reduce. #### Param A function that processes each element and updates the accumulator. #### Param The initial value for the accumulator. If not provided, the first element in the Set is used. #### Returns The final accumulated value. #### Throws If the Set is empty and no initial value is provided. #### Examples ``` const set = new Set([1, 2, 3]); const result = reduce(set, (acc, value) => acc + value, 0); // result will be: 6 ``` ``` const set = new Set([10, 20]); const result = reduce(set, (acc, value) => acc + value); // result will be: 30 (starts with first value 10) ``` #### See Powered by `es-toolkit` (MIT License): ______________________________________________________________________ ### some ``` const some: typeof esToolkit_some = esToolkit_some; ``` Tests whether at least one element in a Set satisfies the provided predicate function. This function iterates through the elements of the Set and checks if the predicate function returns true for at least one element. It returns true if any element satisfies the predicate, and false otherwise. #### Template The type of elements in the Set. #### Param The Set to test. #### Param A predicate function that tests each element. #### Returns true if at least one element satisfies the predicate, false otherwise. #### Example ``` const set = new Set([1, 2, 3]); const result = some(set, (value) => value > 2); // result will be: true const result2 = some(set, (value) => value > 5); // result2 will be: false ``` #### See Powered by `es-toolkit` (MIT License): # strings ## Functions ### camelCase() ``` function camelCase(str): string; ``` Converts a string to `camelCase`. Tokenization is delegated to `words`, so mixed input styles such as `snake_case`, `kebab-case`, `PascalCase`, `camelCase`, and separator-heavy strings are normalized first and then reassembled. The first token is lowercased. Every following token is capitalized with the remainder lowercased. Empty or separator-only inputs return an empty string. #### Parameters ##### str `string` String to normalize. #### Returns `string` The `camelCase` representation of `str`. #### Example ``` camelCase("user_profile-name") // "userProfileName" ``` ______________________________________________________________________ ### dedent() ``` function dedent(input): string; ``` Removes shared indentation from a multi-line string. This helper is useful for generating readable code templates, markdown, or text fixtures inside plugins without carrying indentation from the source file into the final output. #### Parameters ##### input `string` Multi-line string to dedent. #### Returns `string` The same text with common indentation removed. #### Example ``` dedent(` export interface User { id: string; } `); // returns "export interface User {\n id: string;\n}" ``` #### See Powered by `dedent` (MIT License): ______________________________________________________________________ ### kebabCase() ``` function kebabCase(str, upperCase?): string; ``` Converts a string to `kebab-case`. The function tokenizes the input with `words`, lowercases every token, and joins the result with hyphens. This allows mixed casing conventions and noisy separators to converge into a consistent kebab-cased string. When `upperCase` is `true`, the same tokenization and joining rules are used, but the final tokens are uppercased instead. This is useful for constants, identifiers, or file names that still need kebab separators. Empty or separator-only inputs return an empty string. #### Parameters ##### str `string` String to normalize. ##### upperCase? `boolean` = `false` When `true`, uppercases each token before joining. #### Returns `string` The `kebab-case` representation of `str`. #### Examples ``` kebabCase("UserProfileName") // "user-profile-name" ``` ``` kebabCase("UserProfileName", true) // "USER-PROFILE-NAME" ``` ______________________________________________________________________ ### lowerCase() ``` function lowerCase(str): string; ``` Converts a string to lowercase words separated by spaces. The input is normalized with `words`, then each token is lowercased and joined using a single space. This is useful when a readable, sentence-like representation is preferred over identifier-style separators. Empty or separator-only inputs return an empty string. #### Parameters ##### str `string` String to normalize. #### Returns `string` The lowercased space-separated representation of `str`. #### Example ``` lowerCase("userProfileName") // "user profile name" ``` ______________________________________________________________________ ### pad() ``` function pad( str, length, chars?): string; ``` Pads both sides of a string until it reaches the requested length. Padding is only added when the string is shorter than `length`. The padding pattern repeats as needed and is truncated to fit exactly. When the total number of padding characters cannot be split evenly, the right side receives one more character than the left side. By default, spaces are used as padding. Pass `chars` to use a custom padding pattern. If `chars` is an empty string, the input is returned unchanged. The target length is truncated with `Math.trunc`, so decimal lengths behave predictably. Non-finite lengths are ignored and return the original string. #### Parameters ##### str `string` String to pad. ##### length `number` Final string length to target. ##### chars? `string` Optional padding characters to repeat. #### Returns `string` `str` centered within the requested width. #### Examples ``` pad("cat", 7) // " cat " ``` ``` pad("cat", 8, "_-") // "_-cat_-_" ``` ______________________________________________________________________ ### padLeft() ``` function padLeft( str, length, chars?): string; ``` Pads the left side of a string until it reaches the requested length. Padding is added only when the string is shorter than `length`. The padding pattern repeats as needed and is truncated to fit exactly. By default, spaces are used as padding. Pass `chars` to use a custom padding pattern. If `chars` is an empty string, the input is returned unchanged. The target length is truncated with `Math.trunc`, and non-finite lengths are ignored by returning the original string. #### Parameters ##### str `string` String to pad. ##### length `number` Final string length to target. ##### chars? `string` Optional padding characters to repeat. #### Returns `string` `str` padded on the left up to `length` characters. #### Example ``` padLeft("cat", 5, "0") // "00cat" ``` ______________________________________________________________________ ### padRight() ``` function padRight( str, length, chars?): string; ``` Pads the right side of a string until it reaches the requested length. Padding is added only when the string is shorter than `length`. The padding pattern repeats as needed and is truncated to fit exactly. By default, spaces are used as padding. Pass `chars` to use a custom padding pattern. If `chars` is an empty string, the input is returned unchanged. The target length is truncated with `Math.trunc`, and non-finite lengths are ignored by returning the original string. #### Parameters ##### str `string` String to pad. ##### length `number` Final string length to target. ##### chars? `string` Optional padding characters to repeat. #### Returns `string` `str` padded on the right up to `length` characters. #### Example ``` padRight("cat", 5, "0") // "cat00" ``` ______________________________________________________________________ ### pascalCase() ``` function pascalCase(str): string; ``` Converts a string to `PascalCase`. The input is first tokenized with `words`, allowing the function to accept a wide range of source formats such as `snake_case`, `kebab-case`, spaced strings, `camelCase`, or acronym-heavy identifiers. Every token is normalized to an initial uppercase letter followed by a lowercased remainder. Empty or separator-only inputs return an empty string. #### Parameters ##### str `string` String to normalize. #### Returns `string` The `PascalCase` representation of `str`. #### Example ``` pascalCase("user_profile-name") // "UserProfileName" ``` ______________________________________________________________________ ### snakeCase() ``` function snakeCase(str, upperCase?): string; ``` Converts a string to `snake_case`. The input is tokenized with `words`, each token is lowercased, and the final string is joined with underscores. This keeps the behavior aligned with the shared SDK word-splitting rules. When `upperCase` is `true`, the same tokenization and joining behavior is preserved but the final tokens are uppercased instead. This is useful for environment variable names and constant-like identifiers. Empty or separator-only inputs return an empty string. #### Parameters ##### str `string` String to normalize. ##### upperCase? `boolean` = `false` When `true`, uppercases each token before joining. #### Returns `string` The `snake_case` representation of `str`. #### Examples ``` snakeCase("UserProfileName") // "user_profile_name" ``` ``` snakeCase("UserProfileName", true) // "USER_PROFILE_NAME" ``` ______________________________________________________________________ ### trim() ``` function trim(str, chars?): string; ``` Removes matching characters from both ends of a string. By default, the function trims leading and trailing whitespace using the platform's built-in whitespace semantics. When `chars` is provided, only those characters are trimmed from the start and end of the string. A string value is interpreted as a set of individual characters, and an array combines all characters from all entries. For example, `trim("__value--", "_-")` and `trim("__value--", ["_", "-"])` both return `"value"`. Characters are removed only at the outer edges; matching characters inside the string are preserved. #### Parameters ##### str `string` String to trim. ##### chars? Optional characters to remove instead of whitespace. `string` | readonly `string`[] #### Returns `string` A copy of `str` without the matching leading and trailing characters. #### Examples ``` trim(" hello ") // "hello" ``` ``` trim("__hello--", ["_", "-"]) // "hello" ``` ______________________________________________________________________ ### trimEnd() ``` function trimEnd(str, chars?): string; ``` Removes matching characters from the end of a string. By default, the function trims trailing whitespace using the platform's built-in whitespace semantics. When `chars` is provided, only those characters are removed from the end. A string value is interpreted as a set of individual characters, and an array combines all characters from all entries. Matching characters that appear earlier in the string are preserved. #### Parameters ##### str `string` String to trim. ##### chars? Optional characters to remove instead of whitespace. `string` | readonly `string`[] #### Returns `string` A copy of `str` without the matching trailing characters. #### Examples ``` trimEnd(" hello ") // " hello" ``` ``` trimEnd("__hello__", "_") // "__hello" ``` ______________________________________________________________________ ### trimStart() ``` function trimStart(str, chars?): string; ``` Removes matching characters from the start of a string. By default, the function trims leading whitespace using the platform's built-in whitespace semantics. When `chars` is provided, only those characters are removed from the start. A string value is interpreted as a set of individual characters, and an array combines all characters from all entries. Matching characters that appear later in the string are preserved. #### Parameters ##### str `string` String to trim. ##### chars? Optional characters to remove instead of whitespace. `string` | readonly `string`[] #### Returns `string` A copy of `str` without the matching leading characters. #### Examples ``` trimStart(" hello ") // "hello " ``` ``` trimStart("__hello__", "_") // "hello__" ``` ______________________________________________________________________ ### upperCase() ``` function upperCase(str): string; ``` Converts a string to uppercase words separated by spaces. The input is normalized with `words`, then each token is uppercased and joined using a single space. This is useful for readable labels, headings, or enum-like display values derived from mixed naming conventions. Empty or separator-only inputs return an empty string. #### Parameters ##### str `string` String to normalize. #### Returns `string` The uppercased space-separated representation of `str`. #### Example ``` upperCase("userProfileName") // "USER PROFILE NAME" ``` ______________________________________________________________________ ### words() ``` function words(str): string[]; ``` Splits a string into normalized word tokens. The function preserves the current tokenization rules used by the SDK: it inserts spaces at camelCase and acronym-to-word boundaries, converts any non-alphanumeric separator to a space, trims the result, and then splits on whitespace. This makes it suitable for inputs such as `camelCase`, `PascalCase`, `HTTPServer`, `snake_case`, `kebab-case`, and mixed separator variants. Empty or separator-only inputs return an empty array. #### Parameters ##### str `string` String to tokenize. #### Returns `string`[] An array of normalized word tokens. #### Example ``` words("HTTPServer_error-code"); // returns ["HTTP", "Server", "error", "code"] ```