--- url: /en/async/asyncForEach.md --- # asyncForEach \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input an array `array` and an iterator `iterator`, iterate over each element of the array, and execute `iterator` for each element. The `iterator` supports `async` functions or functions that return a `Promise`. The optional parameter `concurrent` controls whether the `iterator` functions are called concurrently. If the value is `'sequential'`, the next `iterator` will only be executed after the `Promise` returned by the previous `iterator` is either fulfilled or rejected. > Added in v0.0.1 ### Usage ```ts import { asyncForEach } from 'parsnip-kit' const array = [1, 2, 3] const logConcurrent = [] as any[] const iterator = (item, index, arr) => { return new Promise((resolve) => { setTimeout(() => { logConcurrent.push({ item, index }) resolve(void 0) }, Math.random() * 100) }) } asyncForEach(array, iterator).then(() => { console.log(logConcurrent) // Array contain { item: 1, index: 0 }, { item: 2, index: 1 }, { item: 3, index: 2 } with random order. }) const logSequential = [] as any[] const iterator = (item, index, arr) => { return new Promise((resolve) => { setTimeout(() => { logSequential.push({ item, index }) resolve(void 0) }, Math.random() * 100) }) } asyncForEach(array, iterator, 'sequential').then(() => { console.log(logSequential) // [{ item: 1, index: 0 }, { item: 2, index: 1 }, { item: 3, index: 2 }] }) ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Element type of array | | `R` | `extends 'concurrent' \| 'sequential' = 'concurrent' \| 'sequential'` | Concurrent type | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `array` | `T[]` | `false` | `undefined` | Array to iterate | | `iterator` | `(item: T, index: number, array: T[]) => any` | `false` | `undefined` | Iterator function | | `concurrent` | `R` | `true` | `'concurrent'` | Concurrent type | #### Returns | Type | | --- | | `Promise` | --- --- url: /en/async/asyncForEachFields.md --- # asyncForEachFields \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) A function that takes an object `obj` and an `iterator` function, iterates over each field of the object, and executes the `iterator` for each field's value. The `iterator` supports `async` functions or functions that return a `Promise`. The optional parameter `concurrent` controls whether the `iterator` functions are called concurrently. If the value is `'sequential'`, the next `iterator` will only be executed after the `Promise` returned by the previous `iterator` is either fulfilled or rejected. > Added in v0.0.1 ### Usage ```ts import { asyncForEachFields } from 'parsnip-kit' const obj = { a: 1, b: 2, c: 3 } const logConcurrent = [] as any[] const iterator = (value, key, object) => { return new Promise((resolve) => { setTimeout(() => { logConcurrent.push({ key, value }) resolve(void 0) }, Math.random() * 100) }) } asyncForEachFields(obj, iterator, 'sequential').then(() => { console.log(logConcurrent) // Array contain { key: 'a', value: 1 }, { key: 'b', value: 2 }, { key: 'c', value: 3 } with random order. }) const logSequential = [] as any[] const iterator = (value, key, object) => { return new Promise((resolve) => { setTimeout(() => { logSequential.push({ key, value }) resolve(void 0) }, Math.random() * 100) }) } asyncForEachFields(obj, iterator, 'sequential').then(() => { console.log(logSequential) // [{ key: 'a', value: 1 }, { key: 'b', value: 2 }, { key: 'c', value: 3 }] }) ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends object` | Object type | | `R` | `extends 'concurrent' \| 'sequential' = 'concurrent' \| 'sequential'` | Concurrent type | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `T` | `false` | `undefined` | Object to iterate | | `iterator` | `(value: any, key: string, object: T) => any` | `false` | `undefined` | Iterator function | | `concurrent` | `R` | `true` | `'concurrent'` | Concurrent type | #### Returns | Type | | --- | | `Promise` | --- --- url: /en/async/asyncMap.md --- # asyncMap \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input an array `array` and an iterator `iterator`, traverse each element of the array, execute the `iterator` on each element, and return an array composed of the return values after each execution using `await`. The `iterator` supports `async` functions or functions that return a `Promise`. The optional parameter `concurrent` controls whether the `iterator` functions are called concurrently. If the value is `'sequential'`, the next `iterator` will only be executed after the `Promise` returned by the previous `iterator` is either fulfilled or rejected. > Added in v0.0.1 ### Usage ```ts import { asyncMap } from 'parsnip-kit' const array = [1, 2, 3] const logConcurrent = [] as any[] const iterator = (item, index, arr) => { return new Promise((resolve) => { setTimeout(() => { logConcurrent.push({ item, index }) resolve({ item, index }) }, Math.random() * 100) }) } asyncMap(array, iterator).then(res => { console.log(res) // [{ item: 1, index: 0 }, { item: 2, index: 1 }, { item: 3, index: 2 }] console.log(logConcurrent) // Array contain { item: 1, index: 0 }, { item: 2, index: 1 }, { item: 3, index: 2 } with random order. }) const logSequential = [] as any[] const iterator = (item, index, arr) => { return new Promise((resolve) => { setTimeout(() => { logSequential.push({ item, index }) resolve({ item, index }) }, Math.random() * 100) }) } asyncMap(array, iterator, 'sequential').then(res => { console.log(res) // [{ item: 1, index: 0 }, { item: 2, index: 1 }, { item: 3, index: 2 }] console.log(logSequential) // [{ item: 1, index: 0 }, { item: 2, index: 1 }, { item: 3, index: 2 }] }) ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Element type of array | | `U` | ` ` | Return type of the `iterator` | | `R` | `extends 'concurrent' \| 'sequential' = 'concurrent' \| 'sequential'` | Concurrent type | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `array` | `T[]` | `false` | `undefined` | Array to iterate | | `iterator` | `(item: T, index: number, array: T[]) => U \| Promise` | `false` | `undefined` | Iterator function | | `concurrent` | `R` | `true` | `'concurrent'` | Concurrent type | #### Returns | Type | | --- | | `Promise` | --- --- url: /en/statistic/average.md --- # average \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Calculates the average of the input array, supporting the extraction of numeric values via an optional parameter `getter` (or directly using the numeric values of the array elements). The `getter` is a field path of [getByPath](../object/getByPath) or a callback function, for extracting numerical values. > Added in v0.0.1 ### Usage ```ts import { average } from 'parsnip-kit' average([1, 2, 3, 4]) // 2.5 average([{ value: 10 }, { value: 20 }], item => item.value) // 15 average([{ score: 85 }, { score: 95 }], 'score') // 90 ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of input array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `data` | `T[]` | `false` | `undefined` | Input array | | `getter` | `string \| ((item: T, index: number, arr: T[]) => number)` | `true` | `undefined` | For extracting numerical values from array elements | #### Returns | Type | | --- | | `number` | --- --- url: /en/string/camelCase.md --- # camelCase \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Convert the string to camelCase. > Added in v0.0.1 ### Usage ```ts import { camelCase } from 'parsnip-kit' camelCase('HelloWorld') // 'helloWorld' camelCase('helloWorld') // 'helloWorld' camelCase('hello-world') // 'helloWorld' camelCase('hello_world') // 'helloWorld' camelCase('HELLO_WORLD') // 'helloWorld' camelCase('Hello World') // 'helloWorld' camelCase('-_HELLO World -_') // 'helloWorld' ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | The string to be converted. | #### Returns | Type | | --- | | `string` | --- --- url: /en/string/capitalize.md --- # capitalize \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Capitalize the first letter of the string. > Added in v0.0.1 ### Usage ```ts import { capitalize } from 'parsnip-kit' capitalize('HelloWorld') // 'Helloworld' ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | The string to be converted. | #### Returns | Type | | --- | | `string` | --- --- url: /en/array/chunk.md --- # chunk \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Splits array `arr` into sub-arrays with the length of `length`. > Added in v0.0.2 ### Usage ```ts import { chunk } from 'parsnip-kit' const arr = [1, 2, 3, 4, 5] chunk(arr, 2) // [[1, 2], [3, 4], [5]] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of elements of array to split | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arr` | `T[]` | `false` | `undefined` | The array to split | | `length` | `length` | `false` | `undefined` | The length of sub-arrays | #### Returns | Type | | --- | | `T[][]` | --- --- url: /en/object/clone.md --- # clone \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-95.27%-FF8C00) Accepts an argument `arg` and returns its shallow clone. Supports basic types, plain objects (`Object.prototype.toString.apply(arg).slice(8, -1)` returns `"Object"`), as well as built-in objects including these: `Array`, `Map`, `Set`, `Date`, `RegExp`. Similar to Lodash's approach, for built-in objects that are not cloneable, such as `Error`, `Function`, `Promise`, `HTMLElement`, etc., an empty plain object will be returned. For plain objects, it will attempt to construct a new object based on its prototype as a shallow clone. If there is no prototype, an empty object will be created. Then, the enumerable properties of the input argument `arg` will be added. For `Arguments` objects, the function will returns a `Array` as its clone (v0.0.3). For `RegExp` objects, the function will not clone the `lastIndex` field. Supported built-in objects for cloning: |Category|Supported Objects| |-|-| |Wrapper Classes|`String` `Number` `Boolean`| |Collection Types|`Object` `Array` `Map` `Set` `Arguments`(v0.0.3)| |Date and Time|`Date`| |Regular Expressions|`RegExp`| |Files and Streams|`Blob` `File` `ArrayBuffer`| |`TypedArray`|`Int8Array` `Uint8Array` `Uint8ClampedArray` `Int16Array` `Uint16Array` `Int32Array` `Uint32Array` `Float32Array` `Float64Array` `BigInt64Array` `BigUint64Array`| > Added in v0.0.1 ### Usage ```ts import { clone } from 'parsnip-kit' clone(undefined) // undefined clone(null) // null clone(123) // 123 clone('test') // 'test' clone(true) // true clone(BigInt(123)) // 123n clone(Symbol('test')) // Symbol(test) clone(new Date(0)) // Thu Jan 01 1970 08:00:00 clone(/test/) // /test/ const arr = [{ data: 1 }, { data: 2 }, { data: 3 }] const cloneArr = clone(arr) // [{ data: 1 }, { data: 2 }, { data: 3 }] cloneArray === arr // false const obj = { a: { data: 1 }, b: { data: 2 }, c: { data: 3 } } const cloneObj = clone(obj) // { a: { data: 1 }, b: { data: 2 }, c: { data: 3 } } cloneObj === obj // false const set = new Set([{ data: 1 }, { data: 2 }, { data: 3 }]) const cloneSet = clone(set) // Set(3) {{ data: 1 }, { data: 2 }, { data: 3 }} cloneSet === set // false const map = new Map([['a', { data: 1 }], ['b', { data: 2 }], ['c', { data: 3 }]]) const cloneMap = clone(map) // Map(3) {'a' => { data: 1 }, 'b' => { data: 2 }, 'c' => { data: 3 }} cloneMap === map // false ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends PrimitiveType \| ObjectLike` | Type of parameter to be cloned | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `T` | `false` | `undefined` | Parameter to be cloned | #### Returns | Type | | --- | | `T` | #### Reference [PrimitiveType](../common/types#primitivetype) [ObjectLike](../common/types#objectlike) --- --- url: /en/object/cloneDeep.md --- # cloneDeep \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-94.00%-FF8C00) Accepts an argument `arg` and returns its deep clone. Supports the same data types as the [clone](../object/clone) function. For objects that are not supported, refers to Lodash's handling approach by returning these objects themselves to ensure the usability of the copy results. An optional parameter `customizeClone` used to override the behavior when cloning unsupported objects and plain objects. > Added in v0.0.1 ### Usage ```ts import { cloneDeep, getTypeTag } from 'parsnip-kit' cloneDeep('test') // 'test' const testObj0 = [ { label: 'Time', dataIndex: 'time', validation: /^\d+$/, min: new Date() }, { label: 'Name', dataIndex: 'name', validation: (value) => !!(value ?? '').trim() } ] const clonedTestObj0 = cloneDeep(testObj0) // [ // { label: 'Time', dataIndex: 'time', validation: /^\d+$/, min: new Date() } // { label: 'Name', dataIndex: 'name', validation: (value) => !!(value ?? '').trim() } // ] clonedTestObj0 === testObj0 // false clonedTestObj0[0] === testObj0[0] // false clonedTestObj0[0].validation === testObj0[0].validation // false clonedTestObj0[1] === testObj0[1] // false clonedTestObj0[1].validation === testObj0[1].validation // true const testClass = class { #privateData publicData constructor(publicData, privateData) { this.#privateData = privateData this.publicData = publicData }, getPrivateData() { return this.#privateData } } const testObj1 = { data: new testClass('publicData', 'privateData') } const clonedTestObj1 = cloneDeep(testObj1) testObj1.data.getPrivateData() // 'privateData' clonedTestObj1.data.getPrivateData() // TypeError: Cannot read private member #privateData from an object whose class did not declare it const testCloner = ( value: any, key: string | undefined, cache: WeakMap, defaultClone4Object ) => { if (cache.has(value)) { return cache.get(value) } if (getTypeTag(value) === 'Object') { if (value instanceof testClass) { return new testClass(value.publicData, value.getPrivateData()) } else { return defaultClone4Object(value, cache, testCloner) } } else { return value } } const clonedTestObj2 = cloneDeep( testObj1, testCloner ) clonedTestObj2.data.getPrivateData() // 'privateData' const testCircle: any = {} testCircle.a = testCircle const clonedTestObj3 = cloneDeep(testCircle) clonedTestObj3.a === clonedTestObj3 // true ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of parameter to be cloned | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `T` | `false` | `undefined` | Parameter to be cloned | | `customizeClone` | `CustomizeClone` | `true` | `undefined` | Customize the cloning behavior for plain objects and unsupported built-in objects | #### Returns | Type | | --- | | `T` | --- --- url: /en/function/combine.md --- # combine \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Combine multiple functions and execute them in the specified order of `direction`, by default of `'right'` meaning executing from right to left. The return of each function takes the next function as an argument. > Added in v0.0.1 ### Usage ```typescript import { combine } from 'parsnip-kit' function add(a: number, b: number): number { return a + b } function multiply(a: number): number { return a * 2 } const combinedRight = combine([multiply, add] as const) combinedRight(2, 3) // 10 const combinedLeft = combine([add, multiply] as const, 'left') combinedLeft(2, 3) // 10 // This could be useful for combining curried functions. const multiplyCurried = (a: number) => (b: number) => a * b const addCurried = (a: number) => (b: number) => a + b const combinedRightCurried = combine([addCurried(2), multiplyCurried(3)] as const) combinedRightCurried(5) // 17 ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends readonly ((...args: any[]) => any)[]` | Function array type | | `R` | `extends 'left' \| 'right' = 'left' \| 'right'` | Combination direction type | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `functions` | `T` | `false` | `undefined` | The array of functions to combine | | `direction` | `R` | `true` | `'right'` | The direction in which to combine the functions | #### Returns | Type | | --- | | `(...args: EmptyOrParameters>) => EmptyOrReturnType>` | #### Reference [Edge](../common/types#edge) [EdgeReverse](../common/types#edgereverse) [EmptyOrParameters](../common/types#emptyorparameters) [EmptyOrReturnType](../common/types#emptyorreturntype) --- --- url: /en/async/concurrent.md --- # concurrent \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Execute a array of function `functions` that return `Promise` in parallel, with the `limit` parameter restricting the number of concurrent executions. > Added in v0.0.1 ### Usage ```ts import { concurrent } from 'parsnip-kit' const functions = Array.from( { length: 5 }, (_, i) => () => new Promise((resolve) => { setTimeout(() => { resolve(i) }, i * 100) }) concurrent(functions, 2).then(res => { console.log(res) // [{ status: 'fulfilled', value: 0 }, { status: 'fulfilled', value: 1 }, { status: 'fulfilled', value: 2 }, { status: 'fulfilled', value: 3 }, { status: 'fulfilled', value: 4 }] }) ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | The `value` type returned by a function that returns a `Promise` | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `functions` | `(() => Promise)[]` | `false` | `undefined` | Array of functions that return `Promise` | | `limit` | `number` | `false` | `undefined` | Array of functions that return `Promise` | #### Returns | Type | | --- | | `Promise>[]>` | --- --- url: /en/number/convertDataUnit.md --- # convertDataUnit \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Converts data between different units (e.g., bits, bytes, kilobytes, etc.). Supports binary prefix and decimal prefix. Binary prefixes are based on powers of 2 (e.g., 1 KiB = 2^10 bytes) defined by the International Electrotechnical Commission (IEC), while decimal prefixes are part of the International System of Units (SI) based on powers of 10 (e.g., 1 kB = 10^3 bytes). > Added in v0.0.2 ### Usage ```ts import { convertDataUnit } from 'parsnip-kit' convertDataUnit(1, 'B', 'bit', 'binary') // 8 convertDataUnit(1, 'B', 'bit', 'decimal') // 8 convertDataUnit(1024, 'B', 'KB', 'binary') // 1 convertDataUnit(1000, 'B', 'KB', 'decimal') // 1 ``` ### API #### Type Parameter #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `value` | `number` | `false` | `undefined` | The value of the data size to be converted | | `from` | `DataUnit` | `false` | `undefined` | The original unit of the data size | | `to` | `DataUnit` | `false` | `undefined` | The target data unit to convert to | | `prefix` | `'binary' \| 'decimal'` | `false` | `undefined` | The type of prefix to use in conversion (binary or decimal), defaults to `'binary'` | #### Returns | Type | | --- | | `number` | #### Reference [DataUnit](../common/types#dataunit) --- --- url: /en/statistic/count.md --- # count \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Count the occurrences of values extracted via the optional `getter` parameter (or directly using the array elements themselves). The `getter` is a field path of [getByPath](../object/getByPath) or a callback function, used to provide a label for frequency statistics. > Added in v0.0.1 ### Usage ```ts import { count } from 'parsnip-kit' count([1, 2, 2, 3, 3, 3]) // Map { 1 => 1, 2 => 2, 3 => 3 } const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 1, name: 'alice' } ] count(users, 'id') // Map { 1 => 2, 2 => 1 } count(users, (user) => user.name.toLowerCase()) // Map { 'alice' => 2, 'bob' => 1 } ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of input array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `data` | `T[]` | `false` | `undefined` | Input array | | `getter` | `string \| ((item: T, index: number, arr: T[]) => any)` | `true` | `undefined` | Provide an identifier to distinguish the elements | #### Returns | Type | | --- | | `Map` | --- --- url: /en/function/curry.md --- # curry \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Curries the given function. Curry, a fundamental concept in functional programming, involves transforming a function with multiple parameters into a sequence of functions that each accept a single parameter, facilitating the passing of parameters one at a time. > Added in v0.0.1 ### Usage ```typescript import { curry } from 'parsnip-kit' function add(a, b) { return a + b } const curriedAdd = curry(add) curriedAdd(2)(3) // 5 curriedAdd(2, 3) // 5 function greet(name, greeting = 'Hello') { return `${greeting}, ${name}!` } const curriedGreet = curry(greet) curriedGreet('Alice', 'Hi') // 'Hi, Alice!' curriedGreet('Bob') // 'Hello, Bob!' ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `Function` | `Function` | `false` | `undefined` | to be curried | #### Returns | Type | | --- | | `Function` | --- --- url: /en/function/debounce.md --- # debounce \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) This is a debounce function, which is used to limit the frequency of function calls. It will execute the function after a specified time interval. If the function is called multiple times within the interval, the previous timer will be cleared and reset. > Added in v0.0.1 ### Usage ```typescript import { debounce } from 'parsnip-kit' const handler = () => console.log('Function called') // Normal const debounced = debounce(handler, 300) debounced() // console.log is called after 300ms // Immediately executed debounce const immediateDebounced = debounce(handler, 300, { immediate: true }) immediateDebounced() // The console.log is called immediately, and subsequent calls are delayed by 300ms // Maximum waiting time setting const maxDebounced = debounce(handler, 500, { maxWait: 1000 }) maxDebounced() setTimeout(() => { maxDebounced() setTimeout(() => { maxDebounced() setTimeout(() => { maxDebounced() }, 400) }, 400) }, 400) // If it is not called within 1000ms, it will be triggered at 1000ms ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends (...args: any[]) => any` | Type of function to debounce | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `func` | `T` | `false` | `undefined` | The function to debounce | | `wait` | `number` | `false` | `undefined` | The delay time between two consecutive calls (in milliseconds) | | `options` | `object` | `true` | `undefined` | Optional parameter object | | `options.immediate` | `boolean` | `true` | `false` | Whether to execute the function immediately on the first call | | `options.maxWait` | `number` | `true` | `undefined` | Set the maximum waiting time | #### Returns | Type | | --- | | `(...args: Parameters) => void` | --- --- url: /en/function/delay.md --- # delay \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) This is a delay function that accepts a function `func` and a delay `wait` in milliseconds, and returns a function that will call the provided function after the specified delay. > Added in v0.0.1 ### Usage ```typescript import { delay } from 'parsnip-kit' const handler = () => console.log('Function call') const delayed = delay(handler, 3000) delayed() // console.log is called after 3s ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends (...args: any[]) => any` | Function type | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `func` | `T` | `false` | `undefined` | The function to delay | | `wait` | `number` | `false` | `undefined` | The delay time (in milliseconds) | #### Returns | Type | | --- | | `(...args: Parameters) => void` | --- --- url: /en/object/deleteByPath.md --- # deleteByPath \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input an object `obj` and a field path `path`, then traverse the object deeply according to the path to delete the field at the end of the path. > Added in v0.0.1 ### Usage ```ts import { deleteByPath } from 'parsnip-kit' const test0 = { a: 1 } deleteByPath(test0, 'a') // {} const test1 = [1] deleteByPath(test1, '[0]') // [] const test2 = { a: { b: { c: 1 } }, d: [2] } deleteByPath(test2, 'a.b') // { a: {}, d: [2] } ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `object` | `false` | `undefined` | Object to delete value | | `path` | `string` | `false` | `undefined` | Field path | #### Returns | Type | | --- | | `void` | --- --- url: /en/array/difference.md --- # difference \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input two arrays `arr1` and `arr2`, and return the difference set of `arr1` - `arr2`. Accepts a `getter`, which can be a field path of [getByPath](../object/getByPath) or a callback function, used to provide an identifier to distinguish elements. > Added in v0.0.1 ### Usage ```ts import { difference } from 'parsnip-kit' difference([1, 2, 3, NaN], [1, 4, 8, NaN]) // [2, 3] difference( [{ v: 1 }, { v: 2 }, { v: 3 }], [{ v: 1 }, { v: 4 }, { v: 8 }], 'v' ) // [{ v: 2 }, { v: 3 }] difference( [{ v: [1] }, { v: [2] }, { v: [3] }], [{ v: [1] }, { v: [4] }, { v: [8] }], 'v[0]' ) // [{ v: [2] }, { v: [3] }] difference([1.1, 2.4, 3.9, 4.16], [1, 2, 3, 4, 5, 6], Math.floor) // [] difference([1.1, 2.4, 3.9, 4.16], [1, 2, 3, 4, 5, 6], (item: number, index: number, arr: number[]) => { return Math.floor(item) }) // [] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of elements of array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arr1` | `T[]` | `false` | `undefined` | Array for computing the difference | | `arr2` | `T[]` | `false` | `undefined` | Array for computing the difference | | `getter` | `string \| ((item: T, index: number, arr: T[]) => any)` | `true` | `undefined` | Provide an identifier to distinguish the elements | #### Returns | Type | | --- | | `T[]` | --- --- url: /en/string/escapeRegExp.md --- # escapeRegExp \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Escapes the regular expression metacharacters in string `str` and returns the escaped string. > Added in v0.0.2 ### Usage ```ts import { escapeRegExp } from 'parsnip-kit' escapeRegExp('hello world') // 'hello world' escapeRegExp('${name}') // '\\$\\{name\\}' ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `str` | `string` | `false` | `undefined` | The string to escape | #### Returns | Type | | --- | | `string` | --- --- url: /en/object/filterFields.md --- # filterFields \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input an object `obj` and an iterator `iterator`, iterate over each field of the object, execute `iterator` for each field's value, remove the field if the return value `== false`, and return a new plain object or array. > Added in v0.0.1 ### Usage ```ts import { filterFields } from 'parsnip-kit' const obj = { a: 1, b: 2, c: 3 } const iterator0 = (value: number) => value > 1 const result0 = filterFields(obj, iterator0) // { b: 2, c: 3 } const arr0 = [0, 1, 2, 3] const iterator1 = (value: number) => value % 2 === 0 const result1 = filterFields(arr0, iterator1) // [0, 2] const arr1 = [0, 1, 2, 3] arr1['test'] = 'test' const iterator2 = (value, key) => typeof key === 'string' const result2 = filterFields(arr1, iterator2) // [test: 'test'] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends object` | Type of object to iterate | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `T` | `false` | `undefined` | Object to iterate | | `iterator` | `(value: any, key: string, object: T) => boolean` | `false` | `undefined` | Iterator function | #### Returns | Type | | --- | | `object` | --- --- url: /en/object/flattenObject.md --- # flattenObject \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-94.05%-FF8C00) Receive an object `obj`, perform a depth-first traversal of the enumerable properties of nested objects, and return a flattened new object where the key is the field path string and the value is the corresponding value. > Added in v0.0.4 ### Usage ```ts import { flattenObject } from 'parsnip-kit' const input0 = { a: [1, 2, { b: 3 }], c: { d: [4, 5, { e: 6 }] } } flattenObject(input0) // { // 'a[0]': 1, // 'a[1]': 2, // 'a[2].b': 3, // 'c.d[0]': 4, // 'c.d[1]': 5, // 'c.d[2].e': 6 // } const input1 = { a: {}, b: [], c: { d: {}, e: [] } } flattenObject(input1) // {} ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends object` | The type of the object to be flattened | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `T` | `false` | `undefined` | The object to be flattened | #### Returns | Type | | --- | | `FlattenNestObject` | #### Reference [FlattenNestObject](../common/types#flattennestobject) --- --- url: /en/object/forEachFields.md --- # forEachFields \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) A function that takes an object `obj` and an `iterator` function, iterates over each field of the object, and executes the `iterator` for each field's value. > Added in v0.0.1 ### Usage ```ts import { forEachFields } from 'parsnip-kit' const user = { name: 'John', age: 30 } forEachFields(user, (value, key, obj) => { console.log(`Key: ${key}, Value: ${value}`) }) // Key: name, Value: John // Key: age, Value: 30 ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends object` | Object type | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `T` | `false` | `undefined` | Object to iterate | | `iterator` | `(value: any, key: string, object: T) => any` | `false` | `undefined` | Iterator function | #### Returns | Type | | --- | | `void` | --- --- url: /en/object/getByPath.md --- # getByPath \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input an object `obj` and a field path `path`, then traverse the object deeply according to the path to retrieve the value. If the traversal is interrupted (e.g., the path is invalid) or the value is undefined or null, use `defaultValue` as the default value. > Added in v0.0.1 ### Usage ```ts import { getByPath } from 'parsnip-kit' getByPath({ a: 1 }, 'a') // 1 getByPath([1], '[0]') // 1 getByPath({ b: [0, 1, 2] }, 'b[2]') // 2 getByPath({ a: [{ b: { c: 'test' } }] }, 'a[0].b.c') // 'test' getByPath({ a: 1 }, 'a[0].b.c') // undefined getByPath({ a: 1 }, 'a[0].b.c', 'test') // 'test' ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `object` | `false` | `undefined` | Object to get value | | `path` | `string` | `false` | `undefined` | Field path | | `defaultValue` | `any` | `true` | `undefined` | Default value | #### Returns | Type | | --- | | `any` | --- --- url: /en/typed/getTypeTag.md --- # getTypeTag \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Returns the type tag of the provided argument using `Object.prototype.toString`. > Added in v0.0.1 ### Usage ```ts import { getTypeTag } from 'parsnip-kit' getTypeTag('hello') // 'String' getTypeTag(42) // 'Number' getTypeTag(null) // 'Null' getTypeTag([1, 2, 3]) // 'Array' getTypeTag({ a: 1 }) // 'Object' getTypeTag(() => {}) // 'Function' ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | The argument to check | #### Returns | Type | | --- | | `string` | --- --- url: /en/function/go.md --- # go \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) This function mimics the Go language's error handling style, Executing a function (async or regular) and returning a fulfilled `Promise` with value of a tuple of `[Awaited, null]` on success or `[null, error]` on failure. > Added in v0.0.4 ### Usage ```ts import { go } from 'parsnip-kit' function getUltraAnswer() { return Promise(resolve => setTimeout(resolve, 750)) } const [result0, error0] = await go(getUltraAnswer) // [42, null] if (error0 !== null) { // do something... } function throwErrorExample() { throw new Error('test') } const [result1, error1] = await go(throwErrorExample) // [null, Error: test] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | The type of the function's return value | | `U` | `= any` | The type of the error (defaults to `any`) | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `func` | `(...x: any[]) => T` | `false` | `undefined` | The function to execute. | #### Returns | Type | | --- | | `Promise<[T, null] \| [null, U]>` | --- --- url: /en/string/htmlDecode.md --- # htmlDecode \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Decode the string from HTML entities, converting specific HTML entities (such as `<`, `>`, `&`) back to their corresponding plain characters (e.g., <, >, &). > Added in v0.0.1 ### Usage ```ts import { htmlDecode } from 'parsnip-kit' htmlDecode(''test'') // '\'test\'' htmlDecode('"test"') // '"test"' htmlDecode('<img/>') // '' htmlDecode('talk & code') // 'talk & code' ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | The string to be converted. | #### Returns | Type | | --- | | `string` | --- --- url: /en/string/htmlEncode.md --- # htmlEncode \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Encode the string into HTML entities, converting special characters (such as <, >, &) to their corresponding HTML entities (e.g., `<`, `>`, `&`). This prevents these characters from being mistakenly interpreted as part of HTML tags by the browser. > Added in v0.0.1 ### Usage ```ts import { htmlEncode } from 'parsnip-kit' htmlEncode('\'test\'') // ''test'' htmlEncode('"test"') // '"test"' htmlEncode('') // '<img/>' htmlEncode('talk & code') // 'talk & code' ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | The string to be converted. | #### Returns | Type | | --- | | `string` | --- --- url: /en/array/intersection.md --- # intersection \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input two arrays `arr1` and `arr2`, and return their intersection. Accepts a `getter`, which can be a field path of [getByPath](../object/getByPath) or a callback function, used to provide an identifier to distinguish elements. > Added in v0.0.1 ### Usage ```ts import { intersection } from 'parsnip-kit' intersection([1, 2, 3, NaN], [1, 4, 8, NaN]) // [1, NaN] intersection( [{ v: 1 }, { v: 2 }, { v: 3 }], [{ v: 1 }, { v: 4 }, { v: 8 }], 'v' ) // [{ v: 1 }] intersection( [{ v: [1] }, { v: [2] }, { v: [3] }], [{ v: [1] }, { v: [4] }, { v: [8] }], 'v[0]' ) // [{ v: [1] }] intersection([1.1, 2.4, 3.9, 4.16], [1, 2, 3, 4, 5, 6], Math.floor) // [1.1, 2.4, 3.9, 4.16] intersection([1.1, 2.4, 3.9, 4.16], [1, 2, 3, 4, 5, 6], (item: number, index: number, arr: number[]) => { return Math.floor(item) }) // [1.1, 2.4, 3.9, 4.16] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of elements of array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arr1` | `T[]` | `false` | `undefined` | Array to be intersected | | `arr2` | `T[]` | `false` | `undefined` | Array to be intersected | | `getter` | `string \| ((item: T, index: number, arr: T[]) => any)` | `true` | `undefined` | Provide an identifier to distinguish the elements | #### Returns | Type | | --- | | `T[]` | --- --- url: /en/typed/isArray.md --- # isArray \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check if the input parameter is an array. > Added in v0.0.1 ### Usage ```ts import { isArray } from 'parsnip-kit' isArray([1, 2, 3]) // true isBigInt(`123`) // false ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isBigInt.md --- # isBigInt \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check if the input parameter is a `bigint`. > Added in v0.0.1 ### Usage ```ts import { isBigInt } from 'parsnip-kit' isBigInt(BigInt(123)) // true isBigInt(123) // false isBigInt(NaN) // false isBigInt(Infinity) // false ``` ### API #### Arguments #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isBoolean.md --- # isBoolean \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check whether the input parameter is a primitive boolean or a `Boolean` instance. > Added in v0.0.1 ### Usage ```ts import { isBoolean } from 'parsnip-kit' isBoolean('test') // false isBoolean(1) // false isBoolean('') // false isBoolean(null) // false isBoolean(undefined) // false isBoolean(true) // true isBoolean(false) // true isBoolean(Boolean()) // true ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isClass.md --- # isClass \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check if the input parameter is a class. > Added in v0.0.1 ### Usage ```ts import { isClass } from 'parsnip-kit' isClass({}) // false isClass(() => {}) // false isClass(class {}) // true ``` ### API | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/object/isEqual.md --- # isEqual \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-93.67%-FF8C00) Input two parameters `arg1` and `arg2`, perform a deep comparison to check each of their properties, and return whether they are equal. Supports basic types, plain objects (`arg => Object.prototype.toString.apply(arg).slice(8, -1)` returns `"Object"`), and built-in objects including these: `Array`, `Map`, `Set`, `Date`, `RegExp`. For unsupported built-in objects, such as `Blob`, `File`, `Error`, `Function`, `Promise`, `HTMLElement`, etc., [isEqualStrict](../object/isEqualStrict) will be called for strict comparison. For plain objects, only their enumerable properties are checked, and the prototype chain is not examined. Built-in objects supported for deep comparison: |Category|Supported Objects| |-|-| |Wrapper Classes|`String` `Number` `Boolean`| |Collection Types|`Object` `Array` `Map` `Set`| |Date and Time|`Date`| |Regular Expressions|`RegExp`| |Files and Streams| `ArrayBuffer`| |`TypedArray`|`Int8Array` `Uint8Array` `Uint8ClampedArray` `Int16Array` `Uint16Array` `Int32Array` `Uint32Array` `Float32Array` `Float64Array` `BigInt64Array` `BigUint64Array`| > Added in v0.0.1 ### Usage ```ts import { isEqual } from 'parsnip-kit' const arr1 = [1, [2, 3]] const arr2 = [1, [2, 3]] isEqual(arr1, arr2) // true const obj1 = { a: 1, b: { c: 2 } } const obj2 = { a: 1, b: { c: 2 } } isEqual(obj1, obj2) // true const obj3 = { project: ['A', 'B', 'C'], startTime: new Date('2025-1-1'), status: { finish: false, block: true } } const obj4 = { project: ['A', 'B', 'C'], startTime: new Date('2025-1-1'), status: { finish: false, block: true } } isEqual(obj3, obj4) // true const map1 = new Map([[['a'], { data: 1 }], [['b'], { data: 2 }]]) const map2 = new Map([[['a'], { data: 1 }], [['b'], { data: 2 }]]) isEqual(map1, map2) // true ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg1` | `any` | `false` | `undefined` | Variable to compare | | `arg2` | `any` | `false` | `undefined` | Variable to compare | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/object/isEqualStrict.md --- # isEqualStrict \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input two parameters `arg1` and `arg2`, and return whether they are strictly equal. > Added in v0.0.1 ### Usage ```ts import { isEqualStrict } from 'parsnip-kit' isEqualStrict(1, 1) // true isEqualStrict(+0, -0) // false isEqualStrict(NaN, NaN) // true isEqualStrict({ a: 1 }, { a: 1 }) // false ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg1` | `any` | `false` | `undefined` | Variable to compare | | `arg2` | `any` | `false` | `undefined` | Variable to compare | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isFloat.md --- # isFloat \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check if the input parameter is a float or a `Number` object with a float value. > Added in v0.0.1 ### Usage ```ts import { isFloat } from 'parsnip-kit' isFloat(123.1) // true isFloat(new Number(123.1)) // true isFloat(123) // false isFloat(BigInt(123)) // false isFloat(NaN) // false isFloat(Infinity) // false ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isFunction.md --- # isFunction \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check if the input parameter is a function, including classes (`class {}`), generator functions (`function*() {}`), and async functions (`async function() {}`). > Added in v0.0.1 ### Usage ```ts import { isFunction } from 'parsnip-kit' isFunction({}) // false isFunction(() => {}) // true isFunction(class {}) // true isFunction(function*() {}) // true isFunction(async () => {}) // true ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isInfinity.md --- # isInfinity \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check if the input parameter is positive or negative infinity, or a Number object with a value of positive or negative infinity. > Added in v0.0.1 ### Usage ```ts import { isInfinity } from 'parsnip-kit' isInfinity(123) // false isInfinity('123') // false isInfinity(NaN) // false isInfinity(Infinity) // true isInfinity(-Infinity) // true isInfinity(new Number(Infinity)) // true ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isInt.md --- # isInt \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check if the input parameter is an integer or a `Number` object with an integer value. > Added in v0.0.1 ### Usage ```ts import { isInt } from 'parsnip-kit' isInt(123) // true isInt(new Number(123)) // true isInt(123.1) // false isInt(BigInt(123)) // false isInt(NaN) // false isInt(Infinity) // false ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isNanValue.md --- # isNanValue \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check if the input parameter is a `NaN` or a `Number` object with a `NaN` value. > Added in v0.0.1 ### Usage ```ts import { isNanValue } from 'parsnip-kit' isNanValue(123) // false isNanValue('123') // false isNanValue(Infinity) // false isNanValue(NaN) // true isNanValue(new Number(NaN)) // true ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isNull.md --- # isNull \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check if the input parameter is a `null`. > Added in v0.0.1 ### Usage ```ts import { isNull } from 'parsnip-kit' isNull(null) // true isNull({}) // false isNull(undefined) // false ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isNullish.md --- # isNullish \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check if the input parameter is a `undefined` or `null`. > Added in v0.0.4 ### Usage ```ts import { isNullish } from 'parsnip-kit' isNullish(undefined) // true isNullish(null) // true isNullish(NaN) // false isNullish(0) // false ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters to check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isNumber.md --- # isNumber \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check whether the input parameter is a primitive number or a `Number` instance. > Added in v0.0.1 ### Usage ```ts import { isNumber } from 'parsnip-kit' isNumber('test') // false isNumber(123) // true isNumber(new Number(123)) // true isNumber(Infinity) // true isNumber(NaN) // true ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isNumberString.md --- # isNumberString \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check if the input is string consisting only of numeric characters. > Added in v0.0.1 ### Usage ```ts import { isNumberString } from 'parsnip-kit' isNumberString('12345') // true isNumberString('123a5') // false isNumberString('') // false ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isObject.md --- # isObject \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check whether the input parameter is an object, including general objects (`{ key: 'value' }`), functions (`function() {}`), and instances of primitive type wrappers (`new Number(1)`), all of which would return `true`. > Added in v0.0.1 ### Usage ```ts import { isObject } from 'parsnip-kit' isObject(null) // false isObject({}) // true isObject(() => {}) // true isObject(new Number()) // true isObject(/test/) // true isObject(new Date()) // true ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isObjectLike.md --- # isObjectLike \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check if the input parameter is an object, excluding functions. > Added in v0.0.1 ### Usage ```ts import { isObjectLike } from 'parsnip-kit' isObjectLike({}) // true isObjectLike(() => {}) // false ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isPrimitive.md --- # isPrimitive \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check if the input parameter is a primitive type, including `number`, `string`, `boolean`, `null`, `undefined`, `symbol`, and `bigint`. > Added in v0.0.1 ### Usage ```ts import { isPrimitive } from 'parsnip-kit' isPrimitive(1) // true isPrimitive('test') // true isPrimitive(true) // true isPrimitive(null) // true isPrimitive(undefined) // true isPrimitive(Symbol()) // true isPrimitive(BigInt(1)) // true isPrimitive(new Number(1)) // false isPrimitive(new String('test')) // false isPrimitive(new Boolean(true)) // false isPrimitive({}) // false isPrimitive(new Date()) // false ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isPseudoArray.md --- # isPseudoArray \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Determine whether the input parameter is a pseudo-array, i.e., an object that can be accessed via numeric indices (which is true for most ordinary JavaScript objects) and has a numeric `length` property. > Added in v0.0.1 ### Usage ```ts import { isPseudoArray } from 'parsnip-kit' isPseudoArray({}) // false isPseudoArray({ length: 1 }) // true isPseudoArray([]) // true function test () { isPseudoArray(arguments) // true } test() // in browser isPseudoArray(document.querySelectorAll('div')) // true ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isString.md --- # isString \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check whether the input parameter is a primitive string or a `String` instance. > Added in v0.0.1 ### Usage ```ts import { isString } from 'parsnip-kit' isString('test') // true isString(new String('test')) // true isString(123) // false ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isSymbol.md --- # isSymbol \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check if the input parameter is a `symbol`. > Added in v0.0.1 ### Usage ```ts import { isSymbol } from 'parsnip-kit' isSymbol(Symbol('test')) // true isSymbol('test') // false ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/typed/isUndefined.md --- # isUndefined \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Check if the input parameter is a `undefined`. > Added in v0.0.1 ### Usage ```ts import { isUndefined } from 'parsnip-kit' isUndefined(null) // false isUndefined(void 0) // true isUndefined(undefined) // true ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | Parameters for check | #### Returns | Type | | --- | | `boolean` | --- --- url: /en/array/joinToObject.md --- # joinToObject \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input an array of objects `fields`, and return a plain object formed by combining each item from the array. The optional parameters `getKey` and `getValue` are used to convert child objects into keys and values. When they are not provided, the first field of the array element is extracted by default. `getKey` and `getValue` can be field paths of [getByPath](../object/getByPath) or callback functions. > Added in v0.0.1 ### Usage ```ts import { joinToObject } from 'parsnip-kit' const users = [{ Alex: 'vip' }, { Bob: 'viewer' }, { Carter: 'user' }, { Daniel: 'user' }] joinToObject(users) // { Alex: 'vip', Bob: 'viewer', Carter: 'user', Daniel: 'user' } const data = [ { name: 'Alex', type: 'vip' }, { name: 'Bob', type: 'viewer' }, { name: 'Carter', type: 'user' }, { name: 'Daniel', type: 'user' } ] joinToObject(data, 'name', 'type') // { Alex: 'vip', Bob: 'viewer', Carter: 'user', Daniel: 'user' } joinToObject(data, pair => pair.name, pair => pair.type) // { Alex: 'vip', Bob: 'viewer', Carter: 'user', Daniel: 'user' } ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends object` | Type of elements of array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `pairs` | `T[]` | `false` | `undefined` | The array of key-value object | | `getKey` | `string \| ((item: T, index: number, arr: T[]) => any)` | `true` | `undefined` | Extract keys form sub-objects | | `getValue` | `string \| ((item: T, index: number, arr: T[]) => any)` | `true` | `undefined` | Extract values form sub-objects | #### Returns | Type | | --- | | `ObjectLike` | #### Reference [ObjectLike](../common/types#objectlike) --- --- url: /en/string/kebabCase.md --- # kebabCase \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Convert the string to kebab-case. > Added in v0.0.1 ### Usage ```ts import { kebabCase } from 'parsnip-kit' kebabCase('HelloWorld') // 'hello-world' kebabCase('helloWorld') // 'hello-world' kebabCase('hello-world') // 'hello-world' kebabCase('hello_world') // 'hello-world' kebabCase('HELLO_WORLD') // 'hello-world' kebabCase('Hello World') // 'hello-world' kebabCase('-_HELLO World -_') // 'hello-world' ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | The string to be converted. | #### Returns | Type | | --- | | `string` | --- --- url: /en/array/leftJoin.md --- # leftJoin \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input two arrays `left` and `right`, and return the array formed by performing a left join of `left` with `right`. This is commonly used to combine arrays of objects that contain related information, similar to how it is done in SQL. Additionally, it accepts two parameters: `leftKey` and `rightKey`. These can be field paths of [getByPath](../object/getByPath) or callback functions, used to provide identifiers to distinguish elements. The `merge` function is used to generate the return array objects. > Added in v0.0.1 ### Usage ```ts import { leftJoin } from 'parsnip-kit' const leftArray0 = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }, ] const rightArray0 = [ { id: 1, age: 25 }, { id: 3, age: 30 }, ] leftJoin( leftArray0, rightArray0, (item) => item.id, (item) => item.id, (left, right) => ({ ...left, ...(right || {}) }), ) // [{ id: 1, name: 'Alice', age: 25 }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie', age: 30 }] const leftArray1 = [ { id: 1, info: { name: 'Alice', age: 25 } }, { id: 2, info: { name: 'Bob', age: 35 } }, { id: 3, info: { name: 'Charlie', age: 30 } }, ] const rightArray1 = [ { name: 'Alice', experience: ['software engineer', 'designer'] }, { name: 'Charlie', experience: ['freelance'] }, ] leftJoin( leftArray1, rightArray1, 'info.name', 'name', (left, right) => ({ name: left.info.name, job: right?.experience[0] ?? null }), ) // [{ name: 'Alice', job: 'software engineer' }, { name: 'Bob', job: null }, { name: 'Charlie', job: 'freelance' }] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends object` | Type of elements of left array in a left join | | `U` | `extends object` | Type of elements of right array in a left join | | `R` | `extends object` | Type of elements of array returned | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `left` | `T[]` | `false` | `undefined` | The left array in a left join | | `right` | `U[]` | `false` | `undefined` | The right array in a left join | | `leftKey` | `string \| ((item: T, index: number, arr: T[]) => any)` | `false` | `undefined` | Provide an identifier to distinguish elements in the left array | | `rightKey` | `string \| ((item: U, index: number, arr: U[]) => any)` | `false` | `undefined` | Provide an identifier to distinguish elements in the right array | | `merge` | `(left: T, right: U \| undefined) => R` | `false` | `undefined` | Return the result of merging elements from left and right arrays. | #### Returns | Type | | --- | | `R[]` | --- --- url: /en/array/lexSort.md --- # lexSort \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Sorts parameter `arr` lexicographically based on the order specified by parameter `order` with the default of `'asc'`. The parameter `order` can be specified as either `'asc'` (ascending order) or `'desc'` (descending order). It will call [stringComparatorAsc](../common/constants#stringcomparatorasc) or [stringComparatorDesc](../common/constants#stringcomparatordesc) internally. The optional parameter `getter` is used to obtain the string value from elements of `arr`, with the default being to use the element itself for sorting. `getter` can be a field path of [getByPath](../object/getByPath) or a callback function. > Added in v0.0.2 ### Usage ```ts import { lexSort } from 'parsnip-kit' const fruits = ['banana', 'apple', 'cherry', 'date'] lexSort(fruit) // ['apple', 'banana', 'cherry', 'date'] const people = [ { name: 'John', age: 30 }, { name: 'Alice', age: 25 }, { name: 'Bob', age: 35 } ] lexSort([...people], 'desc', 'name') // [ // { name: 'John', age: 30 }, // { name: 'Bob', age: 35 }, // { name: 'Alice', age: 25 } // ] lexSort([...people], 'asc', item => item.name) // [ // { name: 'John', age: 30 }, // { name: 'Bob', age: 35 }, // { name: 'Alice', age: 25 } // ] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of elements of array | | `R` | `extends 'asc' \| 'desc' = 'asc' \| 'desc'` | Type of order for sorting | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arr` | `T[]` | `false` | `undefined` | Array to be sorted | | `order` | `R` | `false` | `undefined` | Order for sorting | | `getter` | `string \| ((item: T) => string)` | `false` | `undefined` | For extracting string values from array elements | #### Returns | Type | | --- | | `T[]` | --- --- url: /en/array/linkToTree.md --- # linkToTree \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Converts a flat array `arr` into a tree structure and returns the array of root nodes. This is useful for build the tree options from flat array. Note: this function can modify the elements of `arr`. Optional parameters: * `getKey`: Used to obtain the unique identifier for each element. This can be a field path for [getByPath](../object/getByPath) or a function. * `getParent`: Retrieves the parent identifier for each element. Like `getKey`, it can be a field path for [getByPath](../object/getByPath) or a function. * `childrenPath`: Specifies the field path in the object where child elements should be stored. It defaults to `'children'`. Both [getByPath](../object/getByPath) and [setByPath](../object/setByPath) will utilize this path when accessing or modifying the child elements. > Added in v0.0.2 ### Usage ```ts import { linkToTree } from 'parsnip-kit' const arr = [ { id: '1', parentId: null, name: 'Root 1' }, { id: '2', parentId: '1', name: 'Child 1' }, { id: '3', parentId: '1', name: 'Child 2' }, { id: '4', parentId: '2', name: 'Grandchild 1' }, { id: '5', parentId: null, name: 'Root 2' } ] const result = linkToTree(arr, 'id', 'parentId', 'items') // [ // { // id: '1', // parentId: null, // name: 'Root 1', // items: [ // { // id: '2', // parentId: '1', // name: 'Child 1', // items: [ // { // id: '4', // parentId: '2', // name: 'Grandchild 1', // items: [] // } // ] // }, // { // id: '3', // parentId: '1', // name: 'Child 2', // items: [] // } // ] // }, // { // id: '5', // parentId: null, // name: 'Root 2', // items: [] // } // ] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends object` | The type of elements of array `arr` | | `R` | `extends string` | The type of `childrenPath` | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arr` | `T[]` | `false` | `undefined` | The flat array to be converted into a tree structure | | `getKey` | `string \| ((item: T, index: number, arr: T[]) => string)` | `true` | `undefined` | To get the unique identifier | | `getParent` | `string \| ((item: T, index: number, arr: T[]) => string)` | `true` | `undefined` | To get the parent identifier | | `childrenPath` | `R` | `true` | `'children'` | The field path in the object where child elements should be stored | #### Returns | Type | | --- | | `(T & DeepMappedTypeByKeyOrIndex, T[], false>)[]` | #### Reference [LiteralStringWithFallback](../common/types#literalstringwithfallback) [DeepMappedTypeByKeyOrIndex](../common/types#deepmappedtypebykeyorindex) --- --- url: /en/statistic/max.md --- # max \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Calculates the maximum of the input array, supporting the extraction of numeric values via an optional parameter `getter` (or directly using the numeric values of the array elements). The `getter` is a field path of [getByPath](../object/getByPath) or a callback function, for extracting numerical values. > Added in v0.0.1 ### Usage ```ts import { max } from 'parsnip-kit' max([1, 2, 3, 4]) // 4 max([{ value: 10 }, { value: 20 }], item => item.value) // 20 max([{ score: 85 }, { score: 95 }], 'score') // 95 ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of input array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `data` | `T[]` | `false` | `undefined` | Input array | | `getter` | `string \| ((item: T, index: number, arr: T[]) => number)` | `true` | `undefined` | For extracting numerical values from array elements | #### Returns | Type | | --- | | `number` | --- --- url: /en/statistic/maxItem.md --- # maxItem \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Calculate the maximum value of the input array and return the first elements that have the maximum value, supporting the extraction of numeric values via an optional parameter `getter` (or directly using the numeric values of the array elements). The `getter` is a field path of [getByPath](../object/getByPath) or a callback function, for extracting numerical values. > Added in v0.0.1 ### Usage ```ts import { maxItem } from 'parsnip-kit' maxItem([1, 2, 3, 4]) // 4 maxItem([{ value: 10 }, { value: 20 }, { value: 20, key: 'count' }], item => item.value) // { value: 20 } maxItem([{ value: 10 }, { value: 20 }, { value: 20, key: 'count' }], 'value') // { value: 20 } ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of input array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `data` | `T[]` | `false` | `undefined` | Input array | | `getter` | `string \| ((item: T, index: number, arr: T[]) => number)` | `true` | `undefined` | For extracting numerical values from array elements | #### Returns | Type | | --- | | `T` | --- --- url: /en/statistic/median.md --- # median \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Calculates the median of the input array, supporting the extraction of numeric values via an optional parameter `getter` (or directly using the numeric values of the array elements). The `getter` is a field path of [getByPath](../object/getByPath) or a callback function, for extracting numerical values. > Added in v0.0.1 ### Usage ```ts import { median } from 'parsnip-kit' median([1, 2, 3, 4, 0]) // 2 median([1, 2, 3, 4]) // 2.5 median([{ value: 10 }, { value: 20 }, { value: 10 }], item => item.value) // 10 median([{ score: 100 }, { score: 85 }, { score: 95 }], 'score') // 95 ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `TType` | ` ` | of input array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `data` | `T[]` | `false` | `undefined` | Input array | | `getter` | `string \| ((item: T, index: number, arr: T[]) => number)` | `true` | `undefined` | For extracting numerical values from array elements | #### Returns | Type | | --- | | `number` | --- --- url: /en/function/memoize.md --- # memoize \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) This is a memoize function, which is used to cache the return values of a function. When called again with the same parameters, it will return the cached result, avoiding redundant calculations. By default, uses `JSON.stringify(arguments)` as the cache key. > Added in v0.0.1 ### Usage ```typescript import { memoize } from 'parsnip-kit' function expensiveCalculation(a: number, b: number): number { // Simulate an expensive computation process console.log('Calculating...') return a + b } const memoizedCalc = memoize(expensiveCalculation) memoizedCalc(2, 3) // Calculating...,returns 5 memoizedCalc(2, 3) // directly return 5, do not call expensiveCalculation // Use a custom resolver const memoizedCalcWithResolver = memoize( expensiveCalculation, (a, b) => a + b ) memoizedCalcWithResolver(2, 3) // Calculating...,returns 5 memoizedCalcWithResolver(4, 1) // directly return 5, do not call expensiveCalculation const memoizedCalcWithAllArgs = memoize( expensiveCalculation, (a, b) => a + b, [2, 3] ) // Calculating..., call expensiveCalculation to cache memoizedCalcWithAllArgs(2, 3) // directly return 5, do not call expensiveCalculation ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends (...args: any[]) => any` | Type of function to memoize | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `func` | `T` | `false` | `undefined` | The function to memoize | | `resolver` | `( ...args: Parameters ) => any` | `true` | `undefined` | A function used to generate cache keys | | `initCache` | ` Parameters` | `true` | `undefined` | Parameters for initializing the cache | #### Returns | Type | | --- | | `( ...args: Parameters ) => ReturnType` | --- --- url: /en/object/mergeSkipNullish.md --- # mergeSkipNullish \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Merge multiple objects from left to right to form a new object. Fields that are not `null` or `undefined` in the preceding objects will not be overwritten by `null` or `undefined` fields from the subsequent objects. > Added in v0.0.4 ### Usage ```ts import { mergeSkipNullish } from 'parsnip-kit' const obj1 = { a: 1, b: null, c: undefined } const obj2 = { b: 2, c: 3, d: null } const obj3 = { c: undefined, d: 4, e: 5 } mergeSkipNullish(obj1, obj2, obj3) // { a: 1, b: 2, c: 3, d: 4, e: 5 } ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends object` | The type of the objects to merge | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `...objs` | `(T \| Nullish)[]` | `false` | `undefined` | The objects to merge | #### Returns | Type | | --- | | `T` | #### Type Definition ```ts { ( a: T | Nullish, b: U | Nullish ): SpreadSkipNullish ( a: T | Nullish, b: U | Nullish, c: V | Nullish ): SpreadSkipNullish, V> ( a: T | Nullish, b: U | Nullish, c: V | Nullish, d: W | Nullish ): SpreadSkipNullish, V>, W> (...objs: any[]): any } ``` #### Reference [Nullish](../common/types#nullish) [SpreadSkipNullish](../common/types#spreadskipnullish) --- --- url: /en/statistic/min.md --- # min \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Calculates the minimum of the input array, supporting the extraction of numeric values via an optional parameter `getter` (or directly using the numeric values of the array elements). The `getter` is a field path of [getByPath](../object/getByPath) or a callback function, for extracting numerical values. > Added in v0.0.1 ### Usage ```ts import { min } from 'parsnip-kit' min([1, 2, 3, 4]) // 1 min([{ value: 10 }, { value: 20 }], item => item.value) // 10 min([{ score: 85 }, { score: 95 }], 'score') // 85 ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of input array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `data` | `T[]` | `false` | `undefined` | Input array | | `getter` | `string \| ((item: T, index: number, arr: T[]) => number)` | `true` | `undefined` | For extracting numerical values from array elements | #### Returns | Type | | --- | | `number` | --- --- url: /en/statistic/minItem.md --- # minItem \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Calculate the minimum value of the input array and return the first elements that have the minimum value, supporting the extraction of numeric values via an optional parameter `getter` (or directly using the numeric values of the array elements). The `getter` is a field path of [getByPath](../object/getByPath) or a callback function, for extracting numerical values. > Added in v0.0.1 ### Usage ```ts import { minItem } from 'parsnip-kit' minItem([1, 2, 3, 4]) // 1 minItem([{ value: 10 }, { value: 10, key: 'count' }, { value: 20 }], item => item.value) // { value: 10 } minItem([{ value: 10 }, { value: 10, key: 'count' }, { value: 20 }], 'value') // { value: 10 } ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of input array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `data` | `T[]` | `false` | `undefined` | Input array | | `getter` | `string \| ((item: T, index: number, arr: T[]) => number)` | `true` | `undefined` | For extracting numerical values from array elements | #### Returns | Type | | --- | | `T` | --- --- url: /en/statistic/mode.md --- # mode \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Extract key values using the optional `getter` parameter (or directly using the array elements themselves), and return the most frequently occurring value. The `getter` is a field path of [getByPath](../object/getByPath) or a callback function, used to provide a label for frequency statistics. > Added in v0.0.1 ### Usage ```ts import { mode } from 'parsnip-kit' mode([1, 2, 2, 3, 3, 3]) // 3 const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 1, name: 'alice' } ] mode(users, 'id') // 1 mode(users, (user) => user.name.toLowerCase()) // 'alice' ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of input array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `data` | `T[]` | `false` | `undefined` | Input array | | `getter` | `string \| ((item: T, index: number, arr: T[]) => any)` | `true` | `undefined` | Provide an identifier to distinguish the elements | #### Returns | Type | | --- | | `any` | --- --- url: /en/statistic/modeItem.md --- # modeItem \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Extract key values using the optional `getter` parameter (or directly using the array elements themselves), and return the first element that have the most frequently occurring value. The `getter` is a field path of [getByPath](../object/getByPath) or a callback function, used to provide a label for frequency statistics. > Added in v0.0.1 ### Usage ```ts import { modeItem } from 'parsnip-kit' modeItem([1, 2, 2, 3, 3, 3]) // 3 const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 1, name: 'alice' } ] modeItem(users, 'id') // { id: 1, name: 'Alice' } modeItem(users, (user) => user.name.toLowerCase()) // { id: 1, name: 'Alice' } ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of input array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `data` | `T[]` | `false` | `undefined` | Input array | | `getter` | `string \| ((item: T, index: number, arr: T[]) => any)` | `true` | `undefined` | Provide an identifier to distinguish the elements | #### Returns | Type | | --- | | `T` | --- --- url: /en/array/numberSort.md --- # numberSort \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Sorts parameter `arr` numerically based on the order specified by parameter `order` with the default of `'asc'`. The parameter `order` can be specified as either `'asc'` (ascending order) or `'desc'` (descending order). It will call [numberComparatorAsc](../common/constants#numbercomparatorasc) or [numberComparatorDesc](../common/constants#numbercomparatordesc) internally. The optional parameter `getter` is used to obtain the numerical value from elements of `arr`, with the default being to use the element itself for sorting. `getter` can be a field path of [getByPath](../object/getByPath) or a callback function. > Added in v0.0.2 ### Usage ```ts // Usage ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of elements of array | | `R` | `extends 'asc' \| 'desc' = 'asc' \| 'desc'` | Type of order for sorting | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arr` | `T[]` | `false` | `undefined` | Array to be sorted | | `order` | `R` | `false` | `undefined` | Order for sorting | | `getter` | `string \| ((item: T) => number)` | `false` | `undefined` | For extracting numerical values from array elements | #### Returns | Type | | --- | | `T[]` | --- --- url: /en/object/objectToPairs.md --- # objectToPairs \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) input an object `obj`, and return an array composed of arrays formed by each field's key-value pairs, or composed of the results returned by the optional parameter `createItem`. > Added in v0.0.1 ### Usage ```ts import { objectToPairs } from 'parsnip-kit' const obj = { Alex: 16, Bob: 659, Carter: 155, Daniel: 825 } objectToPairs(obj) // [['Alex', 16], ['Bob', 659], ['Carter', 155], ['Daniel', 825]] objectToPairs(obj, (value, key) => ({ [key]: value })) // [{ Alex: 16 }, { Bob: 659 }, { Carter: 155 }, { Daniel: 825 }] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends object` | Type of original object | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `T` | `false` | `undefined` | Original object | | `createItem` | `(value: T[string & keyof T], key: string, obj: T) => any` | `true` | `undefined` | To create element of array to be returned | #### Returns | Type | | --- | | `any[]` | --- --- url: /en/object/omit.md --- # omit \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-98.68%-FF8C00) Generate a new object or array from the input object or array with specified keys or indices removed. The returned value is a plain object or array, and the input will not be modified. > Added in v0.0.1 ### Usage ```typescript import { omit } from 'parsnip-kit' const obj = omit({ a: 1, b: 2, c: 3 }, ['b', 'c'] as const) // Omit<{ a: number; b: number; c: number; }, "b" | "c"> // { a: 1 } const arr = omit([1, 2, 3, 4], ['[1]', '3'] as const) // Omit // [1, 3] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends object` | Type of the object to be processed | | `R` | `extends readonly string[]` | Array type of field paths | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `T` | `false` | `undefined` | The object or array to process | | `keys` | `R` | `false` | `undefined` | The keys or array indices to delete | #### Returns | Type | | --- | | `Omit>>` | #### Reference [KeyOrIndex](../common/types#keyorindex) [ExtractUnion](../common/types#extractunion) --- --- url: /en/function/once.md --- # once \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) This is a function that accepts a function `func` and returns a new function that will be called only once. After the first call, it will return the cached result of the first call. > Added in v0.0.2 ### Usage ```typescript import { once } from 'parsnip-kit' const handler = (a) => { console.log('Function Called') return a } const onceFn = once(handler) onceFn(123) // Function Called // result is 123 onceFn(321) // result is 123 ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends (...args: any[]) => any` | Function type | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `func` | `T` | `false` | `undefined` | The function only called once | #### Returns | Type | | --- | | `(...args: Parameters) => ReturnType` | --- --- url: /en/array/orderSort.md --- # orderSort \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Sorts an array `arr` based on a specified order `order`. `getter` is a function that transforms elements of the array `arr` to keys that can be used for sorting, which can be a field path of [getByPath](../object/getByPath) or a function. If `getter` is not provided, the `orderSort` use the array `arr` element itself as the sorting key. Elements not in the `order` array maintain their original relative order and be placed at the end. > Added in v0.0.3 ### Usage ```ts import { orderSort } from 'parsnip-kit' const arr = [{ id: 0 }, { id: 2 }, { id: 1 }, { id: 3 }, { id: 4 }] const order = [1, 3, 2] const getter = (item: { id: number }) => item.id const sortedArr = orderSort(arr, order, getter) // [{ id: 1 }, { id: 3 }, { id: 2 }, { id: 0 }, { id: 4 }] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of elements of array to sort | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arr` | `T[]` | `false` | `undefined` | The array to be sorted | | `order` | `any[]` | `false` | `undefined` | The array specifying the desired order | | `getter` | `string \| ((item: T) => any)` | `true` | `undefined` | Transform the elements of the array into keys that can be used for sorting | #### Returns | Type | | --- | | `T[]` | --- --- url: /en/array/pairsToObject.md --- # pairsToObject \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input a object array `pairs`, and return a plain object composed of key-value pairs extracted from each sub-array. Optional parameters `getKey` and `getValue` can be provided to transform the array elements into keys and values. If not provided, the first element of each sub-array (index 0) will be used as the key, and the second element (index 1) will be used as the value. `getKey` and `getValue` can be field paths of [getByPath](../object/getByPath) or callback functions. > Added in v0.0.1 ### Usage ```ts import { pairsToObject } from 'parsnip-kit' const users = [['Alex', 16, 'vip'], ['Bob', 659, 'viewer'], ['Carter', 155, 'user'], ['Daniel', 825, 'user']] pairsToObject(users) // { Alex: 16, Bob: 659, Carter: 155, Daniel: 825 } pairsToObject(users, '[0]', '[2]') // { Alex: 'vip', Bob: 'viewer', Carter: 'user', Daniel: 'user' } pairsToObject(users, pair => pair[0], pair => `${pair[1]} replies`) // { Alex: '16 replies', Bob: '659 replies', Carter: '155 replies', Daniel: '825 replies' } ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends object` | Type of elements of array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `pairs` | `T[]` | `false` | `undefined` | The array of key-value object | | `getKey` | `string \| ((item: T, index: number, arr: T[]) => any)` | `true` | `undefined` | Extract keys form sub-arrays | | `getValue` | `string \| ((item: T, index: number, arr: T[]) => any)` | `true` | `undefined` | Extract values form sub-arrays | #### Returns | Type | | --- | | `ObjectLike` | #### Reference [ObjectLike](../common/types#objectlike) --- --- url: /en/string/parseTemplate.md --- # parseTemplate \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Parses a template string `template` and replaces placeholders with actual values based on a `parser`. The `parser` can be either a function or a non-function object. If the `parser` is a function, it will be called with the matched pattern string as an argument and should return the actual value for replacement. If the `parser` is a non-function object, [getByPath](../object/getByPath) will be used with the parser and the matched pattern string as arguments. The return value will replace the pattern. If the actual value for replacement is `undefined` or `null`, the pattern string will be preserved. Optional `options` can be used to set the start and end delimiters of the pattern string. > Added in v0.0.2 ### Usage ```ts import { parseTemplate } from 'parsnip-kit' const template0 = 'Hello, {name}! Your balance is {balance}.' parseTemplate(template0, { name: 'Alice', balance: '$100' }) // 'Hello, Alice! Your balance is $100.' parseTemplate(template0, (pattern: string) => data[pattern]) // 'Hello, Alice! Your balance is $100.' const template1 = 'Are you called {info.name}?' parseTemplate(template1, { info: { name: 'Administrator' } }) // 'Are you called Administrator?' const template2 = 'Dear User [username], thank you for registering on our website.' parseTemplate(template2, { username: 'John Titor' }, { start: '[', end: ']' }) // 'Dear User John Titor, thank you for registering on our website.' ``` ### API #### Type Parameter #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `template` | `string` | `false` | `undefined` | The template to replace | | `parser` | `ObjectLike \| ((pattern: string) => string \| undefined \| null)` | `false` | `undefined` | To replace placeholders with actual value | | `options` | `{ start?: string, end?: string }` | `true` | `{}` | To set the delimiters | | `options.start` | `string` | `true` | `'{'` | To set the start delimiters | | `options.end` | `string` | `true` | `'}'` | To set the end delimiters | #### Returns | Type | | --- | | `string` | #### Reference [ObjectLike](../common/types#objectlike) --- --- url: /en/string/pascalCase.md --- # pascalCase \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Convert the string to PascalCase (also known as UpperCamelCase). > Added in v0.0.1 ### Usage ```ts import { pascalCase } from 'parsnip-kit' pascalCase('HelloWorld') // 'HelloWorld' pascalCase('helloWorld') // 'HelloWorld' pascalCase('hello-world') // 'HelloWorld' pascalCase('hello_world') // 'HelloWorld' pascalCase('HELLO_WORLD') // 'HelloWorld' pascalCase('Hello World') // 'HelloWorld' pascalCase('-_HELLO World -_') // 'HelloWorld' ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | The string to be converted. | #### Returns | Type | | --- | | `string` | --- --- url: /en/number/percent.md --- # percent \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input a number `num` and a total `total` (default is 100), and return a formatted percentage string. An optional parameter `fixed` is available to control the number of decimal places, defaulting to 2. > Added in v0.0.1 ### Usage ```ts import { percent } from 'parsnip-kit' percent(50) // '50.00%' percent(25, 100) // '25.00%' percent(75, 200) // '37.50%' percent(75, 200, 0) // '38%' percent(0) // '0.00%' ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `num` | `number` | `false` | `undefined` | The number to calculate | | `total` | `number` | `true` | `100` | Total value | | `fixed` | `number` | `true` | `2` | Decimal places | #### Returns | Type | | --- | | `string` | --- --- url: /en/object/pick.md --- # pick \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Returns a new object or array containing the specified keys or indices extracted from the input object or array. The return value is a plain object or array and does not modify the original input. > Added in v0.0.1 ### Usage ```typescript import { pick } from 'parsnip-kit' const obj = { a: 1, b: 2, c: 3 } const keys0 = ['a', 'c'] as const const result0 = pick(obj, keys0) // Pick<{ a: number; b: number; c: number; }, "a" | "c"> // { a: 1, c: 3 } const arr = [1, 2, 3, 4] const keys1 = ['1', '[3]'] as const const result1 = pick(obj, keys1) // Pick // [2, 4] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends object` | Type of the object to be processed | | `R` | `extends readonly string[]` | Array type of field paths | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `T` | `false` | `undefined` | Type of the object to be processed | | `keys` | `R` | `false` | `undefined` | The keys or array indices to extract | #### Returns | Type | | --- | | `Pick> & keyof T>` | #### Reference [KeyOrIndex](../common/types#keyorindex) [ExtractUnion](../common/types#extractunion) --- --- url: /en/async/poll.md --- # poll \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-93.91%-FF8C00) Provide a function `func` that returns a `Promise` and a wait interval `wait`, and return a function that polls the asynchronous task at a fixed interval, supporting configurable retries and runtime control. Optional parameter options configures retry behavior; see [here](#polloptions). The function returns an object to control polling; see [here](#pollresult). > Added in v0.0.4 ### Usage ```ts import { poll } from 'parsnip-kit' const getList = () => { return fetch('https://example.url.test/list').then((response) => { response.json() // ... }) } const polled = poll(getList, 1000) const pollResult = polled() // ... // Stop polling pollResult.stop() ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of the `value` returned by the `Promise` of function `func` | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `func` | `(...args: any[]) => Promise` | `false` | `undefined` | The async function to poll | | `wait` | `number` | `false` | `undefined` | Interval in milliseconds between polls | | `options` | `PollOptions` | `true` | `undefined` | Polling configuration | | `options.maxRetries` | `number` | `true` | `3` | Max retry count on failure; Reset counter on success | | `options.maxCalls` | `number` | `true` | `Infinity` | Maximum number of calls of `func` | | `options.sequential` | `boolean` | `true` | `false` | Wait for previous run before next poll | | `options.leading` | `boolean` | `true` | `true` | Execute once immediately | | `options.onSuccess` | `(result: T, retries: number) => void` | `true` | `undefined` | Callback on success | | `options.onFailure` | `(error: any, retries: number) => void` | `true` | `undefined` | Callback on failure | #### Returns | Type | | --- | | `(...args: Parameters) => PollResult` | # PollOptions The type of `options` parameter of the `poll` function. > Added in v0.0.4 ### Source ```ts export interface PollOptions { maxRetries?: number sequential?: boolean leading?: boolean maxCalls?: number onSuccess?: (result: T, retries: number) => void onFailure?: (error: any, retries: number) => void } ``` # PollResult The return of the `poll` function. > Added in v0.0.4 ### Source ```ts export interface PollResult { stop: () => void start: () => void isRunning: () => boolean } ``` --- --- url: /en/common/types.md --- # PrimitiveType \[\[TOC]] The primitive types including `number`, `string`, `boolean`, `undefined`, `null`, `bigint`, and `symbol` > Added in v0.0.1 ### Source ```ts export type PrimitiveType = | undefined | null | number | string | boolean | bigint | symbol ``` # NumberString A string composed of numbers. > Added in v0.0.1 ### Source ```ts export type NumberString = `${number}` ``` # PseudoArray A pseudo-array, also known as an array-like object, an object had a numeric `length` property. > Added in v0.0.3 ### Source ```ts export type PseudoArray = object & { length: number } ``` # ObjectLike Non-function object. > Added in v0.0.1 ### Source ```ts export type ObjectLike = object & { call?: never; [x: PropertyKey]: any } ``` # ExtractUnion Extract a union type from a tuple. > Added in v0.0.1 ### Source ```ts export type ExtractUnion = { [K in keyof T]: T[K] }[number] ``` # KeyOrIndex Extracts a number from a string in the form of \[${number}] or ${number}. Otherwise, returns the original string. > Added in v0.0.1 ### Source ```ts export type KeyOrIndex = T extends | `[${infer D extends number}]` | `${infer D extends number}` ? D : T ``` # Tail Returns the last element of tuple type. > Added in v0.0.1 ### Source ```ts export type Tail = T extends readonly [ ...any[], infer L ] ? L : never ``` # Head Returns the first element of tuple type. > Added in v0.0.1 ### Source ```ts export type Head = T extends readonly [ infer L, ...any[] ] ? L : never ``` # Edge Retrieve the first or last element of tuple `T`, determined by type `D`. > Added in v0.0.1 ### Source ```ts export type Edge< T extends readonly any[], D = 'left' | 'right' > = D extends 'left' ? Head : Tail ``` # EdgeReverse Similar to `Edge`, but the effects of `'left'` and `'right'` for D are reversed. > Added in v0.0.1 ### Source ```ts export type EdgeReverse< T extends readonly any[], D = 'left' | 'right' > = D extends 'right' ? Head : Tail ``` # EmptyOrParameters Returns the parameter types of the function; if the input is not a function, returns the `never[]` type. > Added in v0.0.1 ### Source ```ts export type EmptyOrParameters = T extends (...args: any[]) => any ? Parameters : never[] ``` # EmptyOrReturnType Returns the return type of the function; if the input is not a function, returns the `void` type. > Added in v0.0.1 ### Source ```ts export type EmptyOrReturnType = T extends (...args: any[]) => any ? ReturnType : void ``` # WithFallback Either returns the result of type `T` or a fallback value `R` if the result is `null` or `undefined`. > Added in v0.0.2 ### Source ```ts export type WithFallback any, R> = ReturnType extends undefined | null ? R : ReturnType ``` # LiteralStringWithFallback This type provides a default string value `R` when string type `T` is too general (like string). It ensures type safety while allowing flexibility in scenarios such as configuration objects or optional parameters. > Added in v0.0.2 ### Source ```ts export type LiteralStringWithFallback = T & R extends never ? T : R ``` # MappedTypeByKeyOrIndex Generates plain objects or arrays based on input string/numeric index `T`, pointing to type `V`, with optionality controlled by type `O`. > Added in v0.0.2 ### Source ```ts export type MappedTypeByKeyOrIndex< T extends string, V, O extends boolean = false > = KeyOrIndex extends string ? O extends false ? { [P in T]: V } : { [P in T]?: V } : O extends false ? unknown[] & { [P in KeyOrIndex]: V } : unknown[] & { [P in KeyOrIndex]?: V } ``` # DeepMappedTypeByKeyOrIndex Recursively parses the field path `T` and creates nested plain objects or arrays. It can interpret nested path strings like `"data.[0].name"`, with the path's end field pointing to value `V`. `O` decides if the value is optional. It is very useful for creating complex nested types based on string templates. > Added in v0.0.2 ### Source ```ts export type DeepMappedTypeByKeyOrIndex< T extends string, V, O extends boolean = false > = T extends `[${infer Key extends number}][${infer Rest}` ? MappedTypeByKeyOrIndex<`${Key}`, DeepMappedTypeByKeyOrIndex<`[${Rest}`, V>> : T extends `${infer Key}[${infer Rest}` ? MappedTypeByKeyOrIndex< `${Key}`, DeepMappedTypeByKeyOrIndex<`[${Rest}`, V> > : T extends `[${infer Key extends number}].${infer Rest}` ? MappedTypeByKeyOrIndex<`${Key}`, DeepMappedTypeByKeyOrIndex> : T extends `${infer Key}.${infer Rest}` ? MappedTypeByKeyOrIndex<`${Key}`, DeepMappedTypeByKeyOrIndex> : MappedTypeByKeyOrIndex ``` # DataUnit `DataUnit` type represents different units of digital data. > Added in v0.0.2 ### Source ```ts export type DataUnit = | 'bit' | 'B' | 'KB' | 'MB' | 'GB' | 'TB' | 'PB' | 'EB' | 'ZB' | 'YB' ``` # Nullish `Nullish` type represents values that are either `null` or `undefined`. > Added in v0.0.4 ### Source ```ts export type Nullish = undefined | null ``` # SpreadSkipNullish Merge multiple types from left to right to form a new object type. Fields that are not `null` or `undefined` in the preceding objects will not be overwritten by `null` or `undefined` fields from the subsequent objects. > Added in v0.0.4 ### Source ```ts export type SpreadSkipNullish = { [K in keyof T | keyof U]: K extends keyof T ? K extends keyof U ? T[K] extends Nullish ? U[K] : U[K] extends Nullish ? T[K] : U[K] : T[K] : K extends keyof U ? U[K] : never } ``` # IsAny `IsAny` type is used to determine if a type is `any`. If `T` is `any`, the result is `true`; otherwise, it is `false`. > Added in v0.0.4 ### Source ```ts export type IsAny = 0 extends 1 & T ? true : false ``` # ArrayIndexes `ArrayIndexes` type is used to obtain the indexes of elements in an array (excluding general array properties such as `length`). > Added in v0.0.4 ### Source ```ts export type ArrayIndexes = Exclude< keyof T, keyof any[] | 'length' > & (string | number) ``` # FieldPathComponent `FieldPathComponent` type is used to generate field path components. If `Str` is a number or a numeric string, it generates a path like `'[1]'`; if it is a string, it generates a path like `'a'`. Depending on whether the subsequent type is a plain object or an array, it decides whether to append `'.'` at the end. > Added in v0.0.4 ### Source ```ts export type FieldPathComponent< Str extends string | number, Next extends 'object' | 'array' | void = void > = Str extends NumberString | number ? Next extends 'object' ? `[${Str & (string | number)}].` : `[${Str & (string | number)}]` : Next extends 'object' ? `${Str & string}.` : `${Str & string}` ``` # FlattenArrayObject `FlattenArrayObject` type is used to flatten objects within an array into a union type. It recursively processes each element in the array and continues to flatten based on the type of the element (object or array). > Added in v0.0.4 ### Source ```ts export type FlattenArrayObject< T extends Array, Prefix extends string = '' > = { [K in number | ArrayIndexes]: IsAny extends true ? { [P in `${Prefix}${FieldPathComponent}`]: T[K] } : T[K] extends never ? never : T[K] extends object ? T[K] extends Array ? FlattenArrayObject< T[K], `${Prefix}${FieldPathComponent}` > : FlattenObject}`> : { [P in `${Prefix}${FieldPathComponent}`]: T[K] } }[ArrayIndexes | number] ``` # FlattenObject `FlattenObject` type is used to flatten an object into a union type. It recursively processes each field of the object and continues to flatten based on the type of the field (object or array). > Added in v0.0.4 ### Source ```ts export type FlattenObject = { [K in keyof T & string]: IsAny extends true ? { [P in `${Prefix}${FieldPathComponent}`]: T[K] } : T[K] extends never ? never : T[K] extends object ? T[K] extends Array ? FlattenArrayObject< T[K], `${Prefix}${FieldPathComponent}` > : FlattenObject}`> : { [P in `${Prefix}${FieldPathComponent}`]: T[K] } }[keyof T & string] ``` # UnionToIntersection `UnionToIntersection` type is used to convert a union type to an intersection type. For example, `A | B` will be converted to `A & B`. > Added in v0.0.4 ### Source ```ts export type UnionToIntersection = ( U extends any ? (x: U) => any : never ) extends (x: infer R) => any ? R : never ``` # IntersectionToObject `IntersectionToObject` type is used to convert an intersection type to an object type. For example, `A & B` will be converted to `{ [K in keyof (A & B)]: (A & B)[K] }`. > Added in v0.0.4 ### Source ```ts export type IntersectionToObject = { [K in keyof UnionToIntersection]: UnionToIntersection[K] } ``` # FlattenNestObject `FlattenNestObject` type is used to flatten a nested object into a new object type. It first flattens the object into a union type using `FlattenObject`, then converts the union type to an intersection type using `UnionToIntersection`, and finally converts the intersection type to an object type using `IntersectionToObject`. > Added in v0.0.4 ### Source ```ts export type FlattenNestObject = IntersectionToObject< UnionToIntersection> > ``` --- --- url: /en/random/randomBoolean.md --- # randomBoolean \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Returns a random boolean value. > Added in v0.0.1 ### Usage ```ts import { randomBoolean } from 'parsnip-kit' randomBoolean() // false or true ``` ### API #### Returns | Type | | --- | | `boolean` | --- --- url: /en/random/randomFromArray.md --- # randomFromArray \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Returns a random element of the input array `arr`. > Added in v0.0.1 ### Usage ```ts import { randomFromArray } from 'parsnip-kit' randomFromArray([1, 2, 3, 4, 5]) // a element of input array. for example: 3 ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arr` | `any[]` | `false` | `undefined` | Array to be extracted randomly | #### Returns | Type | | --- | | `any` | --- --- url: /en/random/randomInt.md --- # randomInt \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Returns a random integer value in interval \[`start`, `end`). > Added in v0.0.3 ### Usage ```ts import { randomInt } from 'parsnip-kit' randomInt() // a random integer in [0, 10) randomInt(0, 1024) // a random integer in [0, 1024) ``` ### API #### Type Parameter #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `start` | `number` | `true` | `0` | The left boundary of the interval | | `end` | `number` | `true` | `10` | The right boundary of the interval | #### Returns | Type | | --- | | `number` | --- --- url: /en/random/randomNumber.md --- # randomNumber \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Returns a random number in interval \[`start`, `end`). > Added in v0.0.1 ### Usage ```ts import { randomNumber } from 'parsnip-kit' randomNumber() // a number in [0, 1) randomNumber(0, 100) // a number in [0, 100) ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `start` | `number` | `true` | `0` | The left boundary of the interval | | `end` | `number` | `true` | `1` | The right boundary of the interval | #### Returns | Type | | --- | | `number` | --- --- url: /en/random/randomString.md --- # randomString \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Generate a random string with a length of `length`. The `options` parameter specifies the character range. > Added in v0.0.2 ### Usage ```ts import { randomString } from 'parsnip-kit' randomString(10) // a string including uppercase letters, lowercase letters, numbers, for example 'Dij1mzPzyW' randomString(10, { number: false }) // a string only including letters, for example 'iYyyWSReNw' randomString(10, { uppercase: false, lowercase: false }) // a string only including numbers, for example '2398543147' randomString(10, { symbol: true }) // a string including uppercase letters, lowercase letters, numbers and symbols // for example 'gI(CThCMK%' randomString( 10, { uppercase: false, lowercase: false, number: false, customized: 'αβγδεζηθικλμνξοπρστυφχψω' } ) // a string only including lowercase Greek letters, for example 'γμχβωζπθοχ' ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `length` | `number` | `false` | `undefined` | Length of random string | | `options` | `RandomStringOptions` | `true` | `undefined` | String generation options | | `options.lowercase` | `boolean` | `true` | `true` | Whether to include lowercase letters | | `options.uppercase` | `boolean` | `true` | `true` | Whether to include uppercase letters | | `options.number` | `boolean` | `true` | `true` | Whether to include numbers | | `options.symbol` | `boolean` | `true` | `false` | Whether to include symbols: `'!@#$%^&*()_+-=[]{}|;:,.<>?'` | | `options.customized` | `string` | `true` | `undefined` | Included custom characters | #### Returns | Type | | --- | | `string` | # RandomStringOptions The `options` parameter of the `randomString` function. > Added in v0.0.2 ### Source ```ts export interface RandomStringOptions { lowercase?: boolean uppercase?: boolean number?: boolean symbol?: boolean customized?: string } ``` --- --- url: /en/number/range.md --- # range \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input the start value `start` and the end value `end`, and return the sequence starting from `start` with a step size of `step` in the interval \[`start`, `end`). Inspired by the syntax for generating arrays with equal steps in Python, as well as in Matlab, Rust, and others. > Added in v0.0.1 ### Usage ```ts import { range } from 'parsnip-kit' range(1, 10) // [1, 2, 3, 4, 5, 6, 7, 8, 9] range(1, 10, 2) // [1, 3, 5, 7, 9] range(10, 1, -2) // [10, 8, 6, 4, 2] range(1, 10, -2) // [] range(10, 1, 2) // [] range(10, 10, 2) // [] try { range(0, 1, 0) } catch (error) { console.log(error.message) // 'range step must be not equal 0.' } ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `start` | `number` | `false` | `undefined` | Start value | | `end` | `number` | `false` | `undefined` | End value | | `step` | `number` | `true` | `1` | Step size | #### Returns | Type | | --- | | `number[]` | --- --- url: /en/async/retry.md --- # retry \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Accepts a function `func` that returns a `Promise` and a `maxRetries` parameter (defaulting to 3), returning a function that retries the invocation of the given function upon failure. The optional parameter `options` sets up the retry configuration, details of which can be found [here](#retryoptions). > Added in v0.0.1 ### Usage ```ts import { retry } from 'parsnip-kit' let times = 0 const func = async (a: number, b: number) => { if (times < 3) { times++ throw new Error(`Error ${times}`) } return a + b } const retried = retry(func) retried(2, 3).then(res => { console.log(res) // { status: 'fulfilled', value: 5 } }) ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of the `value` returned by the `Promise` of function `func` | \[\[\[template poll ja T:関数`func`が返す`Promise`の`value`の型 ]]] #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `func` | `(...args: any[]) => Promise` | `false` | `undefined` | The asynchronous task function to be retried must return a `Promise` | | `maxRetries` | `number` | `true` | `3` | Maximum number of retries | | `options` | `RetryOptions` | `true` | `undefined` | Configuration options | | `options.delay` | `number` | `true` | `300` | Initial delay for retries (in milliseconds) | | `options.delayFactor` | `number` | `true` | `2` | Delay increment factor (the delay is multiplied by this value for each retry) | | `options.shouldRetry` | `(error: any, attempts: number) => boolean` | `true` | `undefined` | Callback function to determine whether to retry | | `options.onSuccess` | `(result: T, attempts: number) => any` | `true` | `undefined` | Callback function when the task is successful | | `options.onFailure` | `(result: any, attempts: number) => any` | `true` | `undefined` | Callback function when the task fails | #### Returns | Type | | --- | | `(...args: Parameters) => Promise>>` | # RetryOptions The `options` parameter of the `retry` function. > Added in v0.0.1 ### Source ```ts export interface RetryOptions { delay?: number delayFactor?: number shouldRetry?: (error: any, attempts: number) => boolean onSuccess?: (result: T, attempts: number) => void onFailure?: (error: any, attempts: number) => void } ``` --- --- url: /en/async/sequential.md --- # sequential \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) The `sequential` function is typically used when multiple asynchronous operations need to be executed in sequence. It takes an array of functions `functions` that return a `Promise` and executes them serially. Each function can accept the result of the previous function wrapped in a `PromiseSettledResult` type as a parameter. If an optional parameter `initialValue` is provided, it will be wrapped in a `PromiseSettledResult` of fulfilled status and passed to the first function. Otherwise, the first function will receive `undefined` as its parameter. > Added in v0.0.1 ### Usage ```ts import { sequential } from 'parsnip-kit' const functions = [ async (arg?: PromiseSettledResult) => { if (arg?.status === 'fulfilled') { return arg.value } else { throw new Error('test') } }, async (arg?: PromiseSettledResult) => { return arg?.status === 'fulfilled' ? arg.value + 1 : 0 }, async (arg?: PromiseSettledResult) => { return arg?.status === 'fulfilled' ? arg.value * 2 : 0 } ] sequential(functions).then(res => { console.log(res) }) // [ // { status: 'rejected', reason: new Error('test') }, // { status: 'fulfilled', value: 0 }, // { status: 'fulfilled', value: 0 } // ] sequential(functions, 0).then(res => { console.log(res) }) // [ // { status: 'fulfilled', value: 1 }, // { status: 'fulfilled', value: 2 }, // { status: 'fulfilled', value: 4 } // ] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | The `value` type returned by a function that returns a `Promise` | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `functions` | `((arg?: PromiseSettledResult>) => Promise)[]` | `false` | `undefined` | Array of functions that return `Promise` | | `initialValue` | `Awaited` | `true` | `undefined` | Initial Value | #### Returns | Type | | --- | | `Promise>[]>` | --- --- url: /en/object/setByPath.md --- # setByPath \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-97.50%-FF8C00) Input an object `obj` and a field path `path`, then traverse the object deeply according to the path to set the value `value`. > Added in v0.0.1 ### Usage ```ts import { setByPath } from 'parsnip-kit' const test0 = {} setByPath(test0, 'a', 1) // { a: 1 } const test1 = [] setByPath(test1, '[0]', 1) // [1] const test2 = {} setByPath(test2, '[0]', 1) // { 0: 1 } const test3 = {} setByPath(test3, 'b[2]', 2) // { b: [, , 2] } const test4 = { a: 1 } setByPath(test4, 'a[0]', 'test') // { a: ['test'] } const test5 = { a: 1 } setByPath(test5, 'b', 2) // { a: 1, b: 2 } ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `object` | `false` | `undefined` | Object to be set | | `path` | `string` | `false` | `undefined` | Field path | | `value` | `any` | `false` | `undefined` | Value to be set | #### Returns | Type | | --- | | `void` | --- --- url: /en/string/snakeCase.md --- # snakeCase \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Convert the string to snake\_case. > Added in v0.0.1 ### Usage ```ts import { snakeCase } from 'parsnip-kit' snakeCase('HelloWorld') // 'hello_world' snakeCase('helloWorld') // 'hello_world' snakeCase('hello-world') // 'hello_world' snakeCase('hello_world') // 'hello_world' snakeCase('HELLO_WORLD') // 'hello_world' snakeCase('Hello World') // 'hello_world' snakeCase('-_HELLO World -_') // 'hello_world' ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `string` | `false` | `undefined` | The string to be converted. | #### Returns | Type | | --- | | `string` | --- --- url: /en/array/sortIndex.md --- # sortIndex \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input an array `arr` and return an array representing the mapping from the indices of the original array to the indices of the sorted array. Note that the array `arr` itself will not be sorted. A custom comparator `comparator` can be provided; if not provided, the comparison logic will be the same as the native `sort`. > Added in v0.0.1 ### Usage ```ts import { sortIndex } from 'parsnip-kit' import { numberComparatorAsc } from 'parsnip-kit' import { stringComparatorAsc } from 'parsnip-kit' sort([1, 25, 4, 9, 16], (a, b) => a - b) // [1, 4, 9, 16, 25] sortIndex([1, 25, 4, 9, 16], (a, b) => a - b) // [0, 4, 1, 2, 3] sort([1, 25, 4, 9, 16]) // [1, 16, 25, 4, 9] sortIndex([1, 25, 4, 9, 16]) // [0, 2, 3, 4, 1] sort([1, 25, 4, 9, 16], numberComparatorAsc) // [1, 4, 9, 16, 25] sortIndex([1, 25, 4, 9, 16], numberComparatorAsc) // [0, 4, 1, 2, 3] sort(['a', 'b', 'A', 'B', 'c'], stringComparatorAsc) // ['a', 'A', 'b', 'B', 'c'] sortIndex(['a', 'b', 'A', 'B', 'c'], stringComparatorAsc) // [0, 2, 1, 3, 4] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of elements of array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arr` | `T[]` | `false` | `undefined` | Array to be sorted | | `comparator` | `(a: T, b: T) => number` | `true` | `undefined` | Comparator for sorting | #### Returns | Type | | --- | | `number[]` | --- --- url: /en/array/sortWithIndex.md --- # sortWithIndex \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input an array `arr`, sort `arr`, and return an array representing the mapping from the indices of the original array to the indices of the sorted array. The [sortIndex](./sortIndex) will be called internally. Note that the array `arr` itself will be sorted! A custom comparator `comparator` can be provided; if not provided, the comparison logic will be the same as the native `sort`. > Added in v0.0.2 ### Usage ```ts const arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] const indexMap = sortWithIndex(arr) console.log(arr) // [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] console.log(indexMap) // [1, 3, 6, 0, 9, 2, 4, 8, 10, 7, 5] const people = [ { name: 'John', age: 30 }, { name: 'Alice', age: 25 }, { name: 'Bob', age: 35 } ] const comparator = (a: { age: number }, b: { age: number }) => a.age - b.age const indexMap4People = sortWithIndex(people, comparator) console.log(people) // [ // { name: 'Alice', age: 25 }, // { name: 'John', age: 30 }, // { name: 'Bob', age: 35 } // ] console.log(indexMap4People) // [1, 0, 2] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of elements of array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arr` | `T[]` | `false` | `undefined` | Array to be sorted | | `comparator` | `(a: T, b: T) => number` | `true` | `undefined` | Comparator for sorting | #### Returns | Type | | --- | | `number[]` | --- --- url: /en/object/splitToArrays.md --- # splitToArrays \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input an object `obj`, and return an array of plain objects formed from each field of the `obj`, split by the object, or composed of the results returned by the optional parameter `createItem`. > Added in v0.0.1 ### Usage ```ts import { splitToArrays } from 'parsnip-kit' const obj = { Alex: 16, Bob: 659, Carter: 155, Daniel: 825 } splitToArrays(obj) // [{ Alex: 16 }, { Bob: 659 }, { Carter: 155 }, { Daniel: 825 }] splitToArrays(obj, (value, key) => [key, value]) // [['Alex', 16], ['Bob', 659], ['Carter', 155], ['Daniel', 825]] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends object` | Type of original object | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `object` | `false` | `undefined` | Original object | | `createItem` | `(value: T[string & keyof T], key: string, obj: T) => any` | `true` | `undefined` | To create element of array to be returned | #### Returns | Type | | --- | | `any[]` | --- --- url: /en/string/splitToKeys.md --- # splitToKeys \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Split the path string used for accessing values into individual keys. > Added in v0.0.1 ### Usage ```ts import { splitToKeys } from 'parsnip-kit' splitToKeys('a[0].b.c') // ['a', '0', 'b', 'c'] ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | The string to be converted. | #### Returns | Type | | --- | | `string[]` | --- --- url: /en/string/splitToWords.md --- # splitToWords \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Split the string used for naming into individual words. > Added in v0.0.1 ### Usage ```ts import { splitToWords } from 'parsnip-kit' splitToWords('-_i need 123XmlHTTPRequest -_') // ['i', 'need', '123', 'Xml', 'HTTP', 'Request'] ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | The string to be converted. | #### Returns | Type | | --- | | `string[]` | --- --- url: /en/common/constants.md --- # stringComparatorAsc \[\[TOC]] Comparator for sorting strings in lexicographical ascending order. > Added in v0.0.1 ### Source ```ts export const stringComparatorAsc = (a: string, b: string) => { return a.localeCompare(b) } ``` # stringComparatorDesc Comparator for sorting strings in lexicographical descending order. > Added in v0.0.1 ### Source ```ts export const stringComparatorDesc = (a: string, b: string) => { return b.localeCompare(a) } ``` # numberComparatorAsc Comparator for sorting numbers in ascending order. > Added in v0.0.1 ### Source ```ts export const numberComparatorAsc = (a: number, b: number) => { return a - b } ``` # numberComparatorDesc Comparator for sorting numbers in descending order. > Added in v0.0.1 ### Source ```ts export const numberComparatorDesc = (a: number, b: number) => { return b - a } ``` # codeUnitComparatorAsc Comparator for sorting strings in ascending order based on their code unit values. This is the default order used by `Array.prototype.sort` in Vanilla JavaScript. > Added in v0.0.2 ### Source ```ts export const codeUnitComparatorAsc = (a: string, b: string) => { if (a < b) return -1 if (b > a) return 1 return 0 } ``` # codeUnitComparatorDesc Comparator for sorting strings in descending order based on their code unit values. > Added in v0.0.2 ### Source ```ts export const codeUnitComparatorDesc = (a: string, b: string) => { if (a < b) return 1 if (b > a) return -1 return 0 } ``` --- --- url: /en/statistic/sum.md --- # sum \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) The `getter` is a field path of [getByPath](../object/getByPath) or a callback function, for extracting numerical values. > Added in v0.0.1 ### Usage ```ts import { sum } from 'parsnip-kit' sum([1, 2, 3, 4]) // 10 sum([{ value: 10 }, { value: 20 }], item => item.value) // 30 sum([{ score: 85 }, { score: 95 }], 'score') // 180 ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of input array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `data` | `T[]` | `false` | `undefined` | Input array | | `getter` | `string \| ((item: T, index: number, arr: T[]) => number)` | `true` | `undefined` | For extracting numerical values from array elements | #### Returns | Type | | --- | | `number` | --- --- url: /en/array/symmetricDifference.md --- # symmetricDifference \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input two arrays `arr1` and `arr2`, and return their symmetric difference. Symmetric difference refers to the elements that are in either of the two sets but not in their intersection. Accepts a `getter`, which can be a field path of [getByPath](../object/getByPath) or a callback function, used to provide an identifier to distinguish elements. > Added in v0.0.1 ### Usage ```ts import { symmetricDifference } from 'parsnip-kit' symmetricDifference([1, 2, 3, NaN], [1, 4, 8, NaN]) // [2, 3, 4, 8] symmetricDifference( [{ v: 1 }, { v: 2 }, { v: 3 }], [{ v: 1 }, { v: 4 }, { v: 8 }], 'v' ) // [{ v: 2 }, { v: 3 }, { v: 4 }, { v: 8 }] symmetricDifference( [{ v: [1] }, { v: [2] }, { v: [3] }], [{ v: [1] }, { v: [4] }, { v: [8] }], 'v[0]' ) // [{ v: [2] }, { v: [3] }, { v: [4] }, { v: [8] }] symmetricDifference([1.1, 2.4, 3.9, 4.16], [1, 2, 3, 4, 5, 6], Math.floor) // [5, 6] symmetricDifference([1.1, 2.4, 3.9, 4.16], [1, 2, 3, 4, 5, 6], (item: number, index: number, arr: number[]) => { return Math.floor(item) }) // [5, 6] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of elements of array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arr1` | `T[]` | `false` | `undefined` | Array for which the symmetric difference is to be calculated | | `arr2` | `T[]` | `false` | `undefined` | Array for which the symmetric difference is to be calculated | | `getter` | `string \| ((item: T, index: number, arr: T[]) => any)` | `true` | `undefined` | Provide an identifier to distinguish the elements | #### Returns | Type | | --- | | `T[]` | --- --- url: /en/number/thousandSeparator.md --- # thousandSeparator \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input a number `num` and return a string with thousand separators. > Added in v0.0.1 ### Usage ```ts import { thousandSeparator } from 'parsnip-kit' thousandSeparator(100) // '100' thousandSeparator(1000) // '1,000' thousandSeparator(10000) // '10,000' thousandSeparator(1234567) // '1,234,567' thousandSeparator(-1234567) // '-1,234,567' thousandSeparator(1234.567) // '1,234.567' thousandSeparator(1234.5678) // '1,234.567,8' ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `num` | `number` | `false` | `undefined` | The number to format | #### Returns | Type | | --- | | `string` | --- --- url: /en/function/throttle.md --- # throttle \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-93.32%-FF8C00) Throttle function used to limit the frequency of function calls. It ensures that the function is not called more than once within a specified time interval. > Added in v0.0.1 ### Usage ```typescript import { throttle } from 'parsnip-kit' const handler = () => console.log('Function called') // Basic throttle usage const throttled = throttle(handler, 300) throttled() // console.log is called after 300ms throttled() // Call is ignored due to throttle // Throttle with leading and trailing options const throttledWithOptions = throttle(handler, 300, { leading: true, trailing: true }) throttledWithOptions() // console.log is called immediately and again after 300ms if no other calls are made. ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends (...args: any[]) => any` | Type of function to throttle | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `func` | `T` | `false` | `undefined` | The function to throttle | | `wait` | `number` | `false` | `undefined` | The minimum allowed interval between two consecutive calls (in milliseconds). | | `options` | `object` | `true` | `undefined` | Optional parameter object | | `options.leading` | `boolean` | `true` | `false` | Whether to execute the function at the beginning of the wait interval | | `options.trailing` | `boolean` | `true` | `true` | Whether to execute the function at the end of the wait interval, if not already executed | #### Returns | Type | | --- | | `(...args: Parameters) => void` | --- --- url: /en/string/titleCase.md --- # titleCase \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Convert the string to Title Case, with words separated by spaces and each word capitalized. > Added in v0.0.1 ### Usage ```ts import { titleCase } from 'parsnip-kit' titleCase('HelloWorld') // 'Hello World' titleCase('helloWorld') // 'Hello World' titleCase('hello-world') // 'Hello World' titleCase('hello_world') // 'Hello World' titleCase('HELLO_WORLD') // 'Hello World' titleCase('Hello World') // 'Hello World' titleCase('-_HELLO World -_') // 'Hello World' ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | The string to be converted. | #### Returns | Type | | --- | | `string` | --- --- url: /en/array/union.md --- # union \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input two arrays `arr1` and `arr2`, and return their union. Accepts a `getter`, which can be a field path of [getByPath](../object/getByPath) or a callback function, used to provide an identifier to distinguish elements. > Added in v0.0.1 ### Usage ```ts import { union } from 'parsnip-kit' union([1, 2, 3, NaN], [1, 4, 8, NaN]) // [1, 2, 3, NaN, 4, 8] union( [{ v: 1 }, { v: 2 }, { v: 3 }], [{ v: 1 }, { v: 4 }, { v: 8 }], 'v' ) // [{ v: 1 }, { v: 2 }, { v: 3 }, { v: 4 }, { v: 8 }] union( [{ v: [1] }, { v: [2] }, { v: [3] }], [{ v: [1] }, { v: [4] }, { v: [8] }], 'v[0]' ) // [{ v: [1] }, { v: [2] }, { v: [3] }, { v: [4] }, { v: [8] }] union([1.1, 2.4, 3.9, 4.16], [1, 2, 3, 4, 5, 6], Math.floor) // [1.1, 2.4, 3.9, 4.16, 5, 6] union([1.1, 2.4, 3.9, 4.16], [1, 2, 3, 4, 5, 6], (item: number, index: number, arr: number[]) => { return Math.floor(item) }) // [1.1, 2.4, 3.9, 4.16, 5, 6] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of elements of array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arr1` | `T[]` | `false` | `undefined` | Array for computing the union | | `arr2` | `T[]` | `false` | `undefined` | Array for computing the union | | `getter` | `string \| ((item: T, index: number, arr: T[]) => any)` | `true` | `undefined` | Provide an identifier to distinguish the elements | #### Returns | Type | | --- | | `T[]` | --- --- url: /en/array/unique.md --- # unique \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input an array `arr` and return the elements that appear only once. Accepts a `getter`, which can be a field path of [getByPath](../object/getByPath) or a callback function, used to provide an identifier to distinguish elements. > Added in v0.0.1 ### Usage ```ts import { unique } from 'parsnip-kit' unique([1, 2, 3, NaN, 1, 4, 8, NaN]) // [1, 2, 3, NaN, 4, 8] unique( [{ v: 1 }, { v: 2 }, { v: 3 }, { v: 1 }, { v: 4 }, { v: 8 }], 'v' ) // [{ v: 1 }, { v: 2 }, { v: 3 }, { v: 4 }, { v: 8 }] unique( [{ v: [1] }, { v: [2] }, { v: [3] }, { v: [1] }, { v: [4] }, { v: [8] }], 'v[0]' ) // [{ v: [1] }, { v: [2] }, { v: [3] }, { v: [4] }, { v: [8] }] unique([1.1, 2.4, 3.9, 4.16], [1, 2, 3, 4, 5, 6], Math.floor) // [1.1, 2.4, 3.9, 4.16, 5, 6] unique([1.1, 2.4, 3.9, 4.16], [1, 2, 3, 4, 5, 6], (item: number, index: number, arr: number[]) => { return Math.floor(item) }) // [1.1, 2.4, 3.9, 4.16, 5, 6] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of elements of array | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arr` | `T[]` | `false` | `undefined` | Array that needs to be deduplicated | | `getter` | `string \| ((item: T, index: number, arr: T[]) => any)` | `true` | `undefined` | Provide an identifier to distinguish the elements | #### Returns | Type | | --- | | `T[]` | --- --- url: /en/object/unzipToArrays.md --- # unzipToArrays \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input an object `obj`, and return two arrays: one containing its keys and the other containing its values. > Added in v0.0.1 ### Usage ```ts import { unzipToArrays } from 'parsnip-kit' const obj = { Alex: 16, Bob: 659, Carter: 155, Daniel: 825 } unzipToArrays(obj) // [['Alex', 'Bob', 'Carter', 'Daniel'], [16, 659, 155, 825]] unzipToArrays(obj, (_, key) => key.toUpperCase(), (value) => value + '') // [['ALEX', 'BOB', 'CARTER', 'DANIEL'], ['16', '659', '155', '825']] ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends object` | Type of original object | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `T` | `false` | `undefined` | Original object | | `createKey` | `(value: T[string & keyof T], key: string, obj: T) => any` | `true` | `undefined` | To create element of array of keys to be returned | | `createValue` | `(value: T[string & keyof T], key: string, obj: T) => any` | `true` | `undefined` | To create element of array of values to be returned | #### Returns | Type | | --- | | `[string[], any[]]` | --- --- url: /en/string/upperSnakeCase.md --- # upperSnakeCase \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Convert the string to UPPERCASE\_SNAKE\_CASE. > Added in v0.0.1 ### Usage ```ts import { upperSnakeCase } from 'parsnip-kit' upperSnakeCase('HelloWorld') // 'HELLO_WORLD' upperSnakeCase('helloWorld') // 'HELLO_WORLD' upperSnakeCase('hello-world') // 'HELLO_WORLD' upperSnakeCase('hello_world') // 'HELLO_WORLD' upperSnakeCase('HELLO_WORLD') // 'HELLO_WORLD' upperSnakeCase('Hello World') // 'HELLO_WORLD' upperSnakeCase('-_HELLO World -_') // 'HELLO_WORLD' ``` ### API #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `any` | `false` | `undefined` | The string to be converted. | #### Returns | Type | | --- | | `string` | --- --- url: /en/function/withFallback.md --- # withFallback \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) This function returns a new function that either returns the result of `func` or a fallback value `defaultValue` if the result is `null` or `undefined`. > Added in v0.0.2 ### Usage ```ts import { withFallback } from 'parsnip-kit' const func = (a: number) => (a === 0 ? null : a) const funcWithDefault = withFallback(func, -1) funcWithDefault(1) // 1 funcWithDefault(0) // -1 ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | `extends (...args: any[]) => any` | Function type | | `R` | ` ` | Type of default value | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `func` | `T` | `false` | `undefined` | The function with default return value | | `defaultValue` | `R` | `false` | `undefined` | Default value | #### Returns | Type | | --- | | `WithFallback` | #### Reference [WithFallback](../common/types#withfallback) --- --- url: /en/array/zipToObject.md --- # zipToObject \[\[TOC]] ![Static Badge](https://img.shields.io/badge/Coverage-100.00%-FF8C00) Input two arrays `keys` and `values`, and return a plain object where elements of `keys` serve as keys and elements of `values` serve as values. Optional parameters `getKey` and `getValue` can be provided to transform elements of the objects into keys and values, respectively. These can be field paths of [getByPath](../object/getByPath) or callback functions. > Added in v0.0.1 ### Usage ```ts import { zipToObject } from 'parsnip-kit' zipToObject(['id', 'name', 'skill'], [1, 'Alex', ['Javascript']]) // { id: 1, name: 'Alex', skill: ['Javascript'] } const users = [{ id: 0, user: 'IAmBot' }, { id: 2, user: 'Alice' }, { id: 5, user: 'Tom' }] const record = [ { system: 'Linux', count: 99999, userId: 0 }, { system: 'Mac OS', count: 10, userId: 2 }, { system: 'Window', count: 2, userId: 5 }, ] zipToObject( users, record, 'user', 'count' ) // { IAmBot: 99999, Alice: 10, Tom: 2 } zipToObject( users, record, item => item.user, item => item.count ) // { IAmBot: 99999, Alice: 10, Tom: 2 } ``` ### API #### Type Parameter | Arg | Type | Description | | --- | --- | --- | | `T` | ` ` | Type of elements of array serving as keys | | `U` | ` ` | Type of elements of array serving as values | #### Arguments | Arg | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | `keys` | `T[]` | `false` | `undefined` | The array serving as keys | | `values` | `U[]` | `false` | `undefined` | The array serving as values | | `getKey` | `string \| ((item: T, index: number, arr: T[]) => any)` | `true` | `undefined` | Transform array elements into keys | | `getValue` | `string \| ((item: U, index: number, arr: U[]) => any)` | `true` | `undefined` | Transform array elements into values | #### Returns | Type | | --- | | `ObjectLike` | #### Reference [ObjectLike](../common/types#objectlike)