ts-utils 
About
Lightweight TypeScript utility library offering a collection of essential functions to simplify common coding tasks. Designed for a maximized type-safety, efficiency, readability, and maintainability.
Install
npm install --save @axanc/ts-utils
Examples
Components from browser/
and node/
directory only works in their related environment.
- Obj – Utility functions for
Object
manipulation.
- Seq – Enhanced
Array
- Match – Type-safe pattern matching for
Enum
and string unions.
- GroupsBy – Groups an array of objects by multiple criteria and maps the results.
- Chunkify – Processes an array in batches with an asynchronous function, supporting concurrency control.
- Lazy – Caches function results to prevent redundant calls.
- Gzip – Compress and decompress files (Node.js only).
- FileSplitter – Splits a large file into smaller chunks (Node.js only).
Obj
TypeScript refuses to infer types from Object
constructor functions. Obj
implements the same method but infer keys and value to prevent annoying and unnecessary type casting.
const input = {a: 1, b: 2}
Object.keys(input)
Obj.keys(input)
enum Status { OK = 'Ok', ERROR = 'Error' }
Obj.values(Status)
Additionally, it includes helper functions and can be used as a class constructor to enable method chaining.
const res = new Obj({ironman: 2, barman: 1, catwoman: 4, batman: 3})
.sortManual(['catwoman', 'barman', 'ironman', 'batman'])
.mapKeys(_ => _.toUpperCase())
.mapValues(_ => _ + 1)
.get()
Seq
Enhance poor JavaScript Array
.
const a = seq([
{name: 'Dave', age: 35},
{name: 'Charlie', age: 25},
{name: 'Alice', age: 25},
])
a.distinct(_ => _.age)
a.sortByString(_ => _.name, 'z-a')
a.sortByNumber(_ => _.age, '0-9')
a.count(_ => _.age > 26)
a.groupBy(_ => _.age)
a.groupByFirst(_ => _.age)
a.groupByFirstAndApply(_ => _.age, _ => _.length)
a.sum(_ => _.age)
a.head()
a.last()
a.reduceObject(_ => [_.name, _.age])
a.percent(_ => _.age === 35)
[1, 2].difference([1, 2, 3])
[1, 2].intersect([1, 2, 3])
Match
Simple and type-safe pattern matching. Fully infer Enum
and strings union.
enum Enum {
yes = 'yes',
no = 'no',
unknown = 'unknown',
}
const value = Enum.yes
const res: number = match(value)
.cases({
[Enum.yes]: 0,
})
.default(() => -1)
match(value)
.cases({
[Enum.yes]: () => 1,
[Enum.no]: () => 2,
[Enum.unknown]: () => 3,
})
.exhaustive()
GroupsBy
Groups an array of objects by multiple criteria and maps the results.
const data = [
{id: 1, category: 'A', type: 'X', value: 10},
{id: 2, category: 'B', type: 'Y', value: 20},
{id: 3, category: 'A', type: 'Y', value: 15},
{id: 4, category: 'B', type: 'X', value: 25},
{id: 5, category: 'A', type: 'X', value: 5},
]
const result = groupsBy({
data,
groups: [{by: item => item.category}, {by: item => item.type}],
finalTransform: items => items.reduce((sum, item) => sum + item.value, 0),
})
Chunkify
Processes an array of items in batches, applying an asynchronous function fn
to each chunk.
It supports optional concurrency control for optimized parallel execution.
await chunkify({
size: 10,
data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
fn: async chunk => {
await db.insert(chunk)
return chunk.map(_ => _ * 2)
},
})
Lazy
Caches function results based on parameters to avoid redundant calls.
const findByUserId = lazy((id: number) => {
return users.find(_ => _.id === id)
})
findByUserId(1)
findByUserId(1)
findByUserId(2)
Gzip
[!IMPORTANT]
Note: Only available on Node environment.
await gunzipFile(`${fixturePath}/zipped.gz`)
await gzipFile(`${fixturePath}/notzipped`)
FileSplitter
[!IMPORTANT]
Note: Only available on Node environment.
const splitFiles = await fileSplitter({
filepath: 'large.txt',
maxFileSizeMB: 5,
outputDirPath: '.',
})