[@cahil/utils](README.md) › [Globals](globals.md)

# @cahil/utils

## Index

### Classes

* [CancelablePromise](classes/cancelablepromise.md)

### Interfaces

* [BatchTestOptions](interfaces/batchtestoptions.md)
* [CancelableWrappedPromise](interfaces/cancelablewrappedpromise.md)
* [CloneOptions](interfaces/cloneoptions.md)
* [ToCamelOptions](interfaces/tocameloptions.md)

### Variables

* [push](globals.md#push)

### Functions

* [batchTest](globals.md#batchtest)
* [buildCaseArray](globals.md#buildcasearray)
* [camelToTitle](globals.md#cameltotitle)
* [capitalize](globals.md#capitalize)
* [clone](globals.md#clone)
* [ensureNextSectionIsValid](globals.md#private-ensurenextsectionisvalid)
* [filterBy](globals.md#filterby)
* [flatMap](globals.md#flatmap)
* [flatten](globals.md#flatten)
* [get](globals.md#get)
* [getAcronym](globals.md#getacronym)
* [isNonEmptyString](globals.md#isnonemptystring)
* [isValidEmail](globals.md#isvalidemail)
* [isValidURL](globals.md#isvalidurl)
* [makeCancelable](globals.md#makecancelable)
* [noramlizeURL](globals.md#noramlizeurl)
* [normalizeProtocol](globals.md#private-normalizeprotocol)
* [normalizeSectionSlashes](globals.md#private-normalizesectionslashes)
* [partial](globals.md#partial)
* [partitionArray](globals.md#partitionarray)
* [pause](globals.md#pause)
* [pick](globals.md#pick)
* [runTest](globals.md#runtest)
* [set](globals.md#set)
* [toCamel](globals.md#tocamel)
* [toProperList](globals.md#toproperlist)
* [updateItem](globals.md#updateitem)

### Object literals

* [canceledError](globals.md#const-cancelederror)

## Variables

###  push

• **push**: *push*

*Defined in [src/array/flatMap.ts:5](https://github.com/cahilfoley/utils/blob/22bd396/src/array/flatMap.ts#L5)*

## Functions

###  batchTest

▸ **batchTest**(`func`: function, `cases`: any[][], `__namedParameters`: object): *void*

*Defined in [src/tests/batchTest.ts:35](https://github.com/cahilfoley/utils/blob/22bd396/src/tests/batchTest.ts#L35)*

Utility function for running batches of tests with a single call

**`example`** 
```typescript

batchTest(double, [[2, 4], [5, 10]])
```

**Parameters:**

▪ **func**: *function*

The function to test

▸ (...`args`: any[]): *any*

**Parameters:**

Name | Type |
------ | ------ |
`...args` | any[] |

▪ **cases**: *any[][]*

An array of test case tuples (inputs and expected outputs)

▪`Default value`  **__namedParameters**: *object*=  {}

Name | Type |
------ | ------ |
`runner` | function |
`verb` | string |

**Returns:** *void*

___

###  buildCaseArray

▸ **buildCaseArray**(`testInputs`: any[], `output`: any): *any[][]*

*Defined in [src/tests/buildCaseArray.ts:20](https://github.com/cahilfoley/utils/blob/22bd396/src/tests/buildCaseArray.ts#L20)*

Builds an array of test cases with a common output

**`example`** 
```typescript

const evenTests = [...buildCaseArray([2, 4, 6], true), ...buildCaseArray([1, 3, 5], false)]
```

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`testInputs` | any[] | An array of test inputs to build into the case array |
`output` | any | The single output that should be paired with every input |

**Returns:** *any[][]*

Returns the array of test cases

___

###  camelToTitle

▸ **camelToTitle**(`input`: string): *string*

*Defined in [src/transforms/camelToTitle.ts:36](https://github.com/cahilfoley/utils/blob/22bd396/src/transforms/camelToTitle.ts#L36)*

Transforms the provided camel-case string to title case using rules from
[capitalizemytitle.com](https://capitalizemytitle.com/#)

When to capitalize:
- Capitalize the first word in the title
- Capitalize the last word in the title

When not to capitalize
- articles (a, an, the)
- coordinating conjuctions (and, but, for)
- short prepositions (less than 5 letters - at, by, from)

When one of the above conditions is not met then the word is assumed to be some other important word
and it is capitalized

**`example`** 
```typescript

camelToTitle('iLoveCamels') // => 'I Love Camels'
```

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`input` | string | The camel-case string to be converted |

**Returns:** *string*

Returns the transformed title case string

___

###  capitalize

▸ **capitalize**(`text`: string): *string*

*Defined in [src/transforms/capitalize.ts:19](https://github.com/cahilfoley/utils/blob/22bd396/src/transforms/capitalize.ts#L19)*

Capitalize the first letter of a string

**`example`** 
```typescript

const name = capitalize('bob') // => 'Bob'
```

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`text` | string | The string to be capitalized |

**Returns:** *string*

Returns the capitalized string

___

###  clone

▸ **clone**<**T**>(`original`: T, `options?`: [CloneOptions](interfaces/cloneoptions.md)): *T*

*Defined in [src/accessors/clone.ts:23](https://github.com/cahilfoley/utils/blob/22bd396/src/accessors/clone.ts#L23)*

Creates a deep clone of a value

**Type parameters:**

▪ **T**

The type of the original value

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`original` | T | The value to clone |
`options?` | [CloneOptions](interfaces/cloneoptions.md) | Config options |

**Returns:** *T*

Returns the deep cloned value

___

### `Private` ensureNextSectionIsValid

▸ **ensureNextSectionIsValid**(`__namedParameters`: [string, string], `object`: any): *void*

*Defined in [src/accessors/set.ts:11](https://github.com/cahilfoley/utils/blob/22bd396/src/accessors/set.ts#L11)*

Creates an array/object as the next property if required

**Parameters:**

Name | Type |
------ | ------ |
`__namedParameters` | [string, string] |
`object` | any |

**Returns:** *void*

___

###  filterBy

▸ **filterBy**(`array`: object[], `path`: string | string[], `value`: any): *object[]*

*Defined in [src/array/filterBy.ts:17](https://github.com/cahilfoley/utils/blob/22bd396/src/array/filterBy.ts#L17)*

 Allows filtering of an array by querying a property with a getter path instead of a callback function.

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`array` | object[] | The array of object to filter |
`path` | string &#124; string[] | The path of the property to filter |
`value` | any | The value of the property to filter |

**Returns:** *object[]*

Array filtered according to property and past value

___

###  flatMap

▸ **flatMap**<**TValue**, **TNext**>(`array`: TValue[], `fn`: function): *TNext[]*

*Defined in [src/array/flatMap.ts:25](https://github.com/cahilfoley/utils/blob/22bd396/src/array/flatMap.ts#L25)*

Calls a function on every item in an array and concatenates the resulting arrays into a single flat array.

**`example`** 
```typescript

const items = flatMap(['foo', 'bar'], word => word.split())
// Returns ['f', 'o', 'o', 'b', 'a', 'r']
```

**Type parameters:**

▪ **TValue**

The type of items in the input array

▪ **TNext**

the type of items in the output array

**Parameters:**

▪ **array**: *TValue[]*

The input array to be mapped

▪ **fn**: *function*

The functions used to generate the new items

▸ (`value`: TValue, `index?`: number): *TNext[]*

**Parameters:**

Name | Type |
------ | ------ |
`value` | TValue |
`index?` | number |

**Returns:** *TNext[]*

A flat array of the resulting values

___

###  flatten

▸ **flatten**<**T**>(`array`: T | T[] | T[][][], `depth`: number): *T[]*

*Defined in [src/array/flatten.ts:22](https://github.com/cahilfoley/utils/blob/22bd396/src/array/flatten.ts#L22)*

Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

**`example`** 
```typescript

flatten<number>([1, [2, 3], 4, [5, [6, 7] ], 8])
// Expected output: [1, 2, 3, 4, 5, 6, 7, 8]
```

**Type parameters:**

▪ **T**

The type of the items in the array, specify this type parameter to avoid type widening on deeply nested arrays

**Parameters:**

Name | Type | Default | Description |
------ | ------ | ------ | ------ |
`array` | T &#124; T[] &#124; T[][][] | - | The array to be flattened. |
`depth` | number |  Infinity | The depth level specifying how deep a nested array structure should be flattened. Defaults to `Infinity`. |

**Returns:** *T[]*

The flattened array.

___

###  get

▸ **get**<**T**>(`object`: object, `path`: string[] | string, `defaultValue?`: T): *T*

*Defined in [src/accessors/get.ts:17](https://github.com/cahilfoley/utils/blob/22bd396/src/accessors/get.ts#L17)*

Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.

**Type parameters:**

▪ **T**

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`object` | object | The object to query |
`path` | string[] &#124; string | The path of the property to get |
`defaultValue?` | T | The value returned for undefined resolved values |

**Returns:** *T*

The value if it exists, if not then either the default value is returned or undefined

___

###  getAcronym

▸ **getAcronym**(`title`: string): *string*

*Defined in [src/transforms/getAcronym.ts:23](https://github.com/cahilfoley/utils/blob/22bd396/src/transforms/getAcronym.ts#L23)*

Condense a provided string into a 2 or 3 letter acronym using the following rules
- If there is only a single word return the first 3 letters
- If there are more than 3 words filter out articles, conjunctions and short prepositions

**`example`** 
```typescript

const acronym = getAcronym('Empire Strikes Back') // => 'ESB'
```

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`title` | string | The string to convert to an acronym |

**Returns:** *string*

Returns the acronym string

___

###  isNonEmptyString

▸ **isNonEmptyString**(`text`: string): *boolean*

*Defined in [src/validation/isNonEmptyString.ts:20](https://github.com/cahilfoley/utils/blob/22bd396/src/validation/isNonEmptyString.ts#L20)*

Checks if a value provided is of type string and has a non-zero length. If the value is not a string
or it is an empty string then the function returns false

**`example`** 
```typescript

const valid = isNonEmptyString('hello') // => true
```

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`text` | string | The text to validate |

**Returns:** *boolean*

True if the value is an empty string, false otherwise

___

###  isValidEmail

▸ **isValidEmail**(`text`: string): *boolean*

*Defined in [src/validation/isValidEmail.ts:21](https://github.com/cahilfoley/utils/blob/22bd396/src/validation/isValidEmail.ts#L21)*

Tests if the input string is in the form of a valid email address

**`example`** 
```typescript

isValidEmail(`no spaces@sham.co`) // => false
```

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`text` | string | The text to |

**Returns:** *boolean*

Returns true if the input is a valid email address otherwise returns false

___

###  isValidURL

▸ **isValidURL**(`text`: string): *boolean*

*Defined in [src/validation/isValidURL.ts:22](https://github.com/cahilfoley/utils/blob/22bd396/src/validation/isValidURL.ts#L22)*

Checks if a value provided is of type string and is a valid URL. If the value is not a string
or it is an empty string then the function returns false

**`example`** 
```typescript

const valid = isValidURL('http://www.google.com') // returns true
```

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`text` | string | The text to validate |

**Returns:** *boolean*

Returns true if the input is a valid URL otherwise returns false

___

###  makeCancelable

▸ **makeCancelable**<**T**>(`promise`: Promise‹T›): *[CancelableWrappedPromise](interfaces/cancelablewrappedpromise.md)‹T›*

*Defined in [src/async/makeCancelable.ts:44](https://github.com/cahilfoley/utils/blob/22bd396/src/async/makeCancelable.ts#L44)*

Allows the provided promise to be canceled after starting. This does not stop the promise from executing but will
cause it to reject with the value `{ isCanceled: true }` once it finishes, regardless of outcome.

**`example`** 
```typescript

const promise = new Promise((res, rej) => {
  setTimeout(() => res('I finished!'), 3000)
})

// Create a cancelable version of the promise
const cancelablePromise = makeCancelable(promise)

// Stop the cancelable promise from resolving
cancelablePromise.cancel()

promise
  .then(result => console.log('Normal', result)) // This will log `'I finished!'` after 3000ms
  .catch(err => console.log('Normal', err)) // Will reject as per normal

cancelablePromise
  .then(result => console.log('Cancelable', result)) // Never fires, the promise will not resolve after being cancelled
  .catch(err => console.log('Cancelable', err)) // Resolves after 3000ms with the value `{ isCanceled: true }`
```

**Type parameters:**

▪ **T**

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`promise` | Promise‹T› | The promise that is executing |

**Returns:** *[CancelableWrappedPromise](interfaces/cancelablewrappedpromise.md)‹T›*

The cancelable version of the promise

___

###  noramlizeURL

▸ **noramlizeURL**(...`urlParts`: string[]): *string*

*Defined in [src/transforms/normalizeURL.ts:62](https://github.com/cahilfoley/utils/blob/22bd396/src/transforms/normalizeURL.ts#L62)*

Sanitises and safely joins sections of a URL, this includes removing duplicate slashes in the path and
ensuring correctly formatted protocols.

**`example`** 
```typescript

const url = normalizeURL('https://cahilfoley.github.io/', '/utils') // => 'https://cahilfoley.github.io/utils'
```

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`...urlParts` | string[] | The URL parts to be joined and normalized |

**Returns:** *string*

Returns the joined and normalized URL parts as a string

___

### `Private` normalizeProtocol

▸ **normalizeProtocol**(`urlParts`: string[]): *string[]*

*Defined in [src/transforms/normalizeURL.ts:9](https://github.com/cahilfoley/utils/blob/22bd396/src/transforms/normalizeURL.ts#L9)*

Normalizes the number of slashes in the protocol section of a url

**Parameters:**

Name | Type |
------ | ------ |
`urlParts` | string[] |

**Returns:** *string[]*

___

### `Private` normalizeSectionSlashes

▸ **normalizeSectionSlashes**(`urlParts`: string[]): *string[]*

*Defined in [src/transforms/normalizeURL.ts:29](https://github.com/cahilfoley/utils/blob/22bd396/src/transforms/normalizeURL.ts#L29)*

Normalizes the number of slashes in each section of the URL

**Parameters:**

Name | Type |
------ | ------ |
`urlParts` | string[] |

**Returns:** *string[]*

___

###  partial

▸ **partial**(`func`: function, ...`argsBound`: any[]): *function*

*Defined in [src/function/partial.ts:22](https://github.com/cahilfoley/utils/blob/22bd396/src/function/partial.ts#L22)*

Creates a function that invokes `func` with `partials` prepended to the arguments it receives.

**`example`** 
```typescript

const addNums = (a, b, c) => a + b + c
const addNumsTo5 = partial(addNums, 5)

addNumsTo5(1, 3) // => 9
```

**Parameters:**

▪ **func**: *function*

The function to partially apply arguments to

▸ (...`args`: any[]): *any*

**Parameters:**

Name | Type |
------ | ------ |
`...args` | any[] |

▪... **argsBound**: *any[]*

The arguments to be partially applied

**Returns:** *function*

▸ (...`remainingArgs`: any[]): *any*

**Parameters:**

Name | Type |
------ | ------ |
`...remainingArgs` | any[] |

___

###  partitionArray

▸ **partitionArray**<**T**>(`array`: T[], `predicate`: function, `context?`: any): *[T[], T[]]*

*Defined in [src/array/partitionArray.ts:24](https://github.com/cahilfoley/utils/blob/22bd396/src/array/partitionArray.ts#L24)*

Partitions an array using a provided predicate function. All elements satisfying the predicate are part of the first returned array,
and all elements that don't are in the second.

**`example`** 
```typescript

partitionArray([1, 2, 3, 4], x => x % 2)
// Returns [[1, 3], [2, 4]]
```

**Type parameters:**

▪ **T**

**Parameters:**

▪ **array**: *T[]*

The array to partition

▪ **predicate**: *function*

Function to test each item. Items that return true are placed in the first array,
otherwise they are returned in the second array

▸ (`value`: T, `index`: number, `array`: T[]): *boolean*

**Parameters:**

Name | Type |
------ | ------ |
`value` | T |
`index` | number |
`array` | T[] |

▪`Optional`  **context**: *any*

**Returns:** *[T[], T[]]*

Two arrays, the first containing all items that satisfied the predicate, the second containing the rest

___

###  pause

▸ **pause**(`ms`: number): *Promise‹unknown›*

*Defined in [src/async/pause.ts:27](https://github.com/cahilfoley/utils/blob/22bd396/src/async/pause.ts#L27)*

Creates a promise that resolves in the provided number of milliseconds.

This function is basically a promise version of `setTimeout`

**`example`** 
```typescript

async function run() {
  console.log('first log')
  await pause(500)

  // Will run 500 milliseconds after the first
  console.log('second log')
}
```

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`ms` | number | The number of ms to pause for |

**Returns:** *Promise‹unknown›*

The executing promise

___

###  pick

▸ **pick**<**T**, **U**>(`object`: T, ...`keys`: U[]): *Pick‹T, U›*

*Defined in [src/accessors/pick.ts:25](https://github.com/cahilfoley/utils/blob/22bd396/src/accessors/pick.ts#L25)*

Creates a new object containing only the properties of `object` that are specified in `keys`.

**`example`** 
```typescript

const original = { foo: 'hello', bar: 'world', baz: false, something: [1, 2, 3] }
const picked = pick(original, 'foo', 'something')

console.log(picked) // { foo: 'hello', something: [1, 2, 3] }
console.log(Object.keys(picked)) // ['foo', 'something']
```

**Type parameters:**

▪ **T**: *Record‹string, any›*

▪ **U**: *keyof T*

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`object` | T | The base object that properties will be picked from |
`...keys` | U[] | The keys to pick  |

**Returns:** *Pick‹T, U›*

▸ **pick**<**T**, **U**>(`object`: T, `keys`: U[]): *Pick‹T, U›*

*Defined in [src/accessors/pick.ts:29](https://github.com/cahilfoley/utils/blob/22bd396/src/accessors/pick.ts#L29)*

**Type parameters:**

▪ **T**: *Record‹string, any›*

▪ **U**: *keyof T*

**Parameters:**

Name | Type |
------ | ------ |
`object` | T |
`keys` | U[] |

**Returns:** *Pick‹T, U›*

___

###  runTest

▸ **runTest**(`testCase`: [any, any], `func`: function, `testVerb`: string): *void*

*Defined in [src/tests/runTest.ts:21](https://github.com/cahilfoley/utils/blob/22bd396/src/tests/runTest.ts#L21)*

Runs a test based on input(s), if an array is provided then the items are passed as arguments to the function
being tested, if anything else is provided then it is passed directly to the function

**`example`** 
```typescript

runTest([[3, 5], 8], (a, b) => a + b)
```

**Parameters:**

▪ **testCase**: *[any, any]*

A tuple of inputs and expected output

▪ **func**: *function*

The function to test

▸ (...`args`: any[]): *any*

**Parameters:**

Name | Type |
------ | ------ |
`...args` | any[] |

▪`Default value`  **testVerb**: *string*= "toBe"

The jest `expect` verb to use when testing - defaults to `toBe`

**Returns:** *void*

___

###  set

▸ **set**(`object`: Record‹string, any› | any[], `path`: string[] | string, `value`: any): *void*

*Defined in [src/accessors/set.ts:33](https://github.com/cahilfoley/utils/blob/22bd396/src/accessors/set.ts#L33)*

Sets the value at path of object. If a portion of path doesn't exist, it's created. Arrays are created for missing
index properties while objects are created for all other missing properties.

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`object` | Record‹string, any› &#124; any[] | The object to modify |
`path` | string[] &#124; string | The path of the property to set |
`value` | any | The value to set   |

**Returns:** *void*

___

###  toCamel

▸ **toCamel**(`input`: string): *string*

*Defined in [src/transforms/toCamel.ts:39](https://github.com/cahilfoley/utils/blob/22bd396/src/transforms/toCamel.ts#L39)*

Transforms the provided string into camel-case.

If the string contains a combination of upper and lower-case letters then the method
will retain the capitalization of acronyms. This behaviour can be explicitly toggled
on or off with the `keepAcronyms` option.

**`example`** 
```typescript

toCamel('ILoveCamels') // => 'iLoveCamels'
toCamel('User ID') // => 'userID'
```

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`input` | string | The string to be converted |

**Returns:** *string*

Returns the camel-case string

▸ **toCamel**(`input`: string, `options`: [ToCamelOptions](interfaces/tocameloptions.md)): *string*

*Defined in [src/transforms/toCamel.ts:40](https://github.com/cahilfoley/utils/blob/22bd396/src/transforms/toCamel.ts#L40)*

**Parameters:**

Name | Type |
------ | ------ |
`input` | string |
`options` | [ToCamelOptions](interfaces/tocameloptions.md) |

**Returns:** *string*

___

###  toProperList

▸ **toProperList**(`items`: string[]): *string*

*Defined in [src/transforms/toProperList.ts:19](https://github.com/cahilfoley/utils/blob/22bd396/src/transforms/toProperList.ts#L19)*

Joins together several strings or numbers in a properly formatted English list. The last two items are seperated by the word
'and' and the remaining items are seperated by a comma and space.

**`example`** 
```typescript

const itemsString = toProperList(['apples', 'pears', 'bananas']) // => 'apples, pears and bananas'
```

**Parameters:**

Name | Type | Description |
------ | ------ | ------ |
`items` | string[] | Array of strings  |

**Returns:** *string*

▸ **toProperList**(...`items`: string[]): *string*

*Defined in [src/transforms/toProperList.ts:20](https://github.com/cahilfoley/utils/blob/22bd396/src/transforms/toProperList.ts#L20)*

**Parameters:**

Name | Type |
------ | ------ |
`...items` | string[] |

**Returns:** *string*

___

###  updateItem

▸ **updateItem**(`array`: object[], `query`: object, `updateCallback`: function): *object[]*

*Defined in [src/array/updateItem.ts:18](https://github.com/cahilfoley/utils/blob/22bd396/src/array/updateItem.ts#L18)*

Updates an item in an array and returns a new array

**Parameters:**

▪ **array**: *object[]*

The array to update

▪ **query**: *object*

A map of property paths (period delimited string) to values used to test if an object should be updated,
the paths are used in the get function

▪ **updateCallback**: *function*

A callback used to update the item

▸ (`item`: any): *any*

**Parameters:**

Name | Type |
------ | ------ |
`item` | any |

**Returns:** *object[]*

The array with the updated item

## Object literals

### `Const` canceledError

### ▪ **canceledError**: *object*

*Defined in [src/async/makeCancelable.ts:6](https://github.com/cahilfoley/utils/blob/22bd396/src/async/makeCancelable.ts#L6)*

An error that indicates a promise has rejected because it was canceled

###  isCanceled

• **isCanceled**: *boolean* = true

*Defined in [src/async/makeCancelable.ts:6](https://github.com/cahilfoley/utils/blob/22bd396/src/async/makeCancelable.ts#L6)*
