@augment-vir/common
Advanced tools
Comparing version 30.0.0 to 30.0.1
import type { ArrayElement } from '@augment-vir/core'; | ||
import { Writable } from '../type/writable.js'; | ||
/** Preserves tuple types. */ | ||
/** | ||
* Performs | ||
* [`[].map()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map) | ||
* on an array but transfers the input tuple's size to the output type. | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {typedMap} from '@augment-vir/common'; | ||
* | ||
* const result = await typedMap( | ||
* [ | ||
* 1, | ||
* 2, | ||
* 3, | ||
* 4, | ||
* 5, | ||
* ], | ||
* (value) => { | ||
* return value + 1; | ||
* }, | ||
* ); | ||
* ``` | ||
* | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function typedMap<const ArrayGeneric extends ReadonlyArray<any>, const OutputType>(arrayToMap: ArrayGeneric, mapCallback: (value: ArrayElement<NoInfer<ArrayGeneric>>, index: number, array: NoInfer<ArrayGeneric>) => OutputType): Writable<{ | ||
[Index in keyof ArrayGeneric]: OutputType; | ||
}>; |
@@ -1,4 +0,32 @@ | ||
/** Preserves tuple types. */ | ||
/** | ||
* Performs | ||
* [`[].map()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map) | ||
* on an array but transfers the input tuple's size to the output type. | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {typedMap} from '@augment-vir/common'; | ||
* | ||
* const result = await typedMap( | ||
* [ | ||
* 1, | ||
* 2, | ||
* 3, | ||
* 4, | ||
* 5, | ||
* ], | ||
* (value) => { | ||
* return value + 1; | ||
* }, | ||
* ); | ||
* ``` | ||
* | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function typedMap(arrayToMap, mapCallback) { | ||
return arrayToMap.map(mapCallback); | ||
} |
/** | ||
* Polyfill for `Object.groupBy`: | ||
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/groupBy | ||
* https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/groupBy | ||
* | ||
* @category Object:Common | ||
* @category Array | ||
* @category Object | ||
* @example | ||
* | ||
* ```ts | ||
* import {arrayToObject} from '@augment-vir/common'; | ||
* | ||
* const result = arrayToObject( | ||
* [ | ||
* 'a', | ||
* 'b', | ||
* ], | ||
* (value) => `key-${value}`, | ||
* ); | ||
* // result is `{key-a: ['a'], key-b: ['b']}` | ||
* ``` | ||
*/ | ||
export declare function groupArrayBy<ElementType, NewKey extends PropertyKey>(inputArray: ReadonlyArray<ElementType>, callback: (value: ElementType, index: number, originalArray: ReadonlyArray<ElementType>) => NewKey): Partial<Record<NewKey, ElementType[]>>; | ||
/** | ||
* Like `groupArrayBy` but maps array entries to a single key. Meaning, the resulting object does | ||
* not have an array of elements (unless the original array itself contains arrays). | ||
* Similar to {@link groupArrayBy} but maps array entries to a single key and requires `key` _and_ | ||
* `value` outputs from the callback. The resulting object does not have an array of elements | ||
* (unless the original array itself contains arrays). | ||
* | ||
* @category Object:Common | ||
* @category Array | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {arrayToObject} from '@augment-vir/common'; | ||
* | ||
* const result = arrayToObject( | ||
* [ | ||
* 'a', | ||
* 'b', | ||
* ], | ||
* (value) => { | ||
* return {key: `key-${value}`, value}; | ||
* }, | ||
* ); | ||
* // result is `{key-a: 'a', key-b: 'b'}` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -14,0 +50,0 @@ export declare function arrayToObject<ElementType, NewKey extends PropertyKey, NewValue>(inputArray: ReadonlyArray<ElementType>, callback: (value: ElementType, index: number, originalArray: ReadonlyArray<ElementType>) => { |
@@ -5,5 +5,20 @@ import { getOrSet } from '../object/get-or-set.js'; | ||
* Polyfill for `Object.groupBy`: | ||
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/groupBy | ||
* https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/groupBy | ||
* | ||
* @category Object:Common | ||
* @category Array | ||
* @category Object | ||
* @example | ||
* | ||
* ```ts | ||
* import {arrayToObject} from '@augment-vir/common'; | ||
* | ||
* const result = arrayToObject( | ||
* [ | ||
* 'a', | ||
* 'b', | ||
* ], | ||
* (value) => `key-${value}`, | ||
* ); | ||
* // result is `{key-a: ['a'], key-b: ['b']}` | ||
* ``` | ||
*/ | ||
@@ -19,6 +34,27 @@ export function groupArrayBy(inputArray, callback) { | ||
/** | ||
* Like `groupArrayBy` but maps array entries to a single key. Meaning, the resulting object does | ||
* not have an array of elements (unless the original array itself contains arrays). | ||
* Similar to {@link groupArrayBy} but maps array entries to a single key and requires `key` _and_ | ||
* `value` outputs from the callback. The resulting object does not have an array of elements | ||
* (unless the original array itself contains arrays). | ||
* | ||
* @category Object:Common | ||
* @category Array | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {arrayToObject} from '@augment-vir/common'; | ||
* | ||
* const result = arrayToObject( | ||
* [ | ||
* 'a', | ||
* 'b', | ||
* ], | ||
* (value) => { | ||
* return {key: `key-${value}`, value}; | ||
* }, | ||
* ); | ||
* // result is `{key-a: 'a', key-b: 'b'}` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -25,0 +61,0 @@ export function arrayToObject(inputArray, callback) { |
@@ -0,1 +1,30 @@ | ||
/** | ||
* Performs | ||
* [`[].filter()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) | ||
* on an array but supports an async callback. | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {awaitedFilter} from '@augment-vir/common'; | ||
* | ||
* const result = await awaitedFilter( | ||
* [ | ||
* 1, | ||
* 2, | ||
* 3, | ||
* 4, | ||
* 5, | ||
* ], | ||
* async (value) => { | ||
* return await Promise.resolve(value > 2); | ||
* }, | ||
* ); | ||
* ``` | ||
* | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function awaitedFilter<OriginalGeneric>(arrayInput: ReadonlyArray<OriginalGeneric>, filterCallback: (arrayElement: OriginalGeneric, index: number, wholeArray: ReadonlyArray<OriginalGeneric>) => Promise<unknown>, options?: { | ||
@@ -2,0 +31,0 @@ /** |
import { awaitedBlockingMap } from './awaited-map.js'; | ||
/** | ||
* Performs | ||
* [`[].filter()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) | ||
* on an array but supports an async callback. | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {awaitedFilter} from '@augment-vir/common'; | ||
* | ||
* const result = await awaitedFilter( | ||
* [ | ||
* 1, | ||
* 2, | ||
* 3, | ||
* 4, | ||
* 5, | ||
* ], | ||
* async (value) => { | ||
* return await Promise.resolve(value > 2); | ||
* }, | ||
* ); | ||
* ``` | ||
* | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export async function awaitedFilter(arrayInput, filterCallback, options) { | ||
@@ -3,0 +32,0 @@ const callbackResults = options?.blocking |
/** | ||
* Acts like calling Array.prototype.forEach in that all elements are executed upon in order, and | ||
* each execution is blocking. Meaning, the callback won't be called on element 2 until the callback | ||
* has finished its call on element 1. | ||
* Performs | ||
* [`[].forEach()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) | ||
* on an array but supports an async callback. The async callback is blocking. Meaning, | ||
* `awaitedForEach` will wait for a callback on array element 1 to finish before moving on to array | ||
* element 2. | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {awaitedForEach} from '@augment-vir/common'; | ||
* | ||
* await awaitedForEach( | ||
* [ | ||
* 1, | ||
* 2, | ||
* 3, | ||
* 4, | ||
* 5, | ||
* ], | ||
* async (value) => { | ||
* await Promise.resolve(value); | ||
* }, | ||
* ); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function awaitedForEach<OriginalGeneric>(input: ReadonlyArray<OriginalGeneric>, callback: (arrayElement: OriginalGeneric, index: number, wholeArray: ReadonlyArray<OriginalGeneric>) => void | PromiseLike<void>): Promise<void>; |
import { awaitedBlockingMap } from './awaited-map.js'; | ||
/** | ||
* Acts like calling Array.prototype.forEach in that all elements are executed upon in order, and | ||
* each execution is blocking. Meaning, the callback won't be called on element 2 until the callback | ||
* has finished its call on element 1. | ||
* Performs | ||
* [`[].forEach()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) | ||
* on an array but supports an async callback. The async callback is blocking. Meaning, | ||
* `awaitedForEach` will wait for a callback on array element 1 to finish before moving on to array | ||
* element 2. | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {awaitedForEach} from '@augment-vir/common'; | ||
* | ||
* await awaitedForEach( | ||
* [ | ||
* 1, | ||
* 2, | ||
* 3, | ||
* 4, | ||
* 5, | ||
* ], | ||
* async (value) => { | ||
* await Promise.resolve(value); | ||
* }, | ||
* ); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -7,0 +32,0 @@ export async function awaitedForEach(input, callback) { |
@@ -0,1 +1,33 @@ | ||
/** | ||
* Performs | ||
* [`[].map()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map) | ||
* on an array but supports an async callback. The async callback is blocking. Meaning, | ||
* `awaitedForEach` will wait for a callback on array element 1 to finish before moving on to array | ||
* element 2. Compare to `await Promise.all([].map(async () => {}))` which is _not_ blocking (all | ||
* callbacks are called in parallel). | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {awaitedBlockingMap} from '@augment-vir/common'; | ||
* | ||
* const result = await awaitedBlockingMap( | ||
* [ | ||
* 1, | ||
* 2, | ||
* 3, | ||
* 4, | ||
* 5, | ||
* ], | ||
* async (value) => { | ||
* return await Promise.resolve(value); | ||
* }, | ||
* ); | ||
* ``` | ||
* | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function awaitedBlockingMap<OriginalGeneric, MappedGeneric>(input: ReadonlyArray<OriginalGeneric>, callback: (arrayElement: OriginalGeneric, index: number, wholeArray: ReadonlyArray<OriginalGeneric>) => MappedGeneric | PromiseLike<MappedGeneric>): Promise<Awaited<MappedGeneric>[]>; |
@@ -0,1 +1,33 @@ | ||
/** | ||
* Performs | ||
* [`[].map()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map) | ||
* on an array but supports an async callback. The async callback is blocking. Meaning, | ||
* `awaitedForEach` will wait for a callback on array element 1 to finish before moving on to array | ||
* element 2. Compare to `await Promise.all([].map(async () => {}))` which is _not_ blocking (all | ||
* callbacks are called in parallel). | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {awaitedBlockingMap} from '@augment-vir/common'; | ||
* | ||
* const result = await awaitedBlockingMap( | ||
* [ | ||
* 1, | ||
* 2, | ||
* 3, | ||
* 4, | ||
* 5, | ||
* ], | ||
* async (value) => { | ||
* return await Promise.resolve(value); | ||
* }, | ||
* ); | ||
* ``` | ||
* | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export async function awaitedBlockingMap(input, callback) { | ||
@@ -2,0 +34,0 @@ return await input.reduce(async (accumPromise, currentElement, index, wholeArray) => { |
@@ -0,3 +1,32 @@ | ||
/** | ||
* Removes all given indexes from the given array. | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {filterOutIndexes} from '@augment-vir/common'; | ||
* | ||
* const result = filterOutIndexes( | ||
* [ | ||
* 'a', | ||
* 'b', | ||
* '', | ||
* ], | ||
* [ | ||
* 0, | ||
* 2, | ||
* ], | ||
* ); | ||
* // result is `['b']` | ||
* ``` | ||
* | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function filterOutIndexes<T>(array: ReadonlyArray<T>, indexes: ReadonlyArray<number>): T[]; | ||
/** Performs `filterMap` with a type guard filter. */ | ||
export declare function filterMap<ElementType, MappedEntry, TypeGuarded extends MappedEntry>(inputArray: ReadonlyArray<ElementType>, mapCallback: (entry: ElementType, index: number, originalArray: ReadonlyArray<ElementType>) => MappedEntry, filterCallback: (mappedOutput: MappedEntry, originalEntry: ElementType, index: number, originalArray: ReadonlyArray<ElementType>) => mappedOutput is TypeGuarded): TypeGuarded[]; | ||
/** Performs a regular `filterMap`. */ | ||
export declare function filterMap<ElementType, MappedEntry>(inputArray: ReadonlyArray<ElementType>, mapCallback: (entry: ElementType, index: number, originalArray: ReadonlyArray<ElementType>) => MappedEntry, filterCallback: (mappedOutput: MappedEntry, originalEntry: ElementType, index: number, originalArray: ReadonlyArray<ElementType>) => boolean): MappedEntry[]; |
@@ -0,4 +1,65 @@ | ||
/** | ||
* Removes all given indexes from the given array. | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {filterOutIndexes} from '@augment-vir/common'; | ||
* | ||
* const result = filterOutIndexes( | ||
* [ | ||
* 'a', | ||
* 'b', | ||
* '', | ||
* ], | ||
* [ | ||
* 0, | ||
* 2, | ||
* ], | ||
* ); | ||
* // result is `['b']` | ||
* ``` | ||
* | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function filterOutIndexes(array, indexes) { | ||
return array.filter((_, index) => !indexes.includes(index)); | ||
} | ||
/** | ||
* Performs | ||
* [`[].map()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map) | ||
* and | ||
* [`[].filter()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) | ||
* (in that order) on an array with a single iteration. | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {filterMap} from '@augment-vir/common'; | ||
* | ||
* const result = filterMap( | ||
* [ | ||
* 'a', | ||
* 'b', | ||
* '', | ||
* ], | ||
* // map callback | ||
* (value) => { | ||
* return `value-${value}`; | ||
* }, | ||
* // filter callback | ||
* (mappedValue, originalValue) => { | ||
* return !!originalValue; | ||
* }, | ||
* ); | ||
* // result is `['value-a', 'value-b']` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function filterMap(inputArray, mapCallback, filterCallback) { | ||
@@ -5,0 +66,0 @@ return inputArray.reduce((accum, entry, index, originalArray) => { |
@@ -1,1 +0,60 @@ | ||
export declare function removeDuplicates<Entry, UniqueId>(originalArray: ReadonlyArray<Readonly<Entry>>, calculateUniqueIdCallback: (entry: Readonly<Entry>) => UniqueId): Readonly<Entry>[]; | ||
/** | ||
* Removes duplicates from an array. Optionally provide a callback for calculating a unique id for | ||
* entries. | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @example No callback | ||
* | ||
* ```ts | ||
* import {removeDuplicates} from '@augment-vir/common'; | ||
* | ||
* const result = removeDuplicates([ | ||
* 1, | ||
* 1, | ||
* 1, | ||
* 1, | ||
* 1, | ||
* 2, | ||
* 4, | ||
* ]); | ||
* // result is `[1, 2, 4]` | ||
* | ||
* const exampleEntry = {id: 5}; | ||
* | ||
* const result2 = removeDuplicates([ | ||
* {id: 1}, | ||
* // this entry will not get filtered out because it's a new object reference | ||
* {id: 1}, | ||
* exampleEntry, | ||
* // this `exampleEntry` will get filtered out because it's the same reference as the one above | ||
* exampleEntry, | ||
* {id: 4}, | ||
* ]); | ||
* // result2 is `[{id: 1}, {id: 1}, exampleEntry, {id: 4}]` | ||
* ``` | ||
* | ||
* @example With callback | ||
* | ||
* ```ts | ||
* import {removeDuplicates} from '@augment-vir/common'; | ||
* | ||
* const exampleEntry = {id: 5}; | ||
* | ||
* const result2 = removeDuplicates( | ||
* [ | ||
* {id: 1}, | ||
* {id: 1}, | ||
* exampleEntry, | ||
* exampleEntry, | ||
* {id: 4}, | ||
* ], | ||
* (entry) => entry.id, | ||
* ); | ||
* // result2 is `[{id: 1}, exampleEntry, {id: 4}]` | ||
* ``` | ||
* | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function removeDuplicates<const Entry>(originalArray: ReadonlyArray<Entry>, calculateUniqueId?: (entry: Readonly<Entry>) => unknown): Entry[]; |
@@ -1,5 +0,64 @@ | ||
export function removeDuplicates(originalArray, calculateUniqueIdCallback) { | ||
/** | ||
* Removes duplicates from an array. Optionally provide a callback for calculating a unique id for | ||
* entries. | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @example No callback | ||
* | ||
* ```ts | ||
* import {removeDuplicates} from '@augment-vir/common'; | ||
* | ||
* const result = removeDuplicates([ | ||
* 1, | ||
* 1, | ||
* 1, | ||
* 1, | ||
* 1, | ||
* 2, | ||
* 4, | ||
* ]); | ||
* // result is `[1, 2, 4]` | ||
* | ||
* const exampleEntry = {id: 5}; | ||
* | ||
* const result2 = removeDuplicates([ | ||
* {id: 1}, | ||
* // this entry will not get filtered out because it's a new object reference | ||
* {id: 1}, | ||
* exampleEntry, | ||
* // this `exampleEntry` will get filtered out because it's the same reference as the one above | ||
* exampleEntry, | ||
* {id: 4}, | ||
* ]); | ||
* // result2 is `[{id: 1}, {id: 1}, exampleEntry, {id: 4}]` | ||
* ``` | ||
* | ||
* @example With callback | ||
* | ||
* ```ts | ||
* import {removeDuplicates} from '@augment-vir/common'; | ||
* | ||
* const exampleEntry = {id: 5}; | ||
* | ||
* const result2 = removeDuplicates( | ||
* [ | ||
* {id: 1}, | ||
* {id: 1}, | ||
* exampleEntry, | ||
* exampleEntry, | ||
* {id: 4}, | ||
* ], | ||
* (entry) => entry.id, | ||
* ); | ||
* // result2 is `[{id: 1}, exampleEntry, {id: 4}]` | ||
* ``` | ||
* | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function removeDuplicates(originalArray, calculateUniqueId = (entry) => entry) { | ||
const grouped = new Map(); | ||
return originalArray.filter((entry) => { | ||
const uniqueId = calculateUniqueIdCallback(entry); | ||
const uniqueId = calculateUniqueId(entry); | ||
if (grouped.get(uniqueId)) { | ||
@@ -6,0 +65,0 @@ return false; |
@@ -0,1 +1,23 @@ | ||
/** | ||
* Repeats an array. Constructs a new array with the entries from the original repeated the given | ||
* number of times. | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {repeatArray} from '@augment-vir/common'; | ||
* | ||
* const result = repeatArray(3, [ | ||
* 'a', | ||
* 'b', | ||
* 'c', | ||
* ]); | ||
* // result is `['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']` | ||
* ``` | ||
* | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function repeatArray<T>(repeatCount: number, array: T[]): T[]; |
@@ -0,3 +1,25 @@ | ||
/** | ||
* Repeats an array. Constructs a new array with the entries from the original repeated the given | ||
* number of times. | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {repeatArray} from '@augment-vir/common'; | ||
* | ||
* const result = repeatArray(3, [ | ||
* 'a', | ||
* 'b', | ||
* 'c', | ||
* ]); | ||
* // result is `['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']` | ||
* ``` | ||
* | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function repeatArray(repeatCount, array) { | ||
return Array.from({ length: repeatCount }, () => [...array]).flat(); | ||
} |
@@ -1,2 +0,9 @@ | ||
/** Creates a new array which is a shuffled version of the input array. */ | ||
/** | ||
* Shuffles the positions of an array's entries (without mutating the array). | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function shuffleArray<ArrayElementType>(input: ReadonlyArray<ArrayElementType>): Array<ArrayElementType>; |
import { randomString } from '../random/random-string.js'; | ||
/** Creates a new array which is a shuffled version of the input array. */ | ||
/** | ||
* Shuffles the positions of an array's entries (without mutating the array). | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function shuffleArray(input) { | ||
@@ -4,0 +11,0 @@ return input |
@@ -0,1 +1,9 @@ | ||
/** | ||
* Trims all entries in an array. | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function trimArrayStrings(input: ReadonlyArray<string>): string[]; |
@@ -0,3 +1,11 @@ | ||
/** | ||
* Trims all entries in an array. | ||
* | ||
* @category Array | ||
* @category Package : @augment-vir/common | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function trimArrayStrings(input) { | ||
return input.map((line) => line.trim()).filter((line) => line !== ''); | ||
} |
import type { EnumBaseType } from '@augment-vir/core'; | ||
/** | ||
* Filters the input array to all valid values from the given enum. | ||
* | ||
* @category Array | ||
* @category Enum | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* enum MyEnum { | ||
* A = 'a', | ||
* B = 'b', | ||
* } | ||
* | ||
* const result = filterToEnumValues( | ||
* [ | ||
* 1, | ||
* 2, | ||
* 3, | ||
* 'a', | ||
* 'b', | ||
* MyEnum.A, | ||
* ], | ||
* MyEnum, | ||
* ); // result is `[MyEnum.A, MyEnum.B, MyEnum.A]` | ||
* ``` | ||
* | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function filterToEnumValues<const T extends EnumBaseType>(inputs: ReadonlyArray<unknown>, checkEnum: T): T[keyof T][]; |
import { check } from '@augment-vir/assert'; | ||
/** | ||
* Filters the input array to all valid values from the given enum. | ||
* | ||
* @category Array | ||
* @category Enum | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* enum MyEnum { | ||
* A = 'a', | ||
* B = 'b', | ||
* } | ||
* | ||
* const result = filterToEnumValues( | ||
* [ | ||
* 1, | ||
* 2, | ||
* 3, | ||
* 'a', | ||
* 'b', | ||
* MyEnum.A, | ||
* ], | ||
* MyEnum, | ||
* ); // result is `[MyEnum.A, MyEnum.B, MyEnum.A]` | ||
* ``` | ||
* | ||
* @returns A new array (does not mutate). | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function filterToEnumValues(inputs, checkEnum) { | ||
return inputs.filter((input) => check.isEnumValue(input, checkEnum)); | ||
} |
@@ -1,3 +0,24 @@ | ||
import { type AtLeastTuple } from '@augment-vir/core'; | ||
export declare function combineErrors(errors: AtLeastTuple<Error, 1>): Error; | ||
export declare function combineErrors(errors: ReadonlyArray<Error | undefined>): Error | undefined; | ||
/** | ||
* Combines an array of errors into a single array. | ||
* | ||
* - If no errors are in the given array, a new Error with an empty message is returned. | ||
* - If only one error is in the given array, it is directly returned without modification. | ||
* | ||
* @category Array | ||
* @category Error | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {combineErrors} from '@augment-vir/common'; | ||
* | ||
* const result1 = combineErrors([ | ||
* new Error('message 1'), | ||
* new Error('message 2'), | ||
* ]); // result1 is a single error with the message 'message 1\nmessage 2' | ||
* ``` | ||
* | ||
* @returns A single error. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function combineErrors(errors: ReadonlyArray<Error>): Error; |
import { check } from '@augment-vir/assert'; | ||
import { extractErrorMessage } from '@augment-vir/core'; | ||
export function combineErrors(rawErrors) { | ||
const errors = rawErrors.filter((error) => error); | ||
/** | ||
* Combines an array of errors into a single array. | ||
* | ||
* - If no errors are in the given array, a new Error with an empty message is returned. | ||
* - If only one error is in the given array, it is directly returned without modification. | ||
* | ||
* @category Array | ||
* @category Error | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {combineErrors} from '@augment-vir/common'; | ||
* | ||
* const result1 = combineErrors([ | ||
* new Error('message 1'), | ||
* new Error('message 2'), | ||
* ]); // result1 is a single error with the message 'message 1\nmessage 2' | ||
* ``` | ||
* | ||
* @returns A single error. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function combineErrors(errors) { | ||
if (!check.isLengthAtLeast(errors, 1)) { | ||
return undefined; | ||
return new Error(); | ||
} | ||
if (errors.length === 1) { | ||
else if (errors.length === 1) { | ||
return errors[0]; | ||
@@ -10,0 +32,0 @@ } |
@@ -5,3 +5,22 @@ import { MaybePromise } from '@augment-vir/core'; | ||
* function was originally synchronous. | ||
* | ||
* @category Function | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {callAsynchronously} from '@augment-vir/common'; | ||
* | ||
* console.info('1'); | ||
* const later = callAsynchronously(() => { | ||
* console.info('3'); | ||
* }); | ||
* console.info('2'); | ||
* await later; | ||
* | ||
* // logs 1,2,3 in numeric order | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function callAsynchronously<T>(callback: () => MaybePromise<T>): Promise<T>; |
/** | ||
* Call a function asynchronously without interrupting current synchronous execution, even if the | ||
* function was originally synchronous. | ||
* | ||
* @category Function | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {callAsynchronously} from '@augment-vir/common'; | ||
* | ||
* console.info('1'); | ||
* const later = callAsynchronously(() => { | ||
* console.info('3'); | ||
* }); | ||
* console.info('2'); | ||
* await later; | ||
* | ||
* // logs 1,2,3 in numeric order | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -5,0 +24,0 @@ export async function callAsynchronously(callback) { |
@@ -1,4 +0,24 @@ | ||
import { MaybePromise } from '@augment-vir/core'; | ||
export declare function callWithRetries<const T>(maxRetries: number, callback: () => Promise<T>): Promise<T>; | ||
/** | ||
* Calls `callback` until it doesn't throw an error or throws an error when `maxRetries` is reached. | ||
* Similar to the `waitUntil` guard from '@augment-vir/assert' but doesn't check the callback's | ||
* output. | ||
* | ||
* @category Function | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {callWithRetries} from '@augment-vir/common'; | ||
* | ||
* const result = callWithRetries(5, () => { | ||
* if (Math.random() < 0.5) { | ||
* return 'done'; | ||
* } else { | ||
* throw new Error(); | ||
* } | ||
* }); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function callWithRetries<const T>(maxRetries: number, callback: () => T): T; | ||
export declare function callWithRetries<const T>(maxRetries: number, callback: () => MaybePromise<T>): MaybePromise<T>; |
import { ensureErrorAndPrependMessage } from '@augment-vir/core'; | ||
/** | ||
* Calls `callback` until it doesn't throw an error or throws an error when `maxRetries` is reached. | ||
* Similar to the `waitUntil` guard from '@augment-vir/assert' but doesn't check the callback's | ||
* output. | ||
* | ||
* @category Function | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {callWithRetries} from '@augment-vir/common'; | ||
* | ||
* const result = callWithRetries(5, () => { | ||
* if (Math.random() < 0.5) { | ||
* return 'done'; | ||
* } else { | ||
* throw new Error(); | ||
* } | ||
* }); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function callWithRetries(maxRetries, callback) { | ||
@@ -3,0 +26,0 @@ try { |
import { MaybePromise } from '@augment-vir/core'; | ||
import { AnyDuration } from '@date-vir/duration'; | ||
/** | ||
* Different types of debouncing for the {@link Debounce} class. | ||
* | ||
* @category Function | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare enum DebounceStyle { | ||
/** | ||
* Fires on the first call, then waits the given amount of milliseconds until a subsequent call | ||
* can be made. | ||
* Fires on the first call, then waits the given amount of milliseconds until another call is | ||
* allowed through. | ||
* | ||
* `.execute()` calls with a 25ms debounce time looks like this: | ||
* | ||
* | 1st `.execute()` | 2nd `.execute()` | 3rd `.execute()` | 4th `.execute()` | | ||
* | ---------------- | ---------------- | ---------------- | ---------------- | | ||
* | 0ms | 10ms | 20ms | 30ms | | ||
* | fired! | | | fired! | | ||
*/ | ||
@@ -12,12 +26,65 @@ FirstThenWait = "first-then-wait", | ||
* assigned callback. | ||
* | ||
* `.execute()` calls with a 25ms debounce time looks like this: | ||
* | ||
* | 1st `.execute()` | 2nd `.execute()` | 3rd `.execute()` | - | 4th `.execute()` | ... | | ||
* | ---------------- | ---------------- | ---------------- | ------ | ---------------- | ------ | | ||
* | 0ms | 10ms | 20ms | 25ms | 30ms | 50ms | | ||
* | | | | fired! | | fired! | | ||
*/ | ||
AfterWait = "after-wait" | ||
} | ||
/** | ||
* Enable debouncing of callbacks, with various styles of debounce supported in {@link DebounceStyle} | ||
* (see its docs for debounce style details). A callback can be provided on construction or to the | ||
* `.execute()` method. | ||
* | ||
* @category Function | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {Debounce} from '@augment-vir/common'; | ||
* | ||
* const debounce = new Debounce( | ||
* DebounceStyle.FirstThenWait, | ||
* { | ||
* milliseconds: 500, | ||
* }, | ||
* // callback can optionally be provided on construction | ||
* () => { | ||
* console.log('called'); | ||
* }, | ||
* ); | ||
* | ||
* debounce.execute(); | ||
* // providing a callback in `.execute()` permanently overrides the callback provided in construction. | ||
* debounce.execute(() => {}); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare class Debounce { | ||
/** Debounce style. See {@link DebounceStyle} for more details. */ | ||
debounceStyle: DebounceStyle; | ||
/** Duration between debounces. */ | ||
debounceDuration: AnyDuration; | ||
/** | ||
* Set the callback to be triggered on `.execute()`. If this is not set, the callback to be | ||
* called can be passed in `.execute()` instead. | ||
*/ | ||
callback?: (() => MaybePromise<void>) | undefined; | ||
nextCallTimestamp: number; | ||
callback: (() => MaybePromise<void>) | undefined; | ||
constructor(debounceStyle: DebounceStyle, debounceDuration: AnyDuration, callback?: typeof this.callback | undefined); | ||
constructor( | ||
/** Debounce style. See {@link DebounceStyle} for more details. */ | ||
debounceStyle: DebounceStyle, | ||
/** Duration between debounces. */ | ||
debounceDuration: AnyDuration, | ||
/** | ||
* Set the callback to be triggered on `.execute()`. If this is not set, the callback to be | ||
* called can be passed in `.execute()` instead. | ||
*/ | ||
callback?: (() => MaybePromise<void>) | undefined); | ||
/** Call the callback, if one has been set yet, if the current debounce timer is up. */ | ||
execute(callback?: typeof this.callback | undefined): void; | ||
} |
import { convertDuration, DurationUnit } from '@date-vir/duration'; | ||
/** | ||
* Different types of debouncing for the {@link Debounce} class. | ||
* | ||
* @category Function | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export var DebounceStyle; | ||
(function (DebounceStyle) { | ||
/** | ||
* Fires on the first call, then waits the given amount of milliseconds until a subsequent call | ||
* can be made. | ||
* Fires on the first call, then waits the given amount of milliseconds until another call is | ||
* allowed through. | ||
* | ||
* `.execute()` calls with a 25ms debounce time looks like this: | ||
* | ||
* | 1st `.execute()` | 2nd `.execute()` | 3rd `.execute()` | 4th `.execute()` | | ||
* | ---------------- | ---------------- | ---------------- | ---------------- | | ||
* | 0ms | 10ms | 20ms | 30ms | | ||
* | fired! | | | fired! | | ||
*/ | ||
@@ -12,13 +26,60 @@ DebounceStyle["FirstThenWait"] = "first-then-wait"; | ||
* assigned callback. | ||
* | ||
* `.execute()` calls with a 25ms debounce time looks like this: | ||
* | ||
* | 1st `.execute()` | 2nd `.execute()` | 3rd `.execute()` | - | 4th `.execute()` | ... | | ||
* | ---------------- | ---------------- | ---------------- | ------ | ---------------- | ------ | | ||
* | 0ms | 10ms | 20ms | 25ms | 30ms | 50ms | | ||
* | | | | fired! | | fired! | | ||
*/ | ||
DebounceStyle["AfterWait"] = "after-wait"; | ||
})(DebounceStyle || (DebounceStyle = {})); | ||
/** | ||
* Enable debouncing of callbacks, with various styles of debounce supported in {@link DebounceStyle} | ||
* (see its docs for debounce style details). A callback can be provided on construction or to the | ||
* `.execute()` method. | ||
* | ||
* @category Function | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {Debounce} from '@augment-vir/common'; | ||
* | ||
* const debounce = new Debounce( | ||
* DebounceStyle.FirstThenWait, | ||
* { | ||
* milliseconds: 500, | ||
* }, | ||
* // callback can optionally be provided on construction | ||
* () => { | ||
* console.log('called'); | ||
* }, | ||
* ); | ||
* | ||
* debounce.execute(); | ||
* // providing a callback in `.execute()` permanently overrides the callback provided in construction. | ||
* debounce.execute(() => {}); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export class Debounce { | ||
debounceStyle; | ||
debounceDuration; | ||
callback; | ||
nextCallTimestamp = 0; | ||
callback; | ||
constructor(debounceStyle, debounceDuration, callback) { | ||
constructor( | ||
/** Debounce style. See {@link DebounceStyle} for more details. */ | ||
debounceStyle, | ||
/** Duration between debounces. */ | ||
debounceDuration, | ||
/** | ||
* Set the callback to be triggered on `.execute()`. If this is not set, the callback to be | ||
* called can be passed in `.execute()` instead. | ||
*/ | ||
callback) { | ||
this.debounceStyle = debounceStyle; | ||
this.debounceDuration = debounceDuration; | ||
this.callback = callback; | ||
if (callback) { | ||
@@ -28,2 +89,3 @@ this.callback = callback; | ||
} | ||
/** Call the callback, if one has been set yet, if the current debounce timer is up. */ | ||
execute(callback) { | ||
@@ -30,0 +92,0 @@ if (callback) { |
import { Duration, DurationUnit } from '@date-vir/duration'; | ||
export type ExecutionDuration = Duration<DurationUnit.Milliseconds>; | ||
/** | ||
* Measures how long (in milliseconds) the given callback takes to run to completion. Automatically | ||
* switches to async mode and awaits callbacks if they return a promise (otherwise this function is | ||
* purely synchronous). | ||
* Measures how long (in milliseconds) the given callback takes to run to completion. By default | ||
* this is synchronous, but it will automatically switch to async and await the callback if it | ||
* returns a promise. | ||
* | ||
* @category Function | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {measureExecutionDuration} from '@augment-vir/common'; | ||
* | ||
* const duration1 = measureExecutionDuration(() => {}); | ||
* const duration2 = await measureExecutionDuration(async () => {}); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function measureExecutionDuration<T>(callback: () => T): T extends Promise<any> ? Promise<ExecutionDuration> : ExecutionDuration; | ||
export declare function measureExecutionDuration<T>(callback: () => T): T extends Promise<any> ? Promise<Duration<DurationUnit.Milliseconds>> : Duration<DurationUnit.Milliseconds>; |
import { ensureError } from '@augment-vir/core'; | ||
/** | ||
* Measures how long (in milliseconds) the given callback takes to run to completion. Automatically | ||
* switches to async mode and awaits callbacks if they return a promise (otherwise this function is | ||
* purely synchronous). | ||
* Measures how long (in milliseconds) the given callback takes to run to completion. By default | ||
* this is synchronous, but it will automatically switch to async and await the callback if it | ||
* returns a promise. | ||
* | ||
* @category Function | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {measureExecutionDuration} from '@augment-vir/common'; | ||
* | ||
* const duration1 = measureExecutionDuration(() => {}); | ||
* const duration2 = await measureExecutionDuration(async () => {}); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -7,0 +20,0 @@ export function measureExecutionDuration(callback) { |
import { type NoInputsFunction, type PartialWithUndefined } from '@augment-vir/core'; | ||
/** | ||
* Options for {@link wrapInTry}. | ||
* | ||
* @category Function | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type WrapInTryOptions<FallbackValue> = PartialWithUndefined<{ | ||
/** | ||
* A callback that is passed the error. The output of this callback is returned by `wrapInTry`. | ||
* This takes precedence over the other two options. | ||
* Call this function if the callback passed to {@link wrapInTry} throws an error. The thrown | ||
* error is passed to this function. If a `fallbackValue` option is also provided, it will be | ||
* ignored. | ||
*/ | ||
handleError: (error: unknown) => FallbackValue; | ||
/** | ||
* Fallback to this value if the callback passed to `wrapInTry` throws an error. Takes | ||
* precedence over `returnError`. | ||
* Fallback to this value if the callback passed to {@link wrapInTry} throws an error. This will | ||
* be ignored if a `handleError` option is also set. | ||
*/ | ||
@@ -12,0 +20,0 @@ fallbackValue: FallbackValue; |
import { check } from '@augment-vir/assert'; | ||
import { ensureError, } from '@augment-vir/core'; | ||
/** | ||
* Calls the callback and returns its output. If the callback throws an error, it is handled in the | ||
* following ways: | ||
* | ||
* - If a `handleError` function is provided in `options`, it is passed the thrown error. The output | ||
* of `handleError` is returned by `wrapInTry`. | ||
* - If a `fallbackValue` is provided, it is returned by `wrapInTry`. The thrown error is ignored. | ||
* - If no options are provided, the thrown error is returned by `wrapInTry`. | ||
* | ||
* @category Function | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {wrapInTry} from '@augment-vir/common'; | ||
* | ||
* // `result1` will be `'success'`. | ||
* const result1 = wrapInTry( | ||
* () => { | ||
* return 'success'; | ||
* }, | ||
* { | ||
* fallbackValue: 'failure', | ||
* }, | ||
* ); | ||
* // `result2` will be `'failure'`. | ||
* const result2 = wrapInTry( | ||
* () => { | ||
* throw new Error(); | ||
* return 'success'; | ||
* }, | ||
* { | ||
* fallbackValue: 'failure', | ||
* }, | ||
* ); | ||
* // `result3` will be `'failure also'`. | ||
* const result3 = wrapInTry( | ||
* () => { | ||
* throw new Error(); | ||
* return 'success'; | ||
* }, | ||
* { | ||
* handleError() { | ||
* return 'failure also'; | ||
* }, | ||
* }, | ||
* ); | ||
* // `result4` will be `'failure also'`. | ||
* const result4 = wrapInTry( | ||
* () => { | ||
* throw new Error(); | ||
* return 'success'; | ||
* }, | ||
* { | ||
* handleError() { | ||
* return 'failure also'; | ||
* }, | ||
* fallbackValue: 'ignored', | ||
* }, | ||
* ); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function wrapInTry(callback, options = {}) { | ||
@@ -4,0 +68,0 @@ try { |
import type { JsonCompatibleArray, JsonCompatibleObject, JsonCompatibleValue } from './json-compatible.js'; | ||
export declare function appendJson(...entries: ReadonlyArray<JsonCompatibleObject | undefined>): JsonCompatibleObject; | ||
export declare function appendJson(...entries: ReadonlyArray<JsonCompatibleArray | undefined>): JsonCompatibleArray; | ||
export declare function appendJson(...entries: ReadonlyArray<JsonCompatibleObject | JsonCompatibleArray | undefined>): JsonCompatibleObject | JsonCompatibleArray; | ||
import { JsonCompatiblePrimitive } from './json-compatible.js'; | ||
export declare function appendJson(entry: JsonCompatibleArray | JsonCompatiblePrimitive, ...entries: ReadonlyArray<JsonCompatibleValue | undefined>): JsonCompatibleArray; | ||
export declare function appendJson(entry: JsonCompatibleObject, ...entries: ReadonlyArray<JsonCompatibleObject | JsonCompatibleArray | undefined>): JsonCompatibleObject; | ||
export declare function appendJson(...entries: ReadonlyArray<JsonCompatibleValue | undefined>): JsonCompatibleObject | JsonCompatibleArray; |
import { check } from '@augment-vir/assert'; | ||
import { copyThroughJson } from './copy-through-json.js'; | ||
/** | ||
* Appends all provided JSON values together. `undefined` values will be ignored. The first value | ||
* determines whether the output will be an object or an array. Any value appended to an array will | ||
* work just fine, but primitives append to an object will likely behave unexpectedly. Arrays | ||
* appended to arrays will be flattened (but only by one level). | ||
* | ||
* @category JSON : Common | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {appendJson} from '@augment-vir/common'; | ||
* | ||
* // `result1` will be `{a: 'q', b: 'b'}` | ||
* const result1 = appendJson({a: 'a'}, {b: 'b'}, {a: 'q'}); | ||
* // `result2` will be `[{a: 'a'}, {b: 'b'}, {a: 'q'}, 'r']` | ||
* const result2 = appendJson([{a: 'a'}], {b: 'b'}, {a: 'q'}, 'r'); | ||
* // `result3` will be `['a', ['b', 'c'], 'd', 'e']` | ||
* const result3 = appendJson( | ||
* ['a'], | ||
* [ | ||
* [ | ||
* 'b', | ||
* 'c', | ||
* ], | ||
* ], | ||
* ['d'], | ||
* 'e', | ||
* ); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function appendJson(...rawEntries) { | ||
@@ -4,0 +37,0 @@ const entries = rawEntries.filter(check.isTruthy); |
import { Jsonify, Writable } from 'type-fest'; | ||
/** The input here must be serializable otherwise the output will not match the input. */ | ||
/** | ||
* Deeply copy an object through JSON. This is the fastest deep copy, but the input must already be | ||
* JSON serializable otherwise the copy will not match the original. | ||
* | ||
* @category JSON : Common | ||
* @category Copy | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {copyThroughJson} from '@augment-vir/common'; | ||
* | ||
* // `copy1` will be `{a: 'a', b: 'b'}` | ||
* const copy1 = copyThroughJson({a: 'a', b: 'b'}); | ||
* // `copy2` will be `{map: {}, b: 'b'}` | ||
* const copy2 = copyThroughJson({ | ||
* map: new Map([ | ||
* [ | ||
* 'q', | ||
* 'r', | ||
* ], | ||
* [ | ||
* 's', | ||
* 't', | ||
* ], | ||
* ]), | ||
* b: 'b', | ||
* }); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function copyThroughJson<const T>(input: T): Writable<Jsonify<T>>; |
@@ -1,2 +0,33 @@ | ||
/** The input here must be serializable otherwise the output will not match the input. */ | ||
/** | ||
* Deeply copy an object through JSON. This is the fastest deep copy, but the input must already be | ||
* JSON serializable otherwise the copy will not match the original. | ||
* | ||
* @category JSON : Common | ||
* @category Copy | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {copyThroughJson} from '@augment-vir/common'; | ||
* | ||
* // `copy1` will be `{a: 'a', b: 'b'}` | ||
* const copy1 = copyThroughJson({a: 'a', b: 'b'}); | ||
* // `copy2` will be `{map: {}, b: 'b'}` | ||
* const copy2 = copyThroughJson({ | ||
* map: new Map([ | ||
* [ | ||
* 'q', | ||
* 'r', | ||
* ], | ||
* [ | ||
* 's', | ||
* 't', | ||
* ], | ||
* ]), | ||
* b: 'b', | ||
* }); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function copyThroughJson(input) { | ||
@@ -3,0 +34,0 @@ try { |
import { Jsonify, Primitive } from 'type-fest'; | ||
/** | ||
* These are similar in purpose, name, and structure to type-fest's JsonValue types but these are | ||
* permissive. The goal here is to allow any types that do not get serialized into just empty | ||
* more permissive. The goal here is to allow any types that do not get serialized into just empty | ||
* objects. (For example, JSON.stringify(new Map()) returns "{}", so we don't want to allow that | ||
* type.) | ||
*/ | ||
export type JsonCompatiblePrimitiveValue = Jsonify<Primitive> | undefined; | ||
/** | ||
* All primitives that are allowed in JSON. | ||
* | ||
* Note that while `undefined` is allowed here, it will be behave slightly differently than the | ||
* others. | ||
* | ||
* - `JSON.stringify(undefined)` will output `undefined`, not a string. | ||
* - `JSON.stringify({a: null, b: undefined})` will output `'{"a": null}'`, omitting the `b` key | ||
* entirely. | ||
* | ||
* @category JSON : Common | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type JsonCompatiblePrimitive = Jsonify<Primitive> | undefined; | ||
/** | ||
* An object that only contains JSON compatible values. | ||
* | ||
* @category JSON : Common | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type JsonCompatibleObject = Partial<{ | ||
@@ -14,10 +35,17 @@ readonly [key: string | number]: JsonCompatibleValue | Readonly<JsonCompatibleValue>; | ||
}>; | ||
export type JsonCompatibleArray = JsonCompatibleValue[] | ||
/** | ||
* This weird readonly with object syntax for an array type is so that TypeScript doesn't | ||
* complain about JsonCompatibleArray circularly referencing itself | ||
* An array that only contains JSON compatible values. | ||
* | ||
* @category JSON : Common | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
| ({ | ||
readonly [P in number]: JsonCompatibleValue; | ||
} & ReadonlyArray<any>); | ||
export type JsonCompatibleValue = JsonCompatiblePrimitiveValue | JsonCompatibleObject | JsonCompatibleArray; | ||
export type JsonCompatibleArray = JsonCompatibleValue[] | ReadonlyArray<JsonCompatibleValue>; | ||
/** | ||
* Any JSON compatible value. | ||
* | ||
* @category JSON : Common | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type JsonCompatibleValue = JsonCompatiblePrimitive | JsonCompatibleObject | JsonCompatibleArray; |
import { Jsonify } from 'type-fest'; | ||
export declare function jsonify<T>(input: T): Jsonify<T>; | ||
/** | ||
* Creates a JSON compatible version of the value given. Under the hood this is actually the same as | ||
* {@link copyThroughJson}. | ||
* | ||
* @category JSON : Common | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {jsonify} from '@augment-vir/common'; | ||
* | ||
* // `result` is `{b: 'b'}` | ||
* const result = jsonify({ | ||
* map: new Map([ | ||
* [ | ||
* 'q', | ||
* 'r', | ||
* ], | ||
* [ | ||
* 's', | ||
* 't', | ||
* ], | ||
* ]), | ||
* b: 'b', | ||
* }); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function jsonify<T>(value: T): Jsonify<T>; |
import JSON5 from 'json5'; | ||
export function jsonify(input) { | ||
return JSON5.parse(JSON5.stringify(input)); | ||
/** | ||
* Creates a JSON compatible version of the value given. Under the hood this is actually the same as | ||
* {@link copyThroughJson}. | ||
* | ||
* @category JSON : Common | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {jsonify} from '@augment-vir/common'; | ||
* | ||
* // `result` is `{b: 'b'}` | ||
* const result = jsonify({ | ||
* map: new Map([ | ||
* [ | ||
* 'q', | ||
* 'r', | ||
* ], | ||
* [ | ||
* 's', | ||
* 't', | ||
* ], | ||
* ]), | ||
* b: 'b', | ||
* }); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function jsonify(value) { | ||
return JSON5.parse(JSON5.stringify(value)); | ||
} |
@@ -0,7 +1,26 @@ | ||
/** | ||
* Supported log output types. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare enum LogOutputType { | ||
/** Logged to stdout if the current environment supports it, or just `console.log`. */ | ||
Standard = "stdout", | ||
/** Logged to stderr if the current environment supports it, or just `console.error`. */ | ||
Error = "stderr" | ||
} | ||
/** | ||
* Standardized color keys for logging. If you want to use customized colors, use | ||
* [ansi-styles](https://www.npmjs.com/package/ansi-styles) in Node.js or [custom | ||
* CSS](https://developer.mozilla.org/docs/Web/API/console#styling_console_output) in browsers. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare enum LogColorKey { | ||
Bold = "bold", | ||
Debug = "debug", | ||
Error = "error", | ||
@@ -17,2 +36,10 @@ Faint = "faint", | ||
} | ||
/** | ||
* Configuration for creating a logger. This is not required, as a default configuration is built-in | ||
* already. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type LogColorConfig = Readonly<Record<LogColorKey, { | ||
@@ -23,3 +50,17 @@ /** Either an array of CSS property assignments */ | ||
}>>; | ||
/** | ||
* Mapping of color keys to the current color string. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare const logColors: Readonly<Record<LogColorKey, string>>; | ||
/** | ||
* Default implementation of {@link LogColorConfig}. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare const defaultLogColorConfig: LogColorConfig; |
@@ -1,10 +0,29 @@ | ||
import { forEachEnv, RuntimeEnv } from '@augment-vir/core'; | ||
import { perEnv, RuntimeEnv } from '@augment-vir/core'; | ||
/** | ||
* Supported log output types. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export var LogOutputType; | ||
(function (LogOutputType) { | ||
/** Logged to stdout if the current environment supports it, or just `console.log`. */ | ||
LogOutputType["Standard"] = "stdout"; | ||
/** Logged to stderr if the current environment supports it, or just `console.error`. */ | ||
LogOutputType["Error"] = "stderr"; | ||
})(LogOutputType || (LogOutputType = {})); | ||
/** | ||
* Standardized color keys for logging. If you want to use customized colors, use | ||
* [ansi-styles](https://www.npmjs.com/package/ansi-styles) in Node.js or [custom | ||
* CSS](https://developer.mozilla.org/docs/Web/API/console#styling_console_output) in browsers. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export var LogColorKey; | ||
(function (LogColorKey) { | ||
LogColorKey["Bold"] = "bold"; | ||
LogColorKey["Debug"] = "debug"; | ||
LogColorKey["Error"] = "error"; | ||
@@ -21,3 +40,3 @@ LogColorKey["Faint"] = "faint"; | ||
async function determineDefaultLogColors() { | ||
return await forEachEnv({ | ||
return await perEnv({ | ||
/** We calculate coverage in web, so the node code will never run in coverage tests. */ | ||
@@ -29,2 +48,3 @@ /* node:coverage disable */ | ||
[LogColorKey.Bold]: styles.bold.open, | ||
[LogColorKey.Debug]: styles.blueBright.open, | ||
[LogColorKey.Error]: styles.red.open, | ||
@@ -45,2 +65,3 @@ [LogColorKey.Faint]: styles.gray.open, | ||
[LogColorKey.Bold]: 'font-weight: bold', | ||
[LogColorKey.Debug]: 'color: blue', | ||
[LogColorKey.Error]: 'color: red', | ||
@@ -59,3 +80,17 @@ [LogColorKey.Faint]: 'color: grey', | ||
} | ||
/** | ||
* Mapping of color keys to the current color string. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export const logColors = await determineDefaultLogColors(); | ||
/** | ||
* Default implementation of {@link LogColorConfig}. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export const defaultLogColorConfig = { | ||
@@ -68,2 +103,8 @@ [LogColorKey.Bold]: { | ||
}, | ||
[LogColorKey.Debug]: { | ||
colors: [ | ||
logColors.debug, | ||
], | ||
logType: LogOutputType.Standard, | ||
}, | ||
[LogColorKey.Faint]: { | ||
@@ -70,0 +111,0 @@ colors: [ |
import { LogColorKey, type LogColorConfig } from './log-colors.js'; | ||
import { LogWriterParams } from './log-writer.js'; | ||
/** | ||
* Options for a custom Logger. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type LoggerOptions = { | ||
@@ -7,2 +14,9 @@ colorConfig: LogColorConfig; | ||
}; | ||
/** | ||
* Parameters for {@link toLogString}. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type ToLogStringParams = { | ||
@@ -14,3 +28,10 @@ colorKey: LogColorKey; | ||
type ToLogString = (params: Readonly<ToLogStringParams>) => LogWriterParams; | ||
/** | ||
* Converts log arguments into a single {@link LogWriterParams}. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare const toLogString: ToLogString; | ||
export {}; |
import { check } from '@augment-vir/assert'; | ||
import { forEachEnv, RuntimeEnv, stringify } from '@augment-vir/core'; | ||
import { perEnv, RuntimeEnv, stringify } from '@augment-vir/core'; | ||
import { filterMap } from '../array/filter.js'; | ||
@@ -7,3 +7,3 @@ import { removeSuffix } from '../string/suffix.js'; | ||
async function createToLogString() { | ||
return await forEachEnv({ | ||
return await perEnv({ | ||
/** We calculate coverage in web, so the node code will never run in coverage tests. */ | ||
@@ -67,2 +67,9 @@ /* node:coverage disable */ | ||
} | ||
/** | ||
* Converts log arguments into a single {@link LogWriterParams}. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export const toLogString = await createToLogString(); |
import { type LogOutputType } from './log-colors.js'; | ||
/** | ||
* Params for {@link LogWriter} | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type LogWriterParams = { | ||
@@ -7,3 +14,18 @@ text: string; | ||
}; | ||
/** | ||
* The final step in writing a log. This will actually perform the logging of text to the console. | ||
* CSS will be applied if this is called within a browser. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type LogWriter = (params: Readonly<LogWriterParams>) => void; | ||
/** | ||
* A log writer for each log output type. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type LogWriters = Record<LogOutputType, LogWriter>; |
@@ -5,5 +5,48 @@ import { type PartialWithUndefined } from '@augment-vir/core'; | ||
import { type Logger } from './logger.js'; | ||
/** | ||
* Default implementation of {@link LogWriters} that is dependent on the current runtime environment. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare const defaultLogWriters: LogWriters; | ||
/** | ||
* The default `log`. Use this in place of `console` methods for styled outputs in both Node.js and | ||
* the browser. | ||
* | ||
* @category Log | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {log} from '@augment-vir/common'; | ||
* | ||
* log.info('hi'); | ||
* log.error('failure'); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare const log: Logger; | ||
export declare function createLoggerWithStoredLogs(options?: PartialWithUndefined<LoggerOptions> | undefined): { | ||
/** | ||
* Creates a custom logger that doesn't actually log but stores the logs into a object for later | ||
* usage. This is particularly useful in tests. | ||
* | ||
* @category Log | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {createArrayLogger} from '@augment-vir/common'; | ||
* | ||
* const {log, logs} = createArrayLogger(); | ||
* | ||
* log.info('hi'); | ||
* // `logs[LogOutputType.Standard]` is now `['hi']` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function createArrayLogger(options?: PartialWithUndefined<LoggerOptions> | undefined): { | ||
log: Logger; | ||
@@ -10,0 +53,0 @@ logs: { |
@@ -5,2 +5,9 @@ import { isRuntimeEnv, RuntimeEnv } from '@augment-vir/core'; | ||
import { createLogger } from './logger.js'; | ||
/** | ||
* Default implementation of {@link LogWriters} that is dependent on the current runtime environment. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export const defaultLogWriters = | ||
@@ -28,7 +35,43 @@ /** We calculate coverage in web, so the node code will never run in coverage tests. */ | ||
}; | ||
/** | ||
* The default `log`. Use this in place of `console` methods for styled outputs in both Node.js and | ||
* the browser. | ||
* | ||
* @category Log | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {log} from '@augment-vir/common'; | ||
* | ||
* log.info('hi'); | ||
* log.error('failure'); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export const log = createLogger(defaultLogWriters); | ||
export function createLoggerWithStoredLogs(options) { | ||
/** | ||
* Creates a custom logger that doesn't actually log but stores the logs into a object for later | ||
* usage. This is particularly useful in tests. | ||
* | ||
* @category Log | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {createArrayLogger} from '@augment-vir/common'; | ||
* | ||
* const {log, logs} = createArrayLogger(); | ||
* | ||
* log.info('hi'); | ||
* // `logs[LogOutputType.Standard]` is now `['hi']` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function createArrayLogger(options) { | ||
const logs = { | ||
stdout: [], | ||
stderr: [], | ||
[LogOutputType.Standard]: [], | ||
[LogOutputType.Error]: [], | ||
}; | ||
@@ -35,0 +78,0 @@ const log = createLogger({ |
@@ -5,8 +5,57 @@ import type { PartialWithUndefined } from '@augment-vir/core'; | ||
import { type LogWriters } from './log-writer.js'; | ||
/** | ||
* The base `log` methods. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type LoggerLogs = Readonly<Record<LogColorKey, (...args: ReadonlyArray<unknown>) => void>>; | ||
/** | ||
* Type for the `log` export. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type Logger = LoggerLogs & { | ||
/** | ||
* Only logs if the given condition is `true`. | ||
* | ||
* @example | ||
* | ||
* ```ts | ||
* import {log} from '@augment-vir/common'; | ||
* | ||
* // this will log | ||
* log.if(true).info('hi'); | ||
* // this will not log | ||
* log.if(false).info('hi'); | ||
* ``` | ||
*/ | ||
if: (condition: boolean) => LoggerLogs; | ||
}; | ||
/** | ||
* Default implementation of {@link LoggerOptions}. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare const defaultLoggerOptions: LoggerOptions; | ||
/** | ||
* A default {@link Logger} that simply does nothing. | ||
* | ||
* @category Log | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare const emptyLog: Logger; | ||
/** | ||
* Creates a custom {@link Logger}. | ||
* | ||
* @category Log | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function createLogger(logWriters: LogWriters, optionsOverride?: PartialWithUndefined<LoggerOptions> | undefined): Logger; |
@@ -5,2 +5,9 @@ import { mapEnumToObject } from '../object/map-enum.js'; | ||
import { toLogString } from './log-string.js'; | ||
/** | ||
* Default implementation of {@link LoggerOptions}. | ||
* | ||
* @category Log : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export const defaultLoggerOptions = { | ||
@@ -10,2 +17,9 @@ colorConfig: defaultLogColorConfig, | ||
}; | ||
/** | ||
* A default {@link Logger} that simply does nothing. | ||
* | ||
* @category Log | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export const emptyLog = createLogger({ | ||
@@ -15,2 +29,9 @@ [LogOutputType.Error]() { }, | ||
}); | ||
/** | ||
* Creates a custom {@link Logger}. | ||
* | ||
* @category Log | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function createLogger(logWriters, optionsOverride) { | ||
@@ -17,0 +38,0 @@ const options = mergeDefinedProperties(defaultLoggerOptions, optionsOverride); |
@@ -5,4 +5,15 @@ import { MinMax } from './min-max.js'; | ||
* | ||
* @category Number:Common | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {clamp} from '@augment-vir/common'; | ||
* | ||
* // `result` will be `40` | ||
* const result = clamp(42, {min: 30, max: 40}); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function clamp(value: number, { min, max }: MinMax): number; | ||
export declare function clamp(value: number, { min, max }: Readonly<MinMax>): number; |
/** | ||
* Clamp's the given value to within the min and max bounds, inclusive. | ||
* | ||
* @category Number:Common | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {clamp} from '@augment-vir/common'; | ||
* | ||
* // `result` will be `40` | ||
* const result = clamp(42, {min: 30, max: 40}); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -6,0 +17,0 @@ export function clamp(value, { min, max }) { |
/** | ||
* A simple type for storing 2D coordinates. | ||
* | ||
* @category Number:Common | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -13,3 +15,5 @@ export type Coords = { | ||
* | ||
* @category Number:Common | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -16,0 +20,0 @@ export type Coords3d = { |
@@ -0,1 +1,8 @@ | ||
/** | ||
* A union of all single digits in base 10. | ||
* | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; |
/** | ||
* A simple type for storing 2D dimensions. | ||
* | ||
* @category Number:Common | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -13,3 +15,5 @@ export type Dimensions = { | ||
* | ||
* @category Number:Common | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -16,0 +20,0 @@ export type Dimensions3d = { |
@@ -0,1 +1,6 @@ | ||
/** | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type MinMax = { | ||
@@ -7,6 +12,8 @@ min: number; | ||
* Given a min and max, ensures that they are in correct order. Meaning, min is less than max. If | ||
* that is not the case, the returned value is the given min and max values swapped. | ||
* that is not the case, values are swapped. | ||
* | ||
* @category Number:Common | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function ensureMinMax({ min, max }: MinMax): MinMax; |
/** | ||
* Given a min and max, ensures that they are in correct order. Meaning, min is less than max. If | ||
* that is not the case, the returned value is the given min and max values swapped. | ||
* that is not the case, values are swapped. | ||
* | ||
* @category Number:Common | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -7,0 +9,0 @@ export function ensureMinMax({ min, max }) { |
@@ -5,4 +5,6 @@ /** | ||
* | ||
* @category Number:Common | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @returns The converted number or `NaN`. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -13,5 +15,7 @@ export declare function toNumber(input: unknown): number; | ||
* | ||
* @category Number:Common | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @returns The converted number | ||
* @throws `TypeError` if the conversion resulted in `NaN` | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -22,5 +26,7 @@ export declare function toEnsuredNumber(input: unknown): number; | ||
* | ||
* @category Number:Common | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @returns The converted number or `undefined`. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function toMaybeNumber(input: unknown): number | undefined; |
@@ -1,2 +0,2 @@ | ||
import { removeCommas } from '../string/commas.js'; | ||
import { removeCommas } from '../string/comma.js'; | ||
/** | ||
@@ -6,4 +6,6 @@ * Converts the input into a number and returns `NaN` if the conversion fails. This handles more | ||
* | ||
* @category Number:Common | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @returns The converted number or `NaN`. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -24,5 +26,7 @@ export function toNumber(input) { | ||
* | ||
* @category Number:Common | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @returns The converted number | ||
* @throws `TypeError` if the conversion resulted in `NaN` | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -41,4 +45,6 @@ export function toEnsuredNumber(input) { | ||
* | ||
* @category Number:Common | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @returns The converted number or `undefined`. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -45,0 +51,0 @@ export function toMaybeNumber(input) { |
@@ -0,3 +1,22 @@ | ||
/** | ||
* Round a value to the given number of decimal digits. If no decimal value is present, no rounding | ||
* occurs. | ||
* | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {round} from '@augment-vir/common'; | ||
* | ||
* // `result1` is `5.13` | ||
* const result1 = round(5.125, {digits: 2}); | ||
* // `result2` is `5` | ||
* const result2 = round(25, {digits: 2}); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function round(value: number, { digits }: { | ||
digits: number; | ||
}): number; |
@@ -0,1 +1,20 @@ | ||
/** | ||
* Round a value to the given number of decimal digits. If no decimal value is present, no rounding | ||
* occurs. | ||
* | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {round} from '@augment-vir/common'; | ||
* | ||
* // `result1` is `5.13` | ||
* const result1 = round(5.125, {digits: 2}); | ||
* // `result2` is `5` | ||
* const result2 = round(25, {digits: 2}); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function round(value, { digits }) { | ||
@@ -2,0 +21,0 @@ const digitFactor = Math.pow(10, digits); |
@@ -1,1 +0,18 @@ | ||
export declare function doesRequireScientificNotation(input: number): boolean; | ||
/** | ||
* Determines if the given number is so large that it requires scientific notation (`e`) when | ||
* represented as a string. | ||
* | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {requiresScientificNotation} from '@augment-vir/common'; | ||
* | ||
* requiresScientificNotation(5); // false | ||
* requiresScientificNotation(999999999999999999999); // true | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function requiresScientificNotation(input: number): boolean; |
@@ -1,3 +0,20 @@ | ||
export function doesRequireScientificNotation(input) { | ||
/** | ||
* Determines if the given number is so large that it requires scientific notation (`e`) when | ||
* represented as a string. | ||
* | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {requiresScientificNotation} from '@augment-vir/common'; | ||
* | ||
* requiresScientificNotation(5); // false | ||
* requiresScientificNotation(999999999999999999999); // true | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function requiresScientificNotation(input) { | ||
return String(input).includes('e'); | ||
} |
/** | ||
* This truncates a number such that is will at a max have 6 characters including suffix, decimal | ||
* point, or comma. | ||
* The default truncation prefixes for {@link truncateNumber}. | ||
* | ||
* Default suffixes are: | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare const defaultTruncationSuffixes: readonly ["k", "M", "B", "T", "P", "E", "Z", "Y"]; | ||
/** | ||
* Truncates a number such that is will at a max have 6 (customizable) characters including suffix, | ||
* decimal point, or comma. | ||
* | ||
* Default suffixes are in {@link defaultTruncationSuffixes}: | ||
* | ||
* 'k', // thousand | ||
@@ -15,2 +23,15 @@ * 'M', // million | ||
* 'Y', // yotta- septillion | ||
* | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {truncateNumber} from '@augment-vir/common'; | ||
* | ||
* // `result` will be `'1M'` | ||
* const result = truncateNumber(1_000_000); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -17,0 +38,0 @@ export declare function truncateNumber(originalValue: Readonly<unknown>, { customSuffixes, maxLength, }?: Partial<{ |
@@ -1,7 +0,14 @@ | ||
import { safeMatch } from '../regexp/safe-match.js'; | ||
import { addCommasToNumber } from '../string/commas.js'; | ||
import { safeMatch } from '../regexp/match.js'; | ||
import { addCommasToNumber } from '../string/comma.js'; | ||
import { safeSplit } from '../string/split.js'; | ||
import { toNumber } from './number-conversion.js'; | ||
import { doesRequireScientificNotation } from './scientific.js'; | ||
const defaultTruncationSuffixes = [ | ||
import { requiresScientificNotation } from './scientific.js'; | ||
/** | ||
* The default truncation prefixes for {@link truncateNumber}. | ||
* | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export const defaultTruncationSuffixes = [ | ||
'k', // thousand | ||
@@ -122,6 +129,6 @@ 'M', // million | ||
/** | ||
* This truncates a number such that is will at a max have 6 characters including suffix, decimal | ||
* point, or comma. | ||
* Truncates a number such that is will at a max have 6 (customizable) characters including suffix, | ||
* decimal point, or comma. | ||
* | ||
* Default suffixes are: | ||
* Default suffixes are in {@link defaultTruncationSuffixes}: | ||
* | ||
@@ -136,2 +143,15 @@ * 'k', // thousand | ||
* 'Y', // yotta- septillion | ||
* | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {truncateNumber} from '@augment-vir/common'; | ||
* | ||
* // `result` will be `'1M'` | ||
* const result = truncateNumber(1_000_000); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -145,3 +165,3 @@ export function truncateNumber(originalValue, { customSuffixes = defaultTruncationSuffixes, maxLength = 6, } = {}) { | ||
// handle too big or too small edge cases | ||
if (doesRequireScientificNotation(inputNumber)) { | ||
if (requiresScientificNotation(inputNumber)) { | ||
return truncateScientificNotation({ input: inputNumber, maxLength }); | ||
@@ -148,0 +168,0 @@ } |
import { MinMax } from './min-max.js'; | ||
/** | ||
* If the given value is outside the given min/max bounds, instead of clamping the number (as the | ||
* `clamp` function does), this function wraps the value around to the next bound. | ||
* {@link clamp} function does), this function wraps the value around to the next bound (inclusive). | ||
* | ||
* @category Number:Common | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {wrapNumber} from '@augment-vir/common'; | ||
* | ||
* wrapNumber({min: 0, max: 100, value: 101}); // 0 | ||
* wrapNumber({min: 0, max: 100, value: -1}); // 100 | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function wrapNumber(value: number, minMax: MinMax): number; | ||
export declare function wrapNumber(value: number, minMax: Readonly<MinMax>): number; |
import { ensureMinMax } from './min-max.js'; | ||
/** | ||
* If the given value is outside the given min/max bounds, instead of clamping the number (as the | ||
* `clamp` function does), this function wraps the value around to the next bound. | ||
* {@link clamp} function does), this function wraps the value around to the next bound (inclusive). | ||
* | ||
* @category Number:Common | ||
* @category Number | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {wrapNumber} from '@augment-vir/common'; | ||
* | ||
* wrapNumber({min: 0, max: 100, value: 101}); // 0 | ||
* wrapNumber({min: 0, max: 100, value: -1}); // 100 | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -13,0 +19,0 @@ export function wrapNumber(value, minMax) { |
@@ -5,3 +5,7 @@ import { PartialDeep } from 'type-fest'; | ||
* | ||
* @returns An empty tuple if the values are equal. | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @returns An empty tuple if the values are equal. Otherwise, the first tuple entry contains the | ||
* changes in the first value, second entry contains the changes in the second value. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -12,6 +16,16 @@ export declare function diffObjects<T0 extends Readonly<Record<PropertyKey, unknown>>, T1 extends Readonly<Record<PropertyKey, unknown>>>(object0: T0, object1: T1): [PartialDeep<T0>, PartialDeep<T1>] | []; | ||
* | ||
* @returns An empty tuple if the values are equal. | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @returns An empty tuple if the values are equal. Otherwise, the first tuple entry contains the | ||
* changes in the first value, second entry contains the changes in the second value. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function diffArrays<T0, T1>(array0: ReadonlyArray<T0>, array1: ReadonlyArray<T1>): [Array<T0>, Array<T1>] | []; | ||
/** Callback for checking equality between two values that can be of different types. */ | ||
/** | ||
* Callback for checking equality between two values that can be of different types. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type AreEqualCallback<T0, T1> = (value0: T0, value1: T1) => boolean; | ||
@@ -21,3 +35,7 @@ /** | ||
* | ||
* @returns An empty tuple if the values are equal. | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @returns An empty tuple if the values are equal. Otherwise, the first tuple entry contains the | ||
* changes in the first value, second entry contains the changes in the second value. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -30,4 +48,8 @@ export declare function diffBasic<T0, T1>(value0: T0, value1: T1, | ||
* | ||
* @returns An empty tuple if the values are equal. | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @returns An empty tuple if the values are equal. Otherwise, the first tuple entry contains the | ||
* changes in the first value, second entry contains the changes in the second value. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function diffValues<T0, T1>(value0: T0, value1: T1): [T0, T1] | []; |
@@ -6,3 +6,7 @@ import { check } from '@augment-vir/assert'; | ||
* | ||
* @returns An empty tuple if the values are equal. | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @returns An empty tuple if the values are equal. Otherwise, the first tuple entry contains the | ||
* changes in the first value, second entry contains the changes in the second value. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -46,3 +50,7 @@ export function diffObjects(object0, object1) { | ||
* | ||
* @returns An empty tuple if the values are equal. | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @returns An empty tuple if the values are equal. Otherwise, the first tuple entry contains the | ||
* changes in the first value, second entry contains the changes in the second value. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -83,3 +91,7 @@ export function diffArrays(array0, array1) { | ||
* | ||
* @returns An empty tuple if the values are equal. | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @returns An empty tuple if the values are equal. Otherwise, the first tuple entry contains the | ||
* changes in the first value, second entry contains the changes in the second value. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -123,3 +135,7 @@ export function diffBasic(value0, value1, | ||
* | ||
* @returns An empty tuple if the values are equal. | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @returns An empty tuple if the values are equal. Otherwise, the first tuple entry contains the | ||
* changes in the first value, second entry contains the changes in the second value. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -126,0 +142,0 @@ export function diffValues(value0, value1) { |
import { IsEmptyObject } from 'type-fest'; | ||
/** Excludes empty objects from a union. */ | ||
/** | ||
* Excludes empty objects from a union. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type ExcludeEmpty<T> = IsEmptyObject<T> extends true ? never : T; |
import { MaybePromise, type AnyObject } from '@augment-vir/core'; | ||
/** | ||
* Get a value from a map or call the callback and return its result and store the result in the | ||
* map. | ||
* | ||
* @category Object:Common | ||
*/ | ||
export declare function getOrSetFromMap<MapKey extends object, MapValue>(map: WeakMap<MapKey, MapValue>, key: MapKey, createNewValueCallback: () => MapValue): MapValue; | ||
export declare function getOrSetFromMap<MapKey, MapValue>(map: Map<MapKey, MapValue>, key: MapKey, createNewValueCallback: () => MapValue): MapValue; | ||
/** | ||
* Given an object, tries to get the given key in that object. If the key is not in that object, | ||
* then the given `createCallback` is used to create a new value which is then stored in the given | ||
* object and returned. Automatically handles `createCallback` returning a promise, if it does. | ||
* | ||
* @category Object:Common | ||
* @example | ||
* | ||
* ```ts | ||
* // instead of doing this | ||
* if (!myObject[myKey]) { | ||
* myObject[myKey] = {}; | ||
* } | ||
* myObject[myKey]![nextKey] = 'some value'; | ||
* | ||
* // do this | ||
* getOrSetInObject(myObject, myKey, () => {}); | ||
* ``` | ||
*/ | ||
export declare function getOrSetFromMap<MapKey extends object, MapValue>(map: WeakMap<MapKey, MapValue>, key: MapKey, createCallback: () => MapValue): MapValue; | ||
export declare function getOrSetFromMap<MapKey, MapValue>(map: Map<MapKey, MapValue>, key: MapKey, createCallback: () => MapValue): MapValue; | ||
export declare function getOrSetFromMap<MapKey extends object, MapValue>(map: WeakMap<MapKey, MapValue>, key: MapKey, createCallback: () => Promise<MapValue>): Promise<MapValue>; | ||
export declare function getOrSetFromMap<MapKey, MapValue>(map: Map<MapKey, MapValue>, key: MapKey, createCallback: () => Promise<MapValue>): Promise<MapValue>; | ||
export declare function getOrSetFromMap<MapKey extends object, MapValue>(map: WeakMap<MapKey, MapValue>, key: MapKey, createCallback: () => MaybePromise<MapValue>): MaybePromise<MapValue>; | ||
export declare function getOrSetFromMap<MapKey, MapValue>(map: Map<MapKey, MapValue>, key: MapKey, createCallback: () => MaybePromise<MapValue>): MaybePromise<MapValue>; | ||
export declare function getOrSet<OriginalObject extends AnyObject, Key extends keyof OriginalObject>(originalObject: OriginalObject, key: Key, createCallback: () => OriginalObject[Key]): Required<OriginalObject>[Key]; | ||
export declare function getOrSet<OriginalObject extends AnyObject, Key extends keyof OriginalObject>(originalObject: OriginalObject, key: Key, createCallback: () => Promise<OriginalObject[Key]>): Promise<Required<OriginalObject>[Key]>; | ||
export declare function getOrSet<OriginalObject extends AnyObject, Key extends keyof OriginalObject>(originalObject: OriginalObject, key: Key, createCallback: () => MaybePromise<OriginalObject[Key]>): MaybePromise<Required<OriginalObject>[Key]>; |
import { check } from '@augment-vir/assert'; | ||
import { ensureError } from '@augment-vir/core'; | ||
export function getOrSetFromMap(map, key, createNewValueCallback) { | ||
/** | ||
* Given an map, tries to get the given key in that map. If the key is not in that map, then the | ||
* given `createCallback` is used to create a new value which is then stored in the given map and | ||
* returned. Automatically handles an async `createCallback`. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* // instead of doing this | ||
* if (!myMap.get(myKey)) { | ||
* myMap.set(myKey, {}); | ||
* } | ||
* myMap.get(myKey)![nextKey] = 'some value'; | ||
* | ||
* // do this | ||
* getOrSetInObject(myMap, myKey, () => { | ||
* return {}; | ||
* }); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function getOrSetFromMap(map, key, createCallback) { | ||
const mapKey = key; | ||
@@ -10,7 +34,45 @@ if (map.has(mapKey)) { | ||
else { | ||
const newValue = createNewValueCallback(); | ||
map.set(mapKey, newValue); | ||
return newValue; | ||
const createdValue = createCallback(); | ||
if (check.isPromise(createdValue)) { | ||
return new Promise(async (resolve, reject) => { | ||
try { | ||
const awaitedValue = await createdValue; | ||
map.set(mapKey, awaitedValue); | ||
resolve(awaitedValue); | ||
} | ||
catch (error) { | ||
reject(ensureError(error)); | ||
} | ||
}); | ||
} | ||
else { | ||
map.set(mapKey, createdValue); | ||
return createdValue; | ||
} | ||
} | ||
} | ||
/** | ||
* Given an object, tries to get the given key in that object. If the key is not in that object, | ||
* then the given `createCallback` is used to create a new value which is then stored in the given | ||
* object and returned. Automatically handles an async `createCallback`. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* // instead of doing this | ||
* if (!myObject[myKey]) { | ||
* myObject[myKey] = {}; | ||
* } | ||
* myObject[myKey]![nextKey] = 'some value'; | ||
* | ||
* // do this | ||
* getOrSetInObject(myObject, myKey, () => { | ||
* return {}; | ||
* }); | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function getOrSet(originalObject, key, createCallback) { | ||
@@ -17,0 +79,0 @@ if (key in originalObject) { |
@@ -5,2 +5,6 @@ import type { AnyObject } from '@augment-vir/core'; | ||
* as 1. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -7,0 +11,0 @@ export type KeyCount<T extends AnyObject> = UnionToTuple<keyof T>['length']; |
@@ -5,2 +5,25 @@ import { check } from '@augment-vir/assert'; | ||
import { getObjectTypedEntries, typedObjectFromEntries } from './object-entries.js'; | ||
/** | ||
* Maps an object. The callback must return a key and value. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {mapObject} from '@augment-vir/common'; | ||
* | ||
* mapObject({a: 1, b: 2}, (key, value) => { | ||
* return { | ||
* key: `key-${key}`, | ||
* value: `value-${value}`, | ||
* }; | ||
* }); | ||
* // output is `{'key-a': 'value-1', 'key-b': 'value-2'}` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
* @see | ||
* - {@link mapObjectValues}: the variant that only maps values. | ||
*/ | ||
export function mapObject(originalObject, mapCallback) { | ||
@@ -7,0 +30,0 @@ try { |
import type { EnumBaseType, MaybePromise, Values } from '@augment-vir/core'; | ||
/** | ||
* Creates an object that maps all values of an enum to the provided `Values` type. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type EnumMap<Enum extends EnumBaseType, Value> = Values<Enum> extends PropertyKey ? Record<Values<Enum>, Value> : 'ERROR: invalid enum'; | ||
export declare function mapEnumToObject<const Enum extends EnumBaseType, const Value>(enumInput: Enum, callback: (enumValue: Values<Enum>) => Promise<Value>): Promise<EnumMap<Enum, Value>>; | ||
export declare function mapEnumToObject<const Enum extends EnumBaseType, const Value>(enumInput: Enum, callback: (enumValue: Values<Enum>, wholeEnum: Enum) => Value): Value extends Promise<any> ? Promise<any> extends Value ? Promise<EnumMap<Enum, Awaited<Value>>> : MaybePromise<EnumMap<Enum, Awaited<Value>>> : EnumMap<Enum, Value>; |
import { mapObject } from './map-entries.js'; | ||
/** | ||
* Maps all values of an enum as keys in an object where each value is the callback's output for | ||
* that key. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {mapEnumToObject} from '@augment-vir/common'; | ||
* | ||
* enum MyEnum { | ||
* A = 'a', | ||
* B = 'b', | ||
* } | ||
* | ||
* mapEnumToObject(MyEnum, (enumValue) => { | ||
* return `value-${enumValue}`; | ||
* }); | ||
* // output is `{[MyEnum.A]: 'value-a', [MyEnum.B]: 'value-b'}` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function mapEnumToObject(enumInput, callback) { | ||
@@ -3,0 +27,0 @@ return mapObject(enumInput, (enumKey, enumValue) => { |
@@ -1,23 +0,35 @@ | ||
import { type Values } from '@augment-vir/core'; | ||
export type InnerMappedValues<EntireInputGeneric extends object, MappedValueGeneric> = { | ||
type InnerMappedValues<EntireInputGeneric extends object, MappedValueGeneric> = { | ||
[MappedProp in keyof EntireInputGeneric]: MappedValueGeneric; | ||
}; | ||
export type MappedValues<EntireInputGeneric extends object, MappedValueGeneric> = MappedValueGeneric extends PromiseLike<unknown> ? Promise<InnerMappedValues<EntireInputGeneric, Awaited<MappedValueGeneric>>> : InnerMappedValues<EntireInputGeneric, Awaited<MappedValueGeneric>>; | ||
type MappedValues<EntireInputGeneric extends object, MappedValueGeneric> = MappedValueGeneric extends PromiseLike<unknown> ? Promise<InnerMappedValues<EntireInputGeneric, Awaited<MappedValueGeneric>>> : InnerMappedValues<EntireInputGeneric, Awaited<MappedValueGeneric>>; | ||
/** | ||
* Map an object's keys to new values synchronously. This is different from plain mapObjectValues in | ||
* that this will not wrap the return value in a promise if any of the new object values are | ||
* promises. This function also requires currying in order to get the types correct. This allows you | ||
* to explicitly state the return type. | ||
* Creates a new object with the same keys as the input object, but with values set to the result of | ||
* `mapCallback` for each property. This is the same as {@link mapObjectValues} except that this | ||
* preserves Promise values: it doesn't wrap them all in a single promise. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function mapObjectValuesSync<EntireInputGeneric extends object, MappedValueGeneric>(inputObject: EntireInputGeneric, mapCallback: (inputKey: keyof EntireInputGeneric, keyValue: Required<EntireInputGeneric>[typeof inputKey], fullObject: EntireInputGeneric) => MappedValueGeneric): InnerMappedValues<EntireInputGeneric, MappedValueGeneric>; | ||
/** | ||
* Creates a new object with the same keys as the input object, but with values set to the result of | ||
* `mapCallback` for each property. Automatically handles an async `mapCallback`. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* mapObjectValuesSync({objectToIterateOver: 'initial value'})(callback); | ||
* import {mapObjectValues} from '@augment-vir/common'; | ||
* | ||
* mapObjectValues({a: 1, b: 2}, (key, value) => { | ||
* return `key-${key} value-${value}`; | ||
* }); | ||
* // output is `{a: 'key-a value-1', b: 'key-b value-2'}` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function mapObjectValuesSync<EntireInputGeneric extends object>(inputObject: EntireInputGeneric): <OutputObjectGeneric extends object>(mapCallback: (inputKey: keyof EntireInputGeneric, keyValue: Required<EntireInputGeneric>[typeof inputKey], fullObject: EntireInputGeneric) => never extends Values<OutputObjectGeneric> ? any : Values<OutputObjectGeneric>) => OutputObjectGeneric; | ||
/** | ||
* Creates a new object with the same properties as the input object, but with values set to the | ||
* result of mapCallback for each property. | ||
*/ | ||
export declare function mapObjectValues<EntireInputGeneric extends object, MappedValueGeneric>(inputObject: EntireInputGeneric, mapCallback: (inputKey: keyof EntireInputGeneric, keyValue: Required<EntireInputGeneric>[typeof inputKey], fullObject: EntireInputGeneric) => MappedValueGeneric): MappedValues<EntireInputGeneric, MappedValueGeneric>; | ||
export {}; |
import { ensureError, getObjectTypedKeys } from '@augment-vir/core'; | ||
/** | ||
* Map an object's keys to new values synchronously. This is different from plain mapObjectValues in | ||
* that this will not wrap the return value in a promise if any of the new object values are | ||
* promises. This function also requires currying in order to get the types correct. This allows you | ||
* to explicitly state the return type. | ||
* Creates a new object with the same keys as the input object, but with values set to the result of | ||
* `mapCallback` for each property. This is the same as {@link mapObjectValues} except that this | ||
* preserves Promise values: it doesn't wrap them all in a single promise. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function mapObjectValuesSync(inputObject, mapCallback) { | ||
const mappedObject = getObjectTypedKeys(inputObject).reduce((accum, currentKey) => { | ||
const mappedValue = mapCallback(currentKey, inputObject[currentKey], inputObject); | ||
accum[currentKey] = mappedValue; | ||
return accum; | ||
}, {}); | ||
return mappedObject; | ||
} | ||
/** | ||
* Creates a new object with the same keys as the input object, but with values set to the result of | ||
* `mapCallback` for each property. Automatically handles an async `mapCallback`. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* mapObjectValuesSync({objectToIterateOver: 'initial value'})(callback); | ||
* import {mapObjectValues} from '@augment-vir/common'; | ||
* | ||
* mapObjectValues({a: 1, b: 2}, (key, value) => { | ||
* return `key-${key} value-${value}`; | ||
* }); | ||
* // output is `{a: 'key-a value-1', b: 'key-b value-2'}` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function mapObjectValuesSync(inputObject) { | ||
function innerMap(mapCallback) { | ||
return getObjectTypedKeys(inputObject).reduce((accum, currentKey) => { | ||
const mappedValue = mapCallback(currentKey, inputObject[currentKey], inputObject); | ||
return { | ||
...accum, | ||
[currentKey]: mappedValue, | ||
}; | ||
}, {}); | ||
} | ||
return innerMap; | ||
} | ||
/** | ||
* Creates a new object with the same properties as the input object, but with values set to the | ||
* result of mapCallback for each property. | ||
*/ | ||
export function mapObjectValues(inputObject, mapCallback) { | ||
@@ -31,0 +39,0 @@ let gotAPromise = false; |
@@ -7,2 +7,6 @@ import { PartialDeep } from 'type-fest'; | ||
* Note that order matters! Each input object will overwrite the properties of the previous objects. | ||
* | ||
* @category Object : Merge | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -9,0 +13,0 @@ export declare function mergeDeep<const T extends object>(...inputs: (Readonly<T> | Readonly<PartialDeep<T, { |
@@ -7,2 +7,6 @@ import { check } from '@augment-vir/assert'; | ||
* Note that order matters! Each input object will overwrite the properties of the previous objects. | ||
* | ||
* @category Object : Merge | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -9,0 +13,0 @@ export function mergeDeep(...inputs) { |
@@ -5,3 +5,16 @@ import type { AnyObject, PartialWithNullable } from '@augment-vir/core'; | ||
* missing. This only merges objects at the top level, it is not a deep merge. | ||
* | ||
* @category Object : Merge | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {mergeDefinedProperties} from '@augment-vir/common'; | ||
* | ||
* mergeDefinedProperties({a: 'default', b: 'default'}, {a: 'override', b: undefined}); | ||
* // output is `{a: 'override', b: 'default'}` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function mergeDefinedProperties<const T extends AnyObject>(original: T, ...overrides: ReadonlyArray<PartialWithNullable<NoInfer<T>> | undefined>): T; |
@@ -5,2 +5,15 @@ import { getObjectTypedEntries } from './object-entries.js'; | ||
* missing. This only merges objects at the top level, it is not a deep merge. | ||
* | ||
* @category Object : Merge | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {mergeDefinedProperties} from '@augment-vir/common'; | ||
* | ||
* mergeDefinedProperties({a: 'default', b: 'default'}, {a: 'override', b: undefined}); | ||
* // output is `{a: 'override', b: 'default'}` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -7,0 +20,0 @@ export function mergeDefinedProperties(original, ...overrides) { |
@@ -0,1 +1,29 @@ | ||
/** | ||
* Merges all arrays by their property in the given objects. | ||
* | ||
* @category Object : Merge | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {mergePropertyArrays} from '@augment-vir/common'; | ||
* | ||
* mergePropertyArrays( | ||
* { | ||
* a: [ | ||
* 'a', | ||
* 'b', | ||
* ], | ||
* }, | ||
* { | ||
* a: [ | ||
* 'c', | ||
* 'd', | ||
* ], | ||
* }, | ||
* ); // output is `{a: ['a', 'b', 'c', 'd']}` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function mergePropertyArrays<T extends Record<PropertyKey, unknown[]>>(...inputs: ReadonlyArray<Readonly<T>>): T; |
import { getOrSet } from './get-or-set.js'; | ||
/** | ||
* Merges all arrays by their property in the given objects. | ||
* | ||
* @category Object : Merge | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {mergePropertyArrays} from '@augment-vir/common'; | ||
* | ||
* mergePropertyArrays( | ||
* { | ||
* a: [ | ||
* 'a', | ||
* 'b', | ||
* ], | ||
* }, | ||
* { | ||
* a: [ | ||
* 'c', | ||
* 'd', | ||
* ], | ||
* }, | ||
* ); // output is `{a: ['a', 'b', 'c', 'd']}` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function mergePropertyArrays(...inputs) { | ||
@@ -3,0 +31,0 @@ const combined = {}; |
import { CompleteRequire } from '@augment-vir/core'; | ||
/** | ||
* Gets an object's entries. This is the same as | ||
* [`Object.entries`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) | ||
* except that it has better TypeScript types. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function getObjectTypedEntries<const ObjectGeneric>(input: ObjectGeneric): [keyof ObjectGeneric, CompleteRequire<ObjectGeneric>[keyof CompleteRequire<ObjectGeneric>]][]; | ||
/** | ||
* Create an object from an array of entries. This is the same as | ||
* [`Object.fromEntries`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries) | ||
* except that it has better TypeScript types. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function typedObjectFromEntries<const KeyType extends PropertyKey, const ValueType>(entries: ReadonlyArray<Readonly<[KeyType, ValueType]>>): Record<KeyType, ValueType>; | ||
/** | ||
* Gets an object's entries and sorts them by their key values. This is the same as | ||
* [`Object.entries`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) | ||
* except that it has better TypeScript types and sorts the entries. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function getEntriesSortedByKey<const ObjectGeneric>(input: ObjectGeneric): [keyof ObjectGeneric, CompleteRequire<ObjectGeneric>[keyof CompleteRequire<ObjectGeneric>]][]; |
import { getObjectTypedKeys } from '@augment-vir/core'; | ||
/** | ||
* Gets an object's entries. This is the same as | ||
* [`Object.entries`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) | ||
* except that it has better TypeScript types. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function getObjectTypedEntries(input) { | ||
@@ -8,7 +17,25 @@ return getObjectTypedKeys(input).map((key) => [ | ||
} | ||
/** | ||
* Create an object from an array of entries. This is the same as | ||
* [`Object.fromEntries`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries) | ||
* except that it has better TypeScript types. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function typedObjectFromEntries(entries) { | ||
return Object.fromEntries(entries); | ||
} | ||
/** | ||
* Gets an object's entries and sorts them by their key values. This is the same as | ||
* [`Object.entries`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) | ||
* except that it has better TypeScript types and sorts the entries. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function getEntriesSortedByKey(input) { | ||
return getObjectTypedEntries(input).sort((tupleA, tupleB) => String(tupleA[0]).localeCompare(String(tupleB[0]))); | ||
} |
import { type Values } from '@augment-vir/core'; | ||
/** | ||
* Filters an object. Like | ||
* [`[].filter`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries) | ||
* but for objects. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {filterObject} from '@augment-vir'; | ||
* | ||
* filterObject({a: 1, b: 2, c: 3}, (key, value) => { | ||
* return value >= 2; | ||
* }); | ||
* // output is `{b: 2, c: 3}` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function filterObject<ObjectGeneric>(inputObject: ObjectGeneric, callback: (key: keyof ObjectGeneric, value: Values<ObjectGeneric>, fullObject: ObjectGeneric) => boolean): Partial<ObjectGeneric>; |
import { getObjectTypedEntries, typedObjectFromEntries } from './object-entries.js'; | ||
/** | ||
* Filters an object. Like | ||
* [`[].filter`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries) | ||
* but for objects. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {filterObject} from '@augment-vir'; | ||
* | ||
* filterObject({a: 1, b: 2, c: 3}, (key, value) => { | ||
* return value >= 2; | ||
* }); | ||
* // output is `{b: 2, c: 3}` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function filterObject(inputObject, callback) { | ||
@@ -3,0 +23,0 @@ const filteredEntries = getObjectTypedEntries(inputObject).filter(([key, value,]) => { |
@@ -0,2 +1,34 @@ | ||
/** | ||
* Same as the TypeScript built-in type `Omit` except that it works on actual runtime values. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {omitObjectKeys} from '@augment-vir/common'; | ||
* | ||
* omitObjectKeys({a: 'a', b: 'b'}, ['a']); | ||
* // output is `{b: 'b'}` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function omitObjectKeys<const ObjectGeneric, const KeyGeneric extends keyof ObjectGeneric>(inputObject: Readonly<ObjectGeneric>, omitTheseKeys: ReadonlyArray<KeyGeneric>): Omit<ObjectGeneric, KeyGeneric>; | ||
/** | ||
* Same as the TypeScript built-in type `Pick` except that it works on actual runtime values. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {pickObjectKeys} from '@augment-vir/common'; | ||
* | ||
* pickObjectKeys({a: 'a', b: 'b'}, ['a']); | ||
* // output is `{a: 'a'}` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function pickObjectKeys<const ObjectGeneric, const KeyGeneric extends keyof ObjectGeneric>(inputObject: Readonly<ObjectGeneric>, pickTheseKeys: ReadonlyArray<KeyGeneric>): Pick<ObjectGeneric, KeyGeneric>; |
import { filterObject } from './object-filter.js'; | ||
/** | ||
* Same as the TypeScript built-in type `Omit` except that it works on actual runtime values. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {omitObjectKeys} from '@augment-vir/common'; | ||
* | ||
* omitObjectKeys({a: 'a', b: 'b'}, ['a']); | ||
* // output is `{b: 'b'}` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function omitObjectKeys(inputObject, omitTheseKeys) { | ||
@@ -7,2 +23,18 @@ return filterObject(inputObject, (currentKey) => { | ||
} | ||
/** | ||
* Same as the TypeScript built-in type `Pick` except that it works on actual runtime values. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {pickObjectKeys} from '@augment-vir/common'; | ||
* | ||
* pickObjectKeys({a: 'a', b: 'b'}, ['a']); | ||
* // output is `{a: 'a'}` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function pickObjectKeys(inputObject, pickTheseKeys) { | ||
@@ -9,0 +41,0 @@ return filterObject(inputObject, (currentKey) => { |
import { CompleteRequire } from '@augment-vir/core'; | ||
/** | ||
* Gets an object's values. This is the same as | ||
* [`Object.values`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/values) | ||
* except that it has better TypeScript types. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function getObjectTypedValues<ObjectGeneric>(input: ObjectGeneric): CompleteRequire<ObjectGeneric>[keyof CompleteRequire<ObjectGeneric>][]; |
import { getObjectTypedKeys } from '@augment-vir/core'; | ||
/** | ||
* Gets an object's values. This is the same as | ||
* [`Object.values`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/values) | ||
* except that it has better TypeScript types. | ||
* | ||
* @category Object | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function getObjectTypedValues(input) { | ||
return getObjectTypedKeys(input).map((key) => input[key]); | ||
} |
@@ -5,2 +5,4 @@ import type { AnyFunction, AnyObject } from '@augment-vir/core'; | ||
* | ||
* @category Prisma : Common | ||
* @category Package : @augment-vir/common | ||
* @example | ||
@@ -10,5 +12,8 @@ * | ||
* import type {Prisma} from '@prisma/client'; | ||
* import type {ModelNameFromPrismaTypeMap} from '@augment-vir/common'; | ||
* | ||
* function doThing(modelName: ModelNameFromPrismaTypeMap<Prisma.TypeMap>) {} | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -19,2 +24,4 @@ export type ModelNameFromPrismaTypeMap<PrismaTypeMap extends BasePrismaTypeMap> = PrismaTypeMap['meta']['modelProps']; | ||
* | ||
* @category Prisma : Common | ||
* @category Package : @augment-vir/common | ||
* @example | ||
@@ -24,5 +31,8 @@ * | ||
* import type {PrismaClient} from '@prisma/client'; | ||
* import type {ModelNameFromPrismaClient} from '@augment-vir/common'; | ||
* | ||
* function doThing(modelName: ModelNameFromPrismaClient<PrismaClient>) {} | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -37,2 +47,4 @@ export type ModelNameFromPrismaClient<PrismaClient extends AnyObject> = keyof { | ||
* | ||
* @category Prisma : Common | ||
* @category Package : @augment-vir/common | ||
* @example | ||
@@ -42,5 +54,8 @@ * | ||
* import type {PrismaClient} from '@prisma/client'; | ||
* import type {ModelCreationEntry} from '@augment-vir/common'; | ||
* | ||
* function doThing(entry: ModelCreationEntry<PrismaClient, 'User'>) {} | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -52,3 +67,7 @@ export type PrismaModelCreationEntry<PrismaClient extends AnyObject, Model extends ModelNameFromPrismaClient<PrismaClient>> = NonNullable<Parameters<PrismaClient[Model]['create']>[0]> extends { | ||
* A base type for `Prisma.TypeMap` because Prisma doesn't give us one. This currently only includes | ||
* the properties that are used within `@augment-vir/prisma-node-js`. | ||
* the properties that are used within `@augment-vir/common`. | ||
* | ||
* @category Prisma : Common | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -69,2 +88,6 @@ export type BasePrismaTypeMap = { | ||
* actually are. | ||
* | ||
* @category Prisma : Common | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -79,2 +102,4 @@ export type BasePrismaPayload = { | ||
* | ||
* @category Prisma : Common | ||
* @category Package : @augment-vir/common | ||
* @example | ||
@@ -84,5 +109,8 @@ * | ||
* import type {Prisma} from '@prisma/client'; | ||
* import type {FullPrismaModel} from '@augment-vir/common'; | ||
* | ||
* function doThing(fullModel: FullModel<Prisma.TypeMap, 'User'>) {} | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -94,2 +122,4 @@ export type FullPrismaModel<PrismaTypeMap extends BasePrismaTypeMap, Model extends ModelNameFromPrismaTypeMap<PrismaTypeMap>> = ExpandPrismaTypeMapPayload<PrismaTypeMap['model'][Model]['payload']>; | ||
* | ||
* @category Prisma : Common | ||
* @category Package : @augment-vir/common | ||
* @example | ||
@@ -99,5 +129,8 @@ * | ||
* import type {Prisma} from '@prisma/client'; | ||
* import type {BasePrismaModel} from '@augment-vir/common'; | ||
* | ||
* function doThing(fullModel: BaseModel<Prisma.TypeMap, 'User'>) {} | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -108,3 +141,5 @@ export type BasePrismaModel<PrismaTypeMap extends BasePrismaTypeMap, Model extends ModelNameFromPrismaTypeMap<PrismaTypeMap>> = PrismaTypeMap['model'][Model]['payload']['scalars']; | ||
* | ||
* @category Internals | ||
* @category Prisma : Common : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -117,4 +152,6 @@ export type ExpandPrismaTypeMapPayload<Payload extends BasePrismaPayload> = Payload['scalars'] & { | ||
* | ||
* @category Internals | ||
* @category Prisma : Common : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type ExpandPotentialArrayPrismaTypeMapPayload<PayloadWrapper extends BasePrismaPayload | BasePrismaPayload[]> = PayloadWrapper extends (infer ActualPayload extends BasePrismaPayload)[] ? ExpandPrismaTypeMapPayload<ActualPayload>[] : PayloadWrapper extends BasePrismaPayload ? ExpandPrismaTypeMapPayload<PayloadWrapper> : never; |
import { AnyDuration } from '@date-vir/duration'; | ||
/** | ||
* An error thrown by {@link wrapPromiseInTimeout} when the timeout is reached. | ||
* | ||
* @category Promise | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare class PromiseTimeoutError extends Error { | ||
@@ -7,2 +14,10 @@ readonly duration: AnyDuration; | ||
} | ||
/** | ||
* Wraps an already-created Promise in a timeout, causing a rejection if the original Promise isn't | ||
* resolved by then. | ||
* | ||
* @category Promise | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function wrapPromiseInTimeout<T>(duration: Readonly<AnyDuration>, originalPromise: PromiseLike<T>, failureMessage?: string | undefined): Promise<T>; |
import { check } from '@augment-vir/assert'; | ||
import { ensureError } from '@augment-vir/core'; | ||
import { convertDuration, DurationUnit } from '@date-vir/duration'; | ||
/** | ||
* An error thrown by {@link wrapPromiseInTimeout} when the timeout is reached. | ||
* | ||
* @category Promise | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export class PromiseTimeoutError extends Error { | ||
@@ -17,2 +24,10 @@ duration; | ||
} | ||
/** | ||
* Wraps an already-created Promise in a timeout, causing a rejection if the original Promise isn't | ||
* resolved by then. | ||
* | ||
* @category Promise | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function wrapPromiseInTimeout(duration, originalPromise, failureMessage) { | ||
@@ -19,0 +34,0 @@ const milliseconds = convertDuration(duration, DurationUnit.Milliseconds).milliseconds; |
@@ -9,5 +9,9 @@ /** | ||
* | ||
* @category Random | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {randomBoolean} from '@augment-vir/common'; | ||
* | ||
* randomBoolean(50); // 50% chance to return true | ||
@@ -18,3 +22,5 @@ * randomBoolean(0); // always false, 0% chance of being true | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function randomBoolean(percentLikelyToBeTrue?: number): boolean; |
@@ -11,5 +11,9 @@ import { clamp } from '../number/clamp.js'; | ||
* | ||
* @category Random | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {randomBoolean} from '@augment-vir/common'; | ||
* | ||
* randomBoolean(50); // 50% chance to return true | ||
@@ -20,2 +24,4 @@ * randomBoolean(0); // always false, 0% chance of being true | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -22,0 +28,0 @@ export function randomBoolean(percentLikelyToBeTrue = 50) { |
@@ -7,3 +7,5 @@ /** | ||
* | ||
* @category Random:Common | ||
* @category Random | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -10,0 +12,0 @@ export declare function randomInteger({ min: rawMin, max: rawMax }: { |
@@ -8,3 +8,5 @@ import { ensureMinMax } from '../number/min-max.js'; | ||
* | ||
* @category Random:Common | ||
* @category Random | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -11,0 +13,0 @@ export function randomInteger({ min: rawMin, max: rawMax }) { |
/** | ||
* All letters allowed in {@link randomString}. | ||
* | ||
* @category Random:Common | ||
* @category Random : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -12,4 +14,6 @@ export declare const allowedRandomStringLetters: ReadonlyArray<string>; | ||
* | ||
* @category Random:Common | ||
* @category Random | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function randomString(generatedStringLength?: number): string; |
@@ -5,3 +5,5 @@ import { randomInteger } from './random-integer.js'; | ||
* | ||
* @category Random:Common | ||
* @category Random : Util | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -51,3 +53,5 @@ export const allowedRandomStringLetters = [ | ||
* | ||
* @category Random:Common | ||
* @category Random | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -54,0 +58,0 @@ export function randomString(generatedStringLength = 16) { |
@@ -1,3 +0,56 @@ | ||
export declare function deDupeRegExFlags(flags: string): string; | ||
export declare function addRegExpFlags(originalRegExp: RegExp, flags: string): RegExp; | ||
export declare function makeCaseInsensitiveRegExp(searchForInput: string | RegExp, caseSensitive: boolean): RegExp; | ||
/** | ||
* Creates a new RegExp by adding the given `flags` to the original RegExp. | ||
* | ||
* @category RegExp | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {addRegExpFlags} from '@augment-vir/common'; | ||
* | ||
* addRegExpFlags(/a/i, 'gm'); | ||
* // output is `/a/igm` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function addRegExpFlags(originalRegExpOrString: RegExp | string, flags: string): RegExp; | ||
/** | ||
* Creates a new RegExp with the given `flags`. | ||
* | ||
* @category RegExp | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {setRegExpFlags} from '@augment-vir/common'; | ||
* | ||
* setRegExpFlags(/a/i, 'gm'); | ||
* // output is `/a/gm` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function setRegExpFlags(originalRegExpOrString: RegExp | string, flags: string): RegExp; | ||
/** | ||
* Creates a new RegExp by adding or removing the case insensitivity flag `'i'`, based on the given | ||
* `caseSensitive` input. The first input can also be a string and it will be converted into a | ||
* RegExp. | ||
* | ||
* @category RegExp | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {setRegExpCaseSensitivity} from '@augment-vir/common'; | ||
* | ||
* setRegExpCaseSensitivity(/abc/i, {caseSensitive: true}); // output is `/abc/` | ||
* setRegExpCaseSensitivity(/abc/, {caseSensitive: false}); // output is `/abc/i` | ||
* setRegExpCaseSensitivity('abc', {caseSensitive: true}); // output is `/abc/i` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function setRegExpCaseSensitivity(originalRegExpOrString: string | RegExp, { caseSensitive }: { | ||
caseSensitive: boolean; | ||
}): RegExp; |
@@ -0,18 +1,75 @@ | ||
import { removeDuplicateCharacters } from '../string/remove-duplicate-characters.js'; | ||
import { escapeStringForRegExp } from './regexp-string.js'; | ||
export function deDupeRegExFlags(flags) { | ||
const deDuped = new Set(Array.from(flags.toLowerCase())); | ||
return Array.from(deDuped).join(''); | ||
} | ||
export function addRegExpFlags(originalRegExp, flags) { | ||
return new RegExp(originalRegExp.source, deDupeRegExFlags([ | ||
originalRegExp.flags, | ||
/** | ||
* Creates a new RegExp by adding the given `flags` to the original RegExp. | ||
* | ||
* @category RegExp | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {addRegExpFlags} from '@augment-vir/common'; | ||
* | ||
* addRegExpFlags(/a/i, 'gm'); | ||
* // output is `/a/igm` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function addRegExpFlags(originalRegExpOrString, flags) { | ||
const allFlags = removeDuplicateCharacters([ | ||
typeof originalRegExpOrString === 'string' ? '' : originalRegExpOrString.flags, | ||
flags, | ||
].join(''))); | ||
] | ||
.join('') | ||
.toLowerCase()); | ||
return setRegExpFlags(originalRegExpOrString, allFlags); | ||
} | ||
export function makeCaseInsensitiveRegExp(searchForInput, caseSensitive) { | ||
const regExpFlags = `g${!caseSensitive && typeof searchForInput === 'string' ? 'i' : ''}`; | ||
const searchFor = searchForInput instanceof RegExp | ||
? new RegExp(searchForInput.source, deDupeRegExFlags(`${searchForInput.flags}${regExpFlags}`)) | ||
: new RegExp(escapeStringForRegExp(searchForInput), regExpFlags); | ||
return searchFor; | ||
/** | ||
* Creates a new RegExp with the given `flags`. | ||
* | ||
* @category RegExp | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {setRegExpFlags} from '@augment-vir/common'; | ||
* | ||
* setRegExpFlags(/a/i, 'gm'); | ||
* // output is `/a/gm` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function setRegExpFlags(originalRegExpOrString, flags) { | ||
const allFlags = removeDuplicateCharacters(flags); | ||
if (typeof originalRegExpOrString === 'string') { | ||
return new RegExp(escapeStringForRegExp(originalRegExpOrString), allFlags); | ||
} | ||
else { | ||
return new RegExp(originalRegExpOrString.source, allFlags); | ||
} | ||
} | ||
/** | ||
* Creates a new RegExp by adding or removing the case insensitivity flag `'i'`, based on the given | ||
* `caseSensitive` input. The first input can also be a string and it will be converted into a | ||
* RegExp. | ||
* | ||
* @category RegExp | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {setRegExpCaseSensitivity} from '@augment-vir/common'; | ||
* | ||
* setRegExpCaseSensitivity(/abc/i, {caseSensitive: true}); // output is `/abc/` | ||
* setRegExpCaseSensitivity(/abc/, {caseSensitive: false}); // output is `/abc/i` | ||
* setRegExpCaseSensitivity('abc', {caseSensitive: true}); // output is `/abc/i` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function setRegExpCaseSensitivity(originalRegExpOrString, { caseSensitive }) { | ||
const caseSensitivityFlag = caseSensitive ? '' : 'i'; | ||
return addRegExpFlags(originalRegExpOrString, caseSensitivityFlag); | ||
} |
/** | ||
* Escapes characters from the given string so that it can be used within a RegExp without being | ||
* parsed as RegExp syntax. | ||
* | ||
* @category RegExp | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function escapeStringForRegExp(input: string): string; |
/** | ||
* Escapes characters from the given string so that it can be used within a RegExp without being | ||
* parsed as RegExp syntax. | ||
* | ||
* @category RegExp | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function escapeStringForRegExp(input) { | ||
return input.replace(/[\^$\\.*+?()[\]{}|]/g, String.raw `\$&`); | ||
return input.replaceAll(/[\^$\\.*+?()[\]{}|]/g, String.raw `\$&`); | ||
} |
@@ -5,8 +5,51 @@ import type { AnyObject, Values } from '@augment-vir/core'; | ||
import { TsRecurse, TsRecursionStart, TsRecursionTracker, TsTooMuchRecursion } from '../type/type-recursion.js'; | ||
import { GenericSelectionSet, PickSelection, SelectionSet } from './selection-set.js'; | ||
import { GenericSelectionSet, SelectFrom, SelectionSet } from './selection-set.js'; | ||
/** | ||
* The same as {@link selectFrom} except that the final output is collapsed until the first nested | ||
* value that has more than 1 key or that is not an object. | ||
* | ||
* @category Selection | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {selectCollapsedFrom} from '@augment-vir/common'; | ||
* | ||
* selectCollapsedFrom( | ||
* [ | ||
* { | ||
* child: { | ||
* grandChild: 'hi', | ||
* grandChild2: 3, | ||
* grandChild3: /something/, | ||
* }, | ||
* }, | ||
* { | ||
* child: { | ||
* grandChild: 'hi', | ||
* grandChild2: 4, | ||
* grandChild3: /something/, | ||
* }, | ||
* }, | ||
* ], | ||
* { | ||
* child: { | ||
* grandChild2: true, | ||
* }, | ||
* }, | ||
* ); | ||
* // output is `[3, 4]` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function selectCollapsedFrom<Full extends AnyObject, const Selection extends SelectionSet<NoInfer<Full>>>(originalObject: Readonly<Full>, selectionSet: Readonly<Selection>): PickCollapsedSelection<Full, Selection>; | ||
/** | ||
* Collapses a selected value to the first part of the selection that contains more than 1 key or | ||
* that is not an object. | ||
* that is not an object. This produces the output type for {@link selectCollapsedFrom}. | ||
* | ||
* @category Selection | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type PickCollapsedSelection<Full extends Readonly<AnyObject>, Selection extends SelectionSet<Full>, Depth extends TsRecursionTracker = TsRecursionStart> = Depth extends TsTooMuchRecursion ? 'Error: recursive object depth is too deep.' : KeyCount<ExcludeEmpty<NonNullable<PickSelection<Full, Selection, Depth>>>> extends 1 ? Selection[keyof PickSelection<Full, Selection, Depth>] extends GenericSelectionSet ? PickCollapsedSelection<NonNullable<Full[keyof PickSelection<Full, Selection, Depth>]>, Selection[keyof PickSelection<Full, Selection, Depth>], TsRecurse<Depth>> | Extract<Full[keyof PickSelection<Full, Selection, Depth>], undefined | null> : Values<PickSelection<Full, Selection, Depth>> : PickSelection<Full, Selection, Depth>; | ||
export type PickCollapsedSelection<Full extends Readonly<AnyObject>, Selection extends SelectionSet<Full>, Depth extends TsRecursionTracker = TsRecursionStart> = Depth extends TsTooMuchRecursion ? 'Error: recursive object depth is too deep.' : KeyCount<ExcludeEmpty<NonNullable<SelectFrom<Full, Selection, Depth>>>> extends 1 ? Selection[keyof SelectFrom<Full, Selection, Depth>] extends GenericSelectionSet ? PickCollapsedSelection<NonNullable<Full[keyof SelectFrom<Full, Selection, Depth>]>, Selection[keyof SelectFrom<Full, Selection, Depth>], TsRecurse<Depth>> | Extract<Full[keyof SelectFrom<Full, Selection, Depth>], undefined | null> : Values<SelectFrom<Full, Selection, Depth>> : SelectFrom<Full, Selection, Depth>; |
import { check } from '@augment-vir/assert'; | ||
import { selectFrom } from './select-from.js'; | ||
import { shouldPreserveInSelectionSet, } from './selection-set.js'; | ||
import { selectFrom, shouldPreserveInSelectionSet } from './select-from.js'; | ||
/** | ||
* The same as {@link selectFrom} except that the final output is collapsed until the first nested | ||
* value that has more than 1 key or that is not an object. | ||
* | ||
* @category Selection | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {selectCollapsedFrom} from '@augment-vir/common'; | ||
* | ||
* selectCollapsedFrom( | ||
* [ | ||
* { | ||
* child: { | ||
* grandChild: 'hi', | ||
* grandChild2: 3, | ||
* grandChild3: /something/, | ||
* }, | ||
* }, | ||
* { | ||
* child: { | ||
* grandChild: 'hi', | ||
* grandChild2: 4, | ||
* grandChild3: /something/, | ||
* }, | ||
* }, | ||
* ], | ||
* { | ||
* child: { | ||
* grandChild2: true, | ||
* }, | ||
* }, | ||
* ); | ||
* // output is `[3, 4]` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function selectCollapsedFrom(originalObject, selectionSet) { | ||
@@ -5,0 +43,0 @@ const selected = selectFrom(originalObject, selectionSet); |
import type { AnyObject } from '@augment-vir/core'; | ||
import { PickSelection, SelectionSet } from './selection-set.js'; | ||
export declare function selectFrom<Full extends AnyObject, const Selection extends SelectionSet<NoInfer<Full>>>(originalObject: Readonly<Full>, selectionSet: Readonly<Selection>): PickSelection<Full, Selection>; | ||
import { SelectFrom, SelectionSet } from './selection-set.js'; | ||
/** | ||
* Determine if the given input should be preserved in the selection output, meaning it won't be | ||
* recursed into. | ||
* | ||
* @ignore | ||
*/ | ||
export declare function shouldPreserveInSelectionSet(input: unknown): boolean; | ||
/** | ||
* Performs a SQL-like nested selection on an object, extracting the selected values. | ||
* | ||
* @category Selection | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {selectFrom} from '@augment-vir/common'; | ||
* | ||
* selectFrom( | ||
* [ | ||
* { | ||
* child: { | ||
* grandChild: 'hi', | ||
* grandChild2: 3, | ||
* grandChild3: /something/, | ||
* }, | ||
* }, | ||
* { | ||
* child: { | ||
* grandChild: 'hi', | ||
* grandChild2: 4, | ||
* grandChild3: /something/, | ||
* }, | ||
* }, | ||
* ], | ||
* { | ||
* child: { | ||
* grandChild2: true, | ||
* }, | ||
* }, | ||
* ); | ||
* // output is `[{child: {grandChild2: 3}}, {child: {grandChild2: 4}}]` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function selectFrom<Full extends AnyObject, const Selection extends SelectionSet<NoInfer<Full>>>(originalObject: Readonly<Full>, selectionSet: Readonly<Selection>): SelectFrom<Full, Selection>; |
@@ -0,4 +1,51 @@ | ||
import { check } from '@augment-vir/assert'; | ||
import { mapObjectValues } from '../object/map-values.js'; | ||
import { omitObjectKeys } from '../object/object-keys.js'; | ||
import { shouldPreserveInSelectionSet } from './selection-set.js'; | ||
/** | ||
* Determine if the given input should be preserved in the selection output, meaning it won't be | ||
* recursed into. | ||
* | ||
* @ignore | ||
*/ | ||
export function shouldPreserveInSelectionSet(input) { | ||
return check.isPrimitive(input) || input instanceof RegExp || input instanceof Promise; | ||
} | ||
/** | ||
* Performs a SQL-like nested selection on an object, extracting the selected values. | ||
* | ||
* @category Selection | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {selectFrom} from '@augment-vir/common'; | ||
* | ||
* selectFrom( | ||
* [ | ||
* { | ||
* child: { | ||
* grandChild: 'hi', | ||
* grandChild2: 3, | ||
* grandChild3: /something/, | ||
* }, | ||
* }, | ||
* { | ||
* child: { | ||
* grandChild: 'hi', | ||
* grandChild2: 4, | ||
* grandChild3: /something/, | ||
* }, | ||
* }, | ||
* ], | ||
* { | ||
* child: { | ||
* grandChild2: true, | ||
* }, | ||
* }, | ||
* ); | ||
* // output is `[{child: {grandChild2: 3}}, {child: {grandChild2: 4}}]` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function selectFrom(originalObject, selectionSet) { | ||
@@ -5,0 +52,0 @@ if (Array.isArray(originalObject)) { |
import type { AnyObject } from '@augment-vir/core'; | ||
import { IsAny, IsNever, Primitive, UnionToIntersection } from 'type-fest'; | ||
import { TsRecurse, TsRecursionStart, TsRecursionTracker, TsTooMuchRecursion } from '../type/type-recursion.js'; | ||
export declare function shouldPreserveInSelectionSet(input: unknown): input is SelectionTypesToPreserve; | ||
/** All types that won't be recursed into when defining a {@link SelectionSet}. */ | ||
export type SelectionTypesToPreserve = Primitive | RegExp | Promise<any>; | ||
/** A generic selection set without specific keys. */ | ||
type SelectionTypesToPreserve = Primitive | RegExp | Promise<any>; | ||
/** | ||
* A generic selection set without specific keys. Useful for type parameter baselines. | ||
* | ||
* @category Selection | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type GenericSelectionSet = { | ||
[Key in PropertyKey]: unknown; | ||
}; | ||
/** Masks an object value with the given {@link SelectionSet}. */ | ||
export type PickSelection<Full extends Readonly<AnyObject>, Selection extends SelectionSet<Full>, Depth extends TsRecursionTracker = TsRecursionStart> = Depth extends TsTooMuchRecursion ? ['Error: recursive object depth is too deep.'] : Full extends ReadonlyArray<infer Element extends any> ? (PickSelection<Extract<Element, AnyObject>, Selection, TsRecurse<Depth>> | Exclude<Element, AnyObject>)[] : { | ||
-readonly [Key in keyof Selection as Selection[Key] extends false ? never : Key extends keyof Full ? Key : never]: (Selection[Key] extends GenericSelectionSet ? PickSelection<NonNullable<Extract<Full[Key], AnyObject>>, Selection[Key], TsRecurse<Depth>> : Full[Key]) | Exclude<Full[Key], AnyObject>; | ||
/** | ||
* Performs a SQL-like nested selection on an object, extracting the selected values. This produces | ||
* the output type for `selectFrom`. | ||
* | ||
* @category Selection | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type SelectFrom<Full extends Readonly<AnyObject>, Selection extends SelectionSet<Full>, Depth extends TsRecursionTracker = TsRecursionStart> = Depth extends TsTooMuchRecursion ? ['Error: recursive object depth is too deep.'] : Full extends ReadonlyArray<infer Element extends any> ? (SelectFrom<Extract<Element, AnyObject>, Selection, TsRecurse<Depth>> | Exclude<Element, AnyObject>)[] : { | ||
-readonly [Key in keyof Selection as Selection[Key] extends false ? never : Key extends keyof Full ? Key : never]: (Selection[Key] extends GenericSelectionSet ? SelectFrom<NonNullable<Extract<Full[Key], AnyObject>>, Selection[Key], TsRecurse<Depth>> : Full[Key]) | Exclude<Full[Key], AnyObject>; | ||
}; | ||
/** Defines a selection set for the given object. */ | ||
/** | ||
* Defines a selection set for a given object type. This is used in {@link SelectFrom}. | ||
* | ||
* @category Selection | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type SelectionSet<Full extends Readonly<AnyObject>, Depth extends TsRecursionTracker = TsRecursionStart> = IsAny<Full> extends true ? any : Depth extends TsTooMuchRecursion ? boolean : Full extends ReadonlyArray<infer FullChild extends AnyObject> ? SelectionSet<FullChild, TsRecurse<Depth>> : Partial<{ | ||
[Key in keyof Full]: IsNever<Exclude<Full[Key], SelectionTypesToPreserve>> extends true ? boolean : UnionToIntersection<SelectionSet<NonNullable<Required<Full>[Key]>, TsRecurse<Depth>>> | boolean; | ||
}>; | ||
export {}; |
@@ -1,4 +0,1 @@ | ||
import { check } from '@augment-vir/assert'; | ||
export function shouldPreserveInSelectionSet(input) { | ||
return check.isPrimitive(input) || input instanceof RegExp || input instanceof Promise; | ||
} | ||
export {}; |
import { CasingOptions } from './casing.js'; | ||
export declare function maybeCapitalize(input: string, casingOptions: Partial<CasingOptions>): string; | ||
/** | ||
* Capitalize the first letter of the input _only if_ the given options specifies doing so. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function maybeCapitalize(input: string, casingOptions: Pick<CasingOptions, 'capitalizeFirstLetter'>): string; | ||
/** | ||
* Capitalize the first letter of the input. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function capitalizeFirstLetter<InputGeneric extends string>(input: InputGeneric): Capitalize<InputGeneric>; |
@@ -0,4 +1,18 @@ | ||
/** | ||
* Capitalize the first letter of the input _only if_ the given options specifies doing so. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function maybeCapitalize(input, casingOptions) { | ||
return casingOptions.capitalizeFirstLetter ? capitalizeFirstLetter(input) : input; | ||
} | ||
/** | ||
* Capitalize the first letter of the input. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function capitalizeFirstLetter(input) { | ||
@@ -5,0 +19,0 @@ if (!input.length) { |
import { PartialWithUndefined } from '@augment-vir/core'; | ||
/** | ||
* Options for casing functions in `@augment-vir/common`. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type CasingOptions = { | ||
/** | ||
* Capitalize the first letter of the string. | ||
* | ||
* @default false | ||
*/ | ||
capitalizeFirstLetter: boolean; | ||
}; | ||
/** | ||
* Default options for {@link CasingOptions}. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare const defaultCasingOptions: Required<CasingOptions>; | ||
export declare enum StringCaseEnum { | ||
/** | ||
* The different string cases. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare enum StringCase { | ||
Upper = "upper", | ||
Lower = "lower" | ||
} | ||
/** Indicates whether the given string has different lower and upper case variants. */ | ||
/** | ||
* Indicates whether the given string has different lower and upper case variants. (Some strings | ||
* don't, such as all numbers or `'√'`.) | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function hasCase(input: string): boolean; | ||
/** | ||
* Options for {@link isCase}. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type IsCaseOptions = { | ||
/** | ||
* Fail on characters that don't have different upper and lower case versions (such as | ||
* punctuation, like `'.'` or symbols, like `'√'`). | ||
* Set to `true` to fail on characters that don't have different upper and lower case versions | ||
* (such as punctuation, like `'.'` or symbols, like `'√'`). | ||
* | ||
* @default false | ||
*/ | ||
failOnNoCaseCharacters: boolean; | ||
rejectNoCaseCharacters: boolean; | ||
}; | ||
@@ -25,4 +67,8 @@ /** | ||
* regardless of which `caseType` is provided. To instead return `false` for any such characters, | ||
* pass in an options object and set blockNoCaseCharacters to true. | ||
* pass in an options object and set `rejectNoCaseCharacters` to true. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function isCase(input: string, caseType: StringCaseEnum, options?: PartialWithUndefined<IsCaseOptions>): boolean; | ||
export declare function isCase(input: string, caseType: StringCase, options?: PartialWithUndefined<IsCaseOptions>): boolean; |
@@ -0,10 +1,31 @@ | ||
/** | ||
* Default options for {@link CasingOptions}. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export const defaultCasingOptions = { | ||
capitalizeFirstLetter: false, | ||
}; | ||
export var StringCaseEnum; | ||
(function (StringCaseEnum) { | ||
StringCaseEnum["Upper"] = "upper"; | ||
StringCaseEnum["Lower"] = "lower"; | ||
})(StringCaseEnum || (StringCaseEnum = {})); | ||
/** Indicates whether the given string has different lower and upper case variants. */ | ||
/** | ||
* The different string cases. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export var StringCase; | ||
(function (StringCase) { | ||
StringCase["Upper"] = "upper"; | ||
StringCase["Lower"] = "lower"; | ||
})(StringCase || (StringCase = {})); | ||
/** | ||
* Indicates whether the given string has different lower and upper case variants. (Some strings | ||
* don't, such as all numbers or `'√'`.) | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function hasCase(input) { | ||
@@ -19,6 +40,10 @@ return input.toLowerCase() !== input.toUpperCase(); | ||
* regardless of which `caseType` is provided. To instead return `false` for any such characters, | ||
* pass in an options object and set blockNoCaseCharacters to true. | ||
* pass in an options object and set `rejectNoCaseCharacters` to true. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function isCase(input, caseType, options) { | ||
if (!input && options?.failOnNoCaseCharacters) { | ||
if (!input && options?.rejectNoCaseCharacters) { | ||
return false; | ||
@@ -28,3 +53,3 @@ } | ||
if (!hasCase(letter)) { | ||
if (options?.failOnNoCaseCharacters) { | ||
if (options?.rejectNoCaseCharacters) { | ||
return false; | ||
@@ -36,4 +61,4 @@ } | ||
} | ||
else if ((caseType === StringCaseEnum.Upper && letter !== letter.toUpperCase()) || | ||
(caseType === StringCaseEnum.Lower && letter !== letter.toLowerCase())) { | ||
else if ((caseType === StringCase.Upper && letter !== letter.toUpperCase()) || | ||
(caseType === StringCase.Lower && letter !== letter.toLowerCase())) { | ||
return false; | ||
@@ -40,0 +65,0 @@ } |
import { CasingOptions } from './casing.js'; | ||
/** | ||
* Converts a kebab-case string to CamelCase. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function kebabCaseToCamelCase(rawKebabCase: string, casingOptions?: Partial<CasingOptions> | undefined): string; | ||
/** | ||
* Converts a CamelCase string to kebab-case. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function camelCaseToKebabCase(rawCamelCase: string): string; |
@@ -0,4 +1,12 @@ | ||
import { mergeDefinedProperties } from '../../object/merge-defined-properties.js'; | ||
import { maybeCapitalize } from './capitalization.js'; | ||
import { defaultCasingOptions, isCase, StringCaseEnum } from './casing.js'; | ||
export function kebabCaseToCamelCase(rawKebabCase, casingOptions = defaultCasingOptions) { | ||
import { defaultCasingOptions, isCase, StringCase } from './casing.js'; | ||
/** | ||
* Converts a kebab-case string to CamelCase. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function kebabCaseToCamelCase(rawKebabCase, casingOptions = {}) { | ||
const kebabCase = rawKebabCase.toLowerCase(); | ||
@@ -20,4 +28,11 @@ if (!kebabCase.length) { | ||
}); | ||
return maybeCapitalize(camelCase, casingOptions); | ||
return maybeCapitalize(camelCase, mergeDefinedProperties(defaultCasingOptions, casingOptions)); | ||
} | ||
/** | ||
* Converts a CamelCase string to kebab-case. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function camelCaseToKebabCase(rawCamelCase) { | ||
@@ -29,4 +44,4 @@ const kebabCase = rawCamelCase | ||
const nextLetter = index < originalString.length - 1 ? originalString[index + 1] || '' : ''; | ||
const possibleWordBoundary = isCase(previousLetter, StringCaseEnum.Lower, { failOnNoCaseCharacters: true }) || | ||
isCase(nextLetter, StringCaseEnum.Lower, { failOnNoCaseCharacters: true }); | ||
const possibleWordBoundary = isCase(previousLetter, StringCase.Lower, { rejectNoCaseCharacters: true }) || | ||
isCase(nextLetter, StringCase.Lower, { rejectNoCaseCharacters: true }); | ||
if (currentLetter === currentLetter.toLowerCase() || | ||
@@ -33,0 +48,0 @@ index === 0 || |
@@ -6,6 +6,17 @@ /** | ||
* | ||
* @param list Array of items to be converted into strings. Works best if these are simply strings | ||
* to begin with. | ||
* @param conjunction Defaults to 'and'. The conjunction to be used before the final element. | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function joinWithFinalConjunction(list: ReadonlyArray<any>, conjunction?: string): string; | ||
export declare function joinWithFinalConjunction( | ||
/** | ||
* Array of items to be converted into strings. Works best if these are simply strings to begin | ||
* with. | ||
*/ | ||
list: ReadonlyArray<any>, | ||
/** | ||
* The conjunction to be used before the final element. | ||
* | ||
* @default 'and' | ||
*/ | ||
conjunction?: string): string; |
@@ -6,7 +6,18 @@ /** | ||
* | ||
* @param list Array of items to be converted into strings. Works best if these are simply strings | ||
* to begin with. | ||
* @param conjunction Defaults to 'and'. The conjunction to be used before the final element. | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function joinWithFinalConjunction(list, conjunction = 'and') { | ||
export function joinWithFinalConjunction( | ||
/** | ||
* Array of items to be converted into strings. Works best if these are simply strings to begin | ||
* with. | ||
*/ | ||
list, | ||
/** | ||
* The conjunction to be used before the final element. | ||
* | ||
* @default 'and' | ||
*/ | ||
conjunction = 'and') { | ||
if (list.length < 2) { | ||
@@ -13,0 +24,0 @@ /** |
@@ -5,2 +5,4 @@ /** | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -12,2 +14,4 @@ export type WithPrefix<Prefix extends string> = `${Prefix}${string}`; | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -22,2 +26,4 @@ export declare function addPrefix<const Prefix extends string>({ value, prefix, }: { | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -24,0 +30,0 @@ export declare function removePrefix<const Prefix extends string>({ value, prefix, }: { |
@@ -5,2 +5,4 @@ /** | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -19,2 +21,4 @@ export function addPrefix({ value, prefix, }) { | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -21,0 +25,0 @@ export function removePrefix({ value, prefix, }) { |
@@ -0,1 +1,18 @@ | ||
/** | ||
* Replaces whatever substring is at the given index in the original string with the new string. | ||
* Optionally, provide a length of the substring to get replaced. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {replaceStringAtIndex} from '@augment-vir/common'; | ||
* | ||
* replaceStringAtIndex('eat the waffles', 4, 'his'); // outputs `'eat his waffles'` | ||
* replaceStringAtIndex('eat the waffles', 4, 'my', 3); // outputs `'eat my waffles'` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function replaceStringAtIndex(originalString: string, start: number, newString: string, length?: number): string; |
@@ -0,1 +1,18 @@ | ||
/** | ||
* Replaces whatever substring is at the given index in the original string with the new string. | ||
* Optionally, provide a length of the substring to get replaced. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {replaceStringAtIndex} from '@augment-vir/common'; | ||
* | ||
* replaceStringAtIndex('eat the waffles', 4, 'his'); // outputs `'eat his waffles'` | ||
* replaceStringAtIndex('eat the waffles', 4, 'my', 3); // outputs `'eat my waffles'` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function replaceStringAtIndex(originalString, start, newString, length = newString.length) { | ||
@@ -2,0 +19,0 @@ const before = originalString.slice(0, Math.max(0, start)); |
import type { AtLeastTuple } from '@augment-vir/core'; | ||
/** Same as String.prototype.split but includes the delimiter to split by in the output array. */ | ||
export declare function splitIncludeSplit(original: string, splitterInput: string | RegExp, caseSensitive: boolean): readonly string[]; | ||
/** | ||
* Same as * | ||
* [`''.split`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/split) | ||
* but includes the split delimiter in the output array. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {splitIncludeSplit} from '@augment-vir/common'; | ||
* | ||
* splitIncludeSplit('1,2,3', ',', {caseSensitive: false}); // outputs `['1', ',', '2', ',', '3']` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function splitIncludeSplit(original: string, splitDelimiter: string | RegExp, { caseSensitive }: { | ||
caseSensitive: boolean; | ||
}): readonly string[]; | ||
/** | ||
* Same as | ||
* [`''.split`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/split) | ||
* but typed better: it always returns an array with at least one string. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function safeSplit(input: string, splitString: string): AtLeastTuple<string, 1>; |
@@ -1,12 +0,28 @@ | ||
import { makeCaseInsensitiveRegExp } from '../regexp/regexp-flags.js'; | ||
import { getSubstringIndexes } from './substring-index.js'; | ||
/** Same as String.prototype.split but includes the delimiter to split by in the output array. */ | ||
export function splitIncludeSplit(original, splitterInput, caseSensitive) { | ||
const indexLengths = getSubstringIndexes({ | ||
import { setRegExpCaseSensitivity } from '../regexp/regexp-flags.js'; | ||
import { findSubstringIndexes } from './substring-index.js'; | ||
/** | ||
* Same as * | ||
* [`''.split`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/split) | ||
* but includes the split delimiter in the output array. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {splitIncludeSplit} from '@augment-vir/common'; | ||
* | ||
* splitIncludeSplit('1,2,3', ',', {caseSensitive: false}); // outputs `['1', ',', '2', ',', '3']` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function splitIncludeSplit(original, splitDelimiter, { caseSensitive }) { | ||
const indexLengths = findSubstringIndexes({ | ||
searchIn: original, | ||
searchFor: splitterInput, | ||
searchFor: splitDelimiter, | ||
caseSensitive, | ||
includeLength: true, | ||
}); | ||
const splitter = makeCaseInsensitiveRegExp(splitterInput, caseSensitive); | ||
const splitter = setRegExpCaseSensitivity(splitDelimiter, { caseSensitive }); | ||
const splits = original.split(splitter); | ||
@@ -26,4 +42,13 @@ return splits.reduce((accum, current, index) => { | ||
} | ||
/** | ||
* Same as | ||
* [`''.split`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/split) | ||
* but typed better: it always returns an array with at least one string. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function safeSplit(input, splitString) { | ||
return input.split(splitString); | ||
} |
@@ -1,9 +0,15 @@ | ||
export declare function getSubstringIndexes<IncludeLength extends boolean | undefined>({ searchIn, searchFor, caseSensitive, includeLength, }: { | ||
/** | ||
* Finds all indexes of a `searchFor` string or RegExp in `searchIn`. Ths is similar to | ||
* [`''.indexOf`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) | ||
* except that it finds _all_ indexes of. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function findSubstringIndexes<IncludeLength extends boolean | undefined>({ searchIn, searchFor, caseSensitive, includeLength, }: { | ||
searchIn: string; | ||
searchFor: string | RegExp; | ||
/** | ||
* CaseSensitive only applies when the input is a string. Otherwise, the RegExp's "i" flag is | ||
* used to determine case sensitivity. | ||
*/ | ||
caseSensitive: boolean; | ||
/** Set to true to get an array of objects with the found indexes _and_ their lengths. */ | ||
includeLength?: IncludeLength; | ||
@@ -10,0 +16,0 @@ }): IncludeLength extends true ? { |
@@ -1,4 +0,13 @@ | ||
import { makeCaseInsensitiveRegExp } from '../regexp/regexp-flags.js'; | ||
export function getSubstringIndexes({ searchIn, searchFor, caseSensitive, includeLength, }) { | ||
const searchRegExp = makeCaseInsensitiveRegExp(searchFor, caseSensitive); | ||
import { addRegExpFlags, setRegExpCaseSensitivity } from '../regexp/regexp-flags.js'; | ||
/** | ||
* Finds all indexes of a `searchFor` string or RegExp in `searchIn`. Ths is similar to | ||
* [`''.indexOf`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) | ||
* except that it finds _all_ indexes of. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function findSubstringIndexes({ searchIn, searchFor, caseSensitive, includeLength, }) { | ||
const searchRegExp = addRegExpFlags(setRegExpCaseSensitivity(searchFor, { caseSensitive }), 'g'); | ||
const indexes = []; | ||
@@ -5,0 +14,0 @@ const indexesAndLengths = []; |
@@ -5,2 +5,4 @@ /** | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -12,2 +14,4 @@ export type WithSuffix<Suffix extends string> = `${string}${Suffix}`; | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -19,2 +23,4 @@ export declare const percentSuffix = "%"; | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -26,2 +32,4 @@ export declare const pxSuffix = "px"; | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -33,2 +41,4 @@ export type WithPx = WithSuffix<typeof pxSuffix>; | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -40,2 +50,4 @@ export type WithPercent = WithSuffix<typeof percentSuffix>; | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -47,3 +59,5 @@ export declare function addPx(input: number | string): WithPx; | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @throws `TypeError` if the input can't be converted into a number. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -55,2 +69,4 @@ export declare function removePx(input: string): number; | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -62,3 +78,5 @@ export declare function addPercent(input: number | string): WithPercent; | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @throws `TypeError` if the input can't be converted into a number. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -70,2 +88,4 @@ export declare function removePercent(input: string): number; | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -80,2 +100,4 @@ export declare function addSuffix<const Suffix extends string>({ value, suffix, }: { | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -82,0 +104,0 @@ export declare function removeSuffix<const Suffix extends string>({ value, suffix, }: { |
@@ -6,2 +6,4 @@ import { toEnsuredNumber } from '../number/number-conversion.js'; | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -13,2 +15,4 @@ export const percentSuffix = '%'; | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -20,2 +24,4 @@ export const pxSuffix = 'px'; | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -29,3 +35,5 @@ export function addPx(input) { | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @throws `TypeError` if the input can't be converted into a number. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -39,2 +47,4 @@ export function removePx(input) { | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -48,3 +58,5 @@ export function addPercent(input) { | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @throws `TypeError` if the input can't be converted into a number. | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -58,2 +70,4 @@ export function removePercent(input) { | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -72,2 +86,4 @@ export function addSuffix({ value, suffix, }) { | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -74,0 +90,0 @@ export function removeSuffix({ value, suffix, }) { |
import { PartialWithUndefined } from '@augment-vir/core'; | ||
/** Collapse all consecutive white space into just one space and trim surrounding whitespace. */ | ||
/** | ||
* Collapse all consecutive white space into just one space and trim surrounding whitespace. | ||
* Optionally, collapsed newlines can be preserved. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function collapseWhiteSpace(input: string, { keepNewLines }?: PartialWithUndefined<{ | ||
keepNewLines: boolean; | ||
}>): string; |
@@ -1,2 +0,9 @@ | ||
/** Collapse all consecutive white space into just one space and trim surrounding whitespace. */ | ||
/** | ||
* Collapse all consecutive white space into just one space and trim surrounding whitespace. | ||
* Optionally, collapsed newlines can be preserved. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function collapseWhiteSpace(input, { keepNewLines } = {}) { | ||
@@ -3,0 +10,0 @@ if (keepNewLines) { |
@@ -0,1 +1,16 @@ | ||
/** | ||
* Wraps a string in another string. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {wrapString} from '@augment-vir/common'; | ||
* | ||
* wrapString({value: 'some words', wrapper: '"'}); // outputs `'"some words"'` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function wrapString({ value, wrapper }: { | ||
@@ -2,0 +17,0 @@ value: string; |
import { addPrefix } from './prefix.js'; | ||
import { addSuffix } from './suffix.js'; | ||
/** | ||
* Wraps a string in another string. | ||
* | ||
* @category String | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import {wrapString} from '@augment-vir/common'; | ||
* | ||
* wrapString({value: 'some words', wrapper: '"'}); // outputs `'"some words"'` | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function wrapString({ value, wrapper }) { | ||
return addPrefix({ value: addSuffix({ value, suffix: wrapper }), prefix: wrapper }); | ||
} |
@@ -7,3 +7,7 @@ /** | ||
* input. | ||
* | ||
* @category Type | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function ensureType<ExpectedType = never>(input: NoInfer<ExpectedType>): NoInfer<ExpectedType>; |
@@ -7,2 +7,6 @@ /** | ||
* input. | ||
* | ||
* @category Type | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
@@ -9,0 +13,0 @@ export function ensureType(input) { |
export type { ReadonlyDeep } from 'type-fest'; | ||
/** | ||
* This function does nothing but return the input as a readonly typed version of itself. | ||
* | ||
* @category Type | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function makeReadonly<T>(input: T): Readonly<T>; |
@@ -0,3 +1,10 @@ | ||
/** | ||
* This function does nothing but return the input as a readonly typed version of itself. | ||
* | ||
* @category Type | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function makeReadonly(input) { | ||
return input; | ||
} |
@@ -153,10 +153,102 @@ type TsRecursionArray = [ | ||
]; | ||
/** | ||
* This is used as the baseline type for TypeScript recursion tracking indexes. Use this to manually | ||
* abort a type's recursion to prevent it from going too deep and throwing an error in TypeScript's | ||
* language server. | ||
* | ||
* @category Type | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import type { | ||
* TsRecursionTracker, | ||
* TsRecursionStart, | ||
* TsRecurse, | ||
* TsTooMuchRecursion, | ||
* } from '@augment-vir/common'; | ||
* | ||
* export type SomeType<Depth extends TsRecursionTracker = TsRecursionStart> = | ||
* Depth extends TsTooMuchRecursion | ||
* ? 'Error: recursive object depth is too deep.' | ||
* : SomeType<TsRecurse<Depth>>; | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type TsRecursionTracker = keyof TsRecursionArray; | ||
/** | ||
* Through experimentation on Typescript version 5.4.5, this is the maximum recursion depth we can | ||
* go to before TypeScript will block recursive types. | ||
* go to before TypeScript will block recursive types. Use this as the limit to type recursion. | ||
* | ||
* @category Type | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import type { | ||
* TsRecursionTracker, | ||
* TsRecursionStart, | ||
* TsRecurse, | ||
* TsTooMuchRecursion, | ||
* } from '@augment-vir/common'; | ||
* | ||
* export type SomeType<Depth extends TsRecursionTracker = TsRecursionStart> = | ||
* Depth extends TsTooMuchRecursion | ||
* ? 'Error: recursive object depth is too deep.' | ||
* : SomeType<TsRecurse<Depth>>; | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type TsTooMuchRecursion = 91; | ||
/** | ||
* This is the default starting recursion depth needed to get the full tested allowed recursion | ||
* depth. | ||
* | ||
* @category Type | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import type { | ||
* TsRecursionTracker, | ||
* TsRecursionStart, | ||
* TsRecurse, | ||
* TsTooMuchRecursion, | ||
* } from '@augment-vir/common'; | ||
* | ||
* export type SomeType<Depth extends TsRecursionTracker = TsRecursionStart> = | ||
* Depth extends TsTooMuchRecursion | ||
* ? 'Error: recursive object depth is too deep.' | ||
* : SomeType<TsRecurse<Depth>>; | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type TsRecursionStart = 0; | ||
/** | ||
* Increments a TypeScript recursion depth tracker. | ||
* | ||
* @category Type | ||
* @category Package : @augment-vir/common | ||
* @example | ||
* | ||
* ```ts | ||
* import type { | ||
* TsRecursionTracker, | ||
* TsRecursionStart, | ||
* TsRecurse, | ||
* TsTooMuchRecursion, | ||
* } from '@augment-vir/common'; | ||
* | ||
* export type SomeType<Depth extends TsRecursionTracker = TsRecursionStart> = | ||
* Depth extends TsTooMuchRecursion | ||
* ? 'Error: recursive object depth is too deep.' | ||
* : SomeType<TsRecurse<Depth>>; | ||
* ``` | ||
* | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type TsRecurse<CurrentRecursion extends TsRecursionTracker> = TsRecursionArray[CurrentRecursion] extends TsRecursionTracker ? TsRecursionArray[CurrentRecursion] : TsTooMuchRecursion; | ||
export {}; |
/** | ||
* Require that the NonVoid parameter is not void. If it is void, the ErrorType or an error string | ||
* type is returned. If it not void, the given SuccessType is returned. | ||
* Require that the given `NonVoid` parameter is not void. If it is void, the `ErrorType` or an | ||
* error string type is returned. If it not void, the given `SuccessType` is returned. | ||
* | ||
* @category Type | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export type RequireNonVoid<NonVoid, SuccessType, ErrorType = 'Input should not be void'> = void extends NonVoid ? (NonVoid extends void ? ErrorType : SuccessType) : SuccessType; |
import type { Writable } from 'type-fest'; | ||
export type { Writable, WritableDeep } from 'type-fest'; | ||
/** | ||
* This function does nothing but return the input as a writable typed version of itself. | ||
* | ||
* @category Type | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export declare function makeWritable<T>(input: T): Writable<T>; |
@@ -0,3 +1,10 @@ | ||
/** | ||
* This function does nothing but return the input as a writable typed version of itself. | ||
* | ||
* @category Type | ||
* @category Package : @augment-vir/common | ||
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) | ||
*/ | ||
export function makeWritable(input) { | ||
return input; | ||
} |
@@ -11,7 +11,5 @@ export * from './augments/array/array-map.js'; | ||
export * from './augments/array/string-array.js'; | ||
export * from './augments/boolean/if-truthy.js'; | ||
export * from './augments/core-exports.js'; | ||
export * from './augments/enum/enum-value-check.js'; | ||
export * from './augments/error/combine-errors.js'; | ||
export * from './augments/file/esm-path.js'; | ||
export * from './augments/function/call-asynchronously.js'; | ||
@@ -21,2 +19,3 @@ export * from './augments/function/call-with-retries.js'; | ||
export * from './augments/function/execution-duration.js'; | ||
export * from './augments/function/if-truthy.js'; | ||
export * from './augments/function/wrap-in-try.js'; | ||
@@ -56,2 +55,3 @@ export * from './augments/json/append-json.js'; | ||
export * from './augments/object/object-values.js'; | ||
export * from './augments/path/esm-path.js'; | ||
export * from './augments/prisma/prisma-models.js'; | ||
@@ -62,5 +62,5 @@ export * from './augments/promise/timed-promise.js'; | ||
export * from './augments/random/random-string.js'; | ||
export * from './augments/regexp/match.js'; | ||
export * from './augments/regexp/regexp-flags.js'; | ||
export * from './augments/regexp/regexp-string.js'; | ||
export * from './augments/regexp/safe-match.js'; | ||
export * from './augments/selection-set/select-collapsed.js'; | ||
@@ -72,5 +72,6 @@ export * from './augments/selection-set/select-from.js'; | ||
export * from './augments/string/casing/kebab-and-camel.js'; | ||
export * from './augments/string/commas.js'; | ||
export * from './augments/string/comma.js'; | ||
export * from './augments/string/join.js'; | ||
export * from './augments/string/prefix.js'; | ||
export * from './augments/string/remove-duplicate-characters.js'; | ||
export * from './augments/string/replace.js'; | ||
@@ -85,3 +86,4 @@ export * from './augments/string/split.js'; | ||
export * from './augments/type/type-recursion.js'; | ||
export * from './augments/type/union.js'; | ||
export * from './augments/type/void-type.js'; | ||
export * from './augments/type/writable.js'; |
@@ -11,7 +11,5 @@ export * from './augments/array/array-map.js'; | ||
export * from './augments/array/string-array.js'; | ||
export * from './augments/boolean/if-truthy.js'; | ||
export * from './augments/core-exports.js'; | ||
export * from './augments/enum/enum-value-check.js'; | ||
export * from './augments/error/combine-errors.js'; | ||
export * from './augments/file/esm-path.js'; | ||
export * from './augments/function/call-asynchronously.js'; | ||
@@ -21,2 +19,3 @@ export * from './augments/function/call-with-retries.js'; | ||
export * from './augments/function/execution-duration.js'; | ||
export * from './augments/function/if-truthy.js'; | ||
export * from './augments/function/wrap-in-try.js'; | ||
@@ -56,2 +55,3 @@ export * from './augments/json/append-json.js'; | ||
export * from './augments/object/object-values.js'; | ||
export * from './augments/path/esm-path.js'; | ||
export * from './augments/prisma/prisma-models.js'; | ||
@@ -62,5 +62,5 @@ export * from './augments/promise/timed-promise.js'; | ||
export * from './augments/random/random-string.js'; | ||
export * from './augments/regexp/match.js'; | ||
export * from './augments/regexp/regexp-flags.js'; | ||
export * from './augments/regexp/regexp-string.js'; | ||
export * from './augments/regexp/safe-match.js'; | ||
export * from './augments/selection-set/select-collapsed.js'; | ||
@@ -72,5 +72,6 @@ export * from './augments/selection-set/select-from.js'; | ||
export * from './augments/string/casing/kebab-and-camel.js'; | ||
export * from './augments/string/commas.js'; | ||
export * from './augments/string/comma.js'; | ||
export * from './augments/string/join.js'; | ||
export * from './augments/string/prefix.js'; | ||
export * from './augments/string/remove-duplicate-characters.js'; | ||
export * from './augments/string/replace.js'; | ||
@@ -85,3 +86,4 @@ export * from './augments/string/split.js'; | ||
export * from './augments/type/type-recursion.js'; | ||
export * from './augments/type/union.js'; | ||
export * from './augments/type/void-type.js'; | ||
export * from './augments/type/writable.js'; |
{ | ||
"name": "@augment-vir/common", | ||
"version": "30.0.0", | ||
"version": "30.0.1", | ||
"description": "A collection of augments, helpers types, functions, and classes for any JavaScript environment.", | ||
"keywords": [ | ||
"augment", | ||
"helper", | ||
"util", | ||
"node", | ||
"browser", | ||
"backend", | ||
"frontend", | ||
"vir", | ||
"augment-vir" | ||
], | ||
"homepage": "https://github.com/electrovir/augment-vir", | ||
@@ -23,6 +35,4 @@ "bugs": { | ||
"compile": "virmator compile", | ||
"docs": "virmator docs", | ||
"test": "concurrently --colors --kill-others-on-fail -c red,blue --names node,web \"npm run test:node\" \"npm run test:web\"", | ||
"test:coverage": "virmator --no-deps test web coverage", | ||
"test:docs": "virmator docs check", | ||
"test:node": "virmator --no-deps test node", | ||
@@ -33,4 +43,4 @@ "test:update": "npm test", | ||
"dependencies": { | ||
"@augment-vir/assert": "^30.0.0", | ||
"@augment-vir/core": "^30.0.0", | ||
"@augment-vir/assert": "^30.0.1", | ||
"@augment-vir/core": "^30.0.1", | ||
"@date-vir/duration": "^6.0.0", | ||
@@ -37,0 +47,0 @@ "ansi-styles": "^6.2.1", |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
No README
QualityPackage does not have a README. This may indicate a failed publish or a low quality package.
Found 1 instance in 1 package
223405
172
6223
0
12
0
Updated@augment-vir/assert@^30.0.1
Updated@augment-vir/core@^30.0.1