Skip to content

Toolkit API Reference

API At a Glance

SymbolPurposeExecution modeCommon gotcha
chunk()Split arrays into fixed-size groupsSyncValidate positive chunk sizes
retry()Retry async operations with delay strategyAsyncUse bounded retries to avoid runaway loops
currency()Format monetary values safelySyncMatch currency precision to business requirements

Overview

Toolkit provides 75+ utilities organized into 10 categories. All utilities are:

  • Type-safe with full TypeScript inference
  • Tree-shakeable for minimal bundle sizes
  • Isomorphic (Browser + Node.js)
  • Well-tested with >95% code coverage

Quick Navigation

Array Utilities

Transform, filter, and manipulate arrays with type safety.

See Array Examples for detailed usage.

Transformation

UtilityDescriptionExample
chunkSplit into chunks of specific sizechunk([1,2,3,4,5], 2)[[1,2],[3,4],[5]]
foldReduce to single value (no initial value)fold([1,2,3], (a,b) => a+b)6
replaceReplace first matching elementreplace([1,2,3], x => x === 2, 0)[1,0,3]
rotateRotate array positionsrotate([1,2,3], 1)[2,3,1]
toggleToggle item in array (add/remove)toggle([1,2], 2)[1]

Aggregation

UtilityDescriptionExample
groupGroup elements by key or functiongroup(users, u => u.role)
keyByIndex array by propertykeyBy(users, 'id')
uniqRemove duplicate valuesuniq([1,2,2,3])[1,2,3]

Querying

UtilityDescriptionExample
containsCheck if array contains valuecontains([1,2,3], 2)true
searchFuzzy search in arraysearch(users, 'alice')

Sorting

UtilityDescriptionExample
sortSort by selector or object selectorssort(users, { age: 'desc', name: 'asc' })

Selection

UtilityDescriptionExample
pickPick and transform elementpick([1,2,3], x => x*2, x => x > 1)4
selectMap non-null elements with callbackselect([null, 1, 2], x => x * 2)[2, 4]

Pagination

UtilityDescriptionExample
listClient-side reactive paginationlist(data, {limit: 10})
remoteListServer-side reactive pagination with cachingremoteList({fetch: fetchFn, limit: 20})

Object Utilities

Deep operations, merging, and property manipulation.

See Object Examples for detailed usage.

UtilityDescriptionExample
stashKey-value cache with automatic GCstash<T>({ hash: key => ... })
diffFind differences between objectsdiff(obj1, obj2)
mergeMerge objects (deep/shallow/etc.)merge('deep', obj1, obj2)
parseJSONSafely parse JSON with fallbackparseJSON(str, defaultValue)
getAccess nested properties safelyget(obj, 'user.profile.name')
proxyObject proxy with get/set hooksproxy(obj, { set: logger })
pruneRemove null/empty values recursivelyprune({ a: 1, b: null })
seekSearch object values by similarityseek(obj, 'hello', 0.8)true

String Utilities

Formatting, casing, similarity, and manipulation.

See String Examples for detailed usage.

Casing

UtilityDescriptionExample
camelCaseConvert to camelCasecamelCase('hello-world')'helloWorld'
snakeCaseConvert to snake_casesnakeCase('helloWorld')'hello_world'
kebabCaseConvert to kebab-casekebabCase('helloWorld')'hello-world'
pascalCaseConvert to PascalCasepascalCase('hello-world')'HelloWorld'

Manipulation

UtilityDescriptionExample
truncateTruncate string with ellipsistruncate('long text', 5)'long...'

Analysis

UtilityDescriptionExample
similarityCalculate string similaritysimilarity('hello', 'hallo')0.8

Function Utilities

Control execution flow, composition, and assertions.

See Function Examples for detailed usage.

UtilityDescriptionExample
assertAssert condition (throws or warns)assert(x > 0, 'Must be positive')
assertParamsAssert required object keys are presentassertParams(params, ['id', 'name'])
compareCompare two values → -1, 0, or 1compare('a', 'b')-1
compareByMulti-key object comparatorcompareBy({ name: 'asc', age: 'desc' })
composeCompose functions right-to-leftcompose(f, g, h)
curryCurry function with partial applicationcurry(add)(1)(2)3
debounceDelay execution until idledebounce(fn, 300)
fpFunctional programming pipeline wrapperfp(map, double)([1,2,3])
memoMemoize/cache function resultsmemo(expensiveFn)
onceExecute function only onceonce(fn)
pipeCompose functions left-to-rightpipe(f, g, h)
throttleLimit execution ratethrottle(fn, 100)

Async Utilities

Async control flow, retry strategies, and concurrency primitives.

See Async Examples for detailed usage.

UtilityDescriptionExample
attemptExecute fn with retry and error handlingattempt(fetchFn, { times: 3, timeout: 5000 })
deferCreate deferred promise with external controlconst { promise, resolve } = defer()
parallelProcess array with controlled concurrencyawait parallel(5, items, asyncFn)
poolConcurrency-limited promise poolconst slot = pool(3); await slot(fn)
queueSequential queue with concurrency controlconst q = queue(); q.add(task)
raceRace promise with minimum delayrace(fetchFn(), 500)
retryRetry async fn with backoff, per-attempt delay, and predicateretry(asyncFn, { times: 3, delay: 250, shouldRetry: fn })
SchedulerTask scheduler with native API or polyfill fallbacknew Scheduler().postTask(fn, { delay: 100, priority: 'background' })
polyfillSchedulerInstall the Scheduler polyfill globally when not natively supportedpolyfillScheduler()
sleepWait millisecondsawait sleep(1000)
waitForPoll condition until trueawait waitFor(() => isReady, { timeout: 5000 })

Math Utilities

Statistics, calculations, and number operations.

See Math Examples for detailed usage.

Arithmetic Operations

UtilityDescriptionExample
absAbsolute valueabs(-5)5

Distribution

UtilityDescriptionExample
allocateDistribute proportionallyallocate(100, [1,2,3])[16,33,51]
distributeDistribute evenlydistribute(100, 3)[34,33,33]

Statistics

UtilityDescriptionExample
sumSum of numberssum([1,2,3])6
averageCalculate average/meanaverage([1,2,3])2
medianFind median valuemedian([1,2,3,4,5])3
minFind minimum valuemin([1,2,3])1
maxFind maximum valuemax([1,2,3])3

Number Utilities

UtilityDescriptionExample
clampClamp value to rangeclamp(10, 0, 5)5
linspaceEvenly spaced number sequencelinspace(0, 1, 5)[0, 0.25, 0.5, 0.75, 1]
percentCalculate percentagepercent(25, 100)25
rangeGenerate number rangerange(1, 6, 1)[1,2,3,4,5]
roundRound to decimal placesround(3.14159, 2)3.14

Money Utilities

Currency formatting and conversion with precision.

See Money Examples for detailed usage.

UtilityDescriptionExample
currencyFormat money for displaycurrency({amount: 123456n, currency: 'USD'})'$1,234.56'
exchangeConvert between currenciesexchange(usd, {from: 'USD', to: 'EUR', rate: 0.85})

Date Utilities

Time intervals, differences, and expiration checks.

See Date Examples for detailed usage.

UtilityDescriptionExample
expiresCheck expiration statusexpires('2030-01-01')'LATER'
intervalGenerate date rangeinterval('2024-01-01', '2024-01-07', { interval: 'day' })
timeDiffCalculate time differencetimeDiff(date1, date2){ value: 5, unit: 'day' }

Random Utilities

Random generation, shuffling, and sampling.

See Random Examples for detailed usage.

UtilityDescriptionExample
randomRandom number in rangerandom(1, 10)7
drawRandom array elementdraw([1,2,3])2
shuffleShuffle arrayshuffle([1,2,3])[3,1,2]
uuidGenerate UUID v4uuid()'550e8400-...'

Typed Utilities

Typed checks are exposed through the is namespace plus is.typeOf(...).

See Typed Examples for detailed usage.

is Namespace Methods

MethodDescriptionExample
is.string(value)Check if value is a stringis.string('x')
is.number(value)Check if value is a number (excluding NaN)is.number(42)
is.boolean(value)Check if value is a booleanis.boolean(false)
is.array(value)Check if value is an arrayis.array([1, 2])
is.object(value)Check if value is a plain objectis.object({ a: 1 })
is.fn(value)Check if value is a functionis.fn(() => {})
is.date(value)Check if value is a valid Dateis.date(new Date())
is.regex(value)Check if value is a RegExpis.regex(/a/)
is.promise(value)Check if value is a Promiseis.promise(Promise.resolve())
is.defined(value)Check if value is not undefinedis.defined(0)
is.nil(value)Check if value is null or undefinedis.nil(null)
is.primitive(value)Check if value is string/number/booleanis.primitive('x')
is.empty(value)Check if value is emptyis.empty([])
is.equal(a, b)Deep equality comparisonis.equal({ a: 1 }, { a: 1 })
is.match(object, source)Partial deep-matchis.match(user, { role: 'admin' })
is.within(value, min, max)Inclusive range checkis.within(5, 1, 10)
is.even(value)Check if number is evenis.even(4)
is.odd(value)Check if number is oddis.odd(3)
is.positive(value)Check if number is positiveis.positive(3)
is.negative(value)Check if number is negativeis.negative(-3)
is.zero(value)Check if value is exactly zerois.zero(0)
is.gt(a, b) / is.ge(a, b)Greater-than / greater-or-equalis.gt(5, 3)
is.lt(a, b) / is.le(a, b)Less-than / less-or-equalis.le(5, 5)
is.typeOf(value)Runtime type tagis.typeOf([]) // 'array'

Import Reference

ts
// Best for tree-shaking — all utilities come from the main package
import { chunk, fold, group, keyBy, select } from '@vielzeug/toolkit';
import { retry, sleep, parallel, Scheduler, polyfillScheduler } from '@vielzeug/toolkit';
import { debounce, throttle, memo } from '@vielzeug/toolkit';
import { merge, prune, diff } from '@vielzeug/toolkit';

See Also


Note: Error behavior is utility-specific. See each utility page for exact validation and thrown error types.