A dependency-free TypeScript utility belt: strings, objects, arrays, dates, numbers, types, binary data, secp256k1 elliptic curve crypto, Swarm chunk trees, geometry and a few small runtime helpers.
Everything is exported from the package root, grouped into namespace objects (Strings, Objects,
…) plus a handful of standalone classes.
import { Strings, Objects, Dates, Optional } from 'cafe-utility'
Strings.slugify('Hello World!') // 'hello-world'
Objects.getDeep({ a: { b: 1 } }, 'a.b') // 1
Dates.humanizeTime(93_000) // '01:33'- Binary · Elliptic · Random · Arrays · System · Numbers · Promises · Dates · Objects · Types · Strings · Assertions · Cache · Vector
- Classes: Optional · Lazy / AsyncLazy · Uint8ArrayReader / Uint8ArrayWriter · Chunk · ChunkSplitter · ChunkJoiner · FixedPointNumber · PubSubChannel · AsyncQueue · TrieRouter · RollingValueProvider · Solver · Lock
Byte-level encoding, hashing and bit twiddling.
| Function | Description |
|---|---|
hexToUint8Array(hex) |
Decode a hex string (with or without 0x) into bytes. |
uint8ArrayToHex(array) |
Hex-encode bytes. |
binaryToUint8Array(binary) |
Decode a '0'/'1' bit string into bytes. |
uint8ArrayToBinary(array) |
Render bytes as a '0'/'1' bit string. |
base64ToUint8Array(base64String) |
Decode base64 into bytes. |
uint8ArrayToBase64(array) |
Base64-encode bytes. |
base32ToUint8Array(base32String) |
Decode RFC-4648 base32 into bytes. |
uint8ArrayToBase32(array) |
Base32-encode bytes. |
log2Reduce(array, reducer) |
Fold a power-of-two array pairwise, level by level (binary tree). |
partition(bytes, size) |
Split bytes into fixed-size views. |
concatBytes(...arrays) |
Concatenate byte arrays. |
numberToUint8(number) |
Encode a number as one byte. |
uint8ToNumber(bytes) |
Read one byte as a number. |
numberToUint16(number, endian) |
Encode a number as 2 bytes, 'LE' or 'BE'. |
uint16ToNumber(bytes, endian) |
Read 2 bytes as a number. |
numberToUint32(number, endian) |
Encode a number as 4 bytes. |
uint32ToNumber(bytes, endian) |
Read 4 bytes as a number. |
numberToUint64(bigint, endian) |
Encode a bigint as 8 bytes. |
uint64ToNumber(bytes, endian) |
Read 8 bytes as a bigint. |
numberToUint256(bigint, endian) |
Encode a bigint as 32 bytes. |
uint256ToNumber(bytes, endian) |
Read 32 bytes as a bigint. |
sliceBytes(bytes, lengths) |
Cut bytes into consecutive views of the given lengths. |
keccak256(bytes) |
Keccak-256 digest (Ethereum flavour). |
sha3_256(bytes) |
SHA3-256 digest. |
proximity(one, other) |
Number of leading identical bits between two byte arrays. |
commonPrefix(one, other) |
The shared leading bytes of two arrays. |
setBit(bytes, index, value, endian) |
Set a single bit in place. |
getBit(bytes, index, endian) |
Read a single bit. |
indexOf(bytes, value, start?) |
Index of a byte subsequence, or -1. |
equals(a, b) |
Byte-wise equality. |
padStart(bytes, size, paddingByte?) |
Left-pad to an exact length. |
padStartToMultiple(bytes, multiple, paddingByte?) |
Left-pad up to a multiple of multiple. |
padEnd(bytes, size, paddingByte?) |
Right-pad to an exact length. |
padEndToMultiple(bytes, multiple, paddingByte?) |
Right-pad up to a multiple of multiple. |
xorCypher(bytes, key) |
XOR bytes with a repeating key. |
isUtf8(bytes) |
Whether the bytes are a valid UTF-8 sequence. |
secp256k1 signing and Ethereum-style key handling, implemented on bigint.
| Function | Description |
|---|---|
privateKeyToPublicKey(privateKey) |
Derive the [x, y] public key from a private scalar. |
compressPublicKey(publicKey) |
Compress a public key to 33 bytes. |
publicKeyFromCompressed(compressed) |
Decompress 33 bytes back into [x, y]. |
publicKeyToAddress(publicKey) |
20-byte Ethereum address of a public key. |
signMessage(message, privateKey, nonce?) |
ECDSA-sign a message, returning [r, s, v]. |
signHash(hash, privateKey, nonce?) |
ECDSA-sign an already-hashed value. |
verifySignature(message, publicKey, r, s) |
Verify a signature against a public key. |
recoverPublicKey(message, r, s, v) |
Recover the signer's public key from a signature. |
checksumEncode(addressBytes) |
EIP-55 mixed-case checksum address string. |
All generators take an optional generator so they can be seeded and made deterministic.
| Function | Description |
|---|---|
intBetween(min, max, gen?) |
Random integer in [min, max], inclusive. |
floatBetween(min, max, gen?) |
Random float in [min, max). |
chance(threshold, gen?) |
true with probability threshold. |
signed() |
Random float in (-1, 1). |
makeSeededRng(seed) |
Deterministic Math.random-compatible generator. |
point(width, height, exclude?, gen?) |
Random [x, y] in a grid, optionally avoiding a rectangle. |
procs(probability, gen?) |
Round a fractional count of "procs" (e.g. 2.3 → 2 or 3). |
| Function | Description |
|---|---|
countUnique(array, mapper?, plain?, sort?, reverse?) |
Count occurrences per value; optionally sorted or as a plain list. |
makeUnique(array, fn) |
Deduplicate by a computed key. |
splitBySize(array, size) |
Chunk into groups of at most size. |
splitByCount(array, count) |
Split into count groups. |
index(array, keyFn) |
Build a key → item map. |
indexCollection(array, keyFn) |
Build a key → items[] map. |
onlyOrThrow(array) |
The single element, or throw. |
onlyOrNull(array) |
The single element, or null. |
firstOrThrow(array) |
First element, or throw if empty. |
firstOrNull(array) |
First element, or null. |
shuffle(array, gen?) |
Fisher-Yates shuffle into a new array. |
initialize(count, initializer) |
Build an array from an index function. |
initialize2D(width, height, initialValue) |
Build a filled 2D array. |
rotate2D(array) |
Rotate a 2D array by 90°. |
containsShape(array2D, shape, x, y) |
Whether a 2D pattern (with undefined wildcards) matches at x, y. |
glue(array, glueElement) |
Interpose a value (or factory result) between elements. |
pluck(array, key) |
Collect one property from every item. |
pick(array, gen?) |
One random element. |
pickMany(array, count, gen?) |
count random elements, with repetition. |
pickManyUnique(array, count, equalityFn, gen?) |
count distinct random elements. |
pickWeighted(array, weights, randomNumber?) |
Weighted random element. |
pickRandomIndices(array, count, gen?) |
count random indices. |
pickGuaranteed(array, include, exclude, count, predicate, gen?) |
Random pick that always contains one required element. |
last(array) |
Last element. |
pipe(value, functions, assertionFn) |
Run a value through functions, asserting the result type. |
makePipe(functions, assertionFn) |
Reusable pipe as a single function. |
sortWeighted(array, weights, gen?) |
Shuffle biased by per-item weights. |
pushAll(array, elements) |
Push many elements in place. |
unshiftAll(array, elements) |
Unshift many elements in place. |
filterAndRemove(array, predicate) |
Remove matches in place and return them. |
merge(target, source) |
Merge object-of-arrays into target, concatenating. |
empty(array) |
Clear an array in place. |
pushToBucket(object, bucket, item) |
Push into object[bucket], creating it if needed. |
unshiftAndLimit(array, item, limit) |
Unshift and trim to a maximum length. |
atRolling(array, index) |
Index with wrap-around (negatives included). |
group(array, groupFn) |
Split into runs wherever groupFn(current, previous) is false. |
createOscillator(values) |
{ next() } that cycles through values forever. |
organiseWithLimits(items, limits, property, defaultValue, sortFn?) |
Bucket items by a property, capped per bucket, rest to a default bucket. |
tickPlaybook(playbook) |
Advance a TTL-based script, returning current entry and progress. |
getArgument(args, key, env?, envKey?) |
Read --key value / --key=value from argv, falling back to env. |
getBooleanArgument(args, key, env?, envKey?) |
Same, parsed as a flag / boolean-ish string. |
getNumberArgument(args, key, env?, envKey?) |
Same, parsed as a number. |
requireStringArgument(args, key, env?, envKey?) |
Like getArgument, but throws when missing. |
requireNumberArgument(args, key, env?, envKey?) |
Like getNumberArgument, but throws when missing. |
bringToFront(array, index) |
Copy with one element moved to the front. |
bringToFrontInPlace(array, index) |
Same, mutating. |
findInstance(array, type) |
First element of a class, as an Optional. |
filterInstances(array, type) |
All elements of a class. |
interleave(arrayA, arrayB) |
Alternate elements of two arrays. |
toggle(array, value) |
Copy with value added or removed. |
createHierarchy(items, idKey, parentKey, sortKey, reverse?) |
Build a sorted parent/child tree from flat rows. |
multicall(functions) |
Combine void functions into one. |
maxBy(array, fn) |
Element with the highest score. |
minBy(array, fn) |
Element with the lowest score. |
allIndexOf(array, predicate) |
Every index matching a predicate. |
pathfind(array, fromX, fromY, toX, toY, maxSteps) |
Shortest path across a boolean wall grid, or null. |
| Function | Description |
|---|---|
sleepMillis(millis) |
Await a delay. |
forever(callable, millis, log?) |
Run a task in an endless loop, swallowing and logging errors. |
scheduleMany(handlers, dates) |
setTimeout each handler to its matching date. |
waitFor(predicate, options) |
Poll until a predicate passes (optionally N times in a row). |
expandError(error, stackTrace?) |
Flatten an error and its own properties into one string. |
runAndSetInterval(callable, millis) |
Run now and on an interval; returns a cancel function. |
whereAmI() |
'browser' or 'node'. |
withRetries(callable, allowedFailures, delayFirst, delayLast, log?, onFailure?) |
Retry with a delay ramping from first to last. |
| Function | Description |
|---|---|
make(numberWithUnit) |
Parse '1.5K', '2M', '3bzz' etc. into a number. |
sum(array) |
Sum. |
average(array) |
Mean. |
median(array) |
Median. |
getDistanceFromMidpoint(position, length) |
Signed offset of an index from the centre of a range. |
clamp(value, lower, upper) |
Constrain to a range. |
range(start, end) |
Inclusive integer array. |
interpolate(a, b, t) |
Linear interpolation. |
createSequence() |
{ next() } counter starting at 0. |
increment(value, change, maximum) |
Add without exceeding a maximum. |
decrement(value, change, minimum) |
Subtract without dropping below a minimum. |
format(number, options?) |
Human format with unit suffixes (1.2K, 3.4 million). |
fromDecimals(number, decimals, unit?) |
Insert a decimal point into an integer string (token amounts). |
makeStorage(numberWithUnit, conversionMultiplier?) |
Parse '4 GB', '512kb' into bytes. |
asMegabytes(number) |
Bytes → megabytes. |
convertBytes(bytes, divisor?) |
Bytes → '1.500 MB'-style string. |
hexToRgb(hex) |
'#ff8800' → [255, 136, 0]. |
rgbToHex(rgb) |
[255, 136, 0] → '#ff8800'. |
haversineDistanceToMeters(lat1, lon1, lat2, lon2) |
Great-circle distance in metres. |
roundToNearest(value, nearest) |
Round to the nearest multiple. |
formatDistance(meters) |
Human distance string. |
triangularNumber(n) |
n * (n + 1) / 2. |
searchFloat(string) |
First float found in a string, or throw. |
binomialSample(n, p, gen?) |
Fast approximate binomial draw. |
toSignificantDigits(decimalString, significantDigits) |
Truncate a decimal string to N significant digits. |
| Function | Description |
|---|---|
raceFulfilled(promises) |
First promise to fulfil, ignoring rejections. |
invert(promise) |
Resolve on rejection and reject on resolution. |
runInParallelBatches(promises, concurrency?) |
Run thunks with a concurrency limit. |
| Function | Description |
|---|---|
getTimestamp(date, options?) |
Chat-style label: today's time, yesterday, weekday, or a date. |
getTimeDelta(date, options?) |
Relative label like now, 5 minutes ago. |
secondsToHumanTime(seconds, labels?) |
Duration in seconds as the same human phrasing. |
countCycles(since, cycleLength, options?) |
How many fixed cycles elapsed and how much of the current one remains. |
isoDate(optionalDate?) |
YYYY-MM-DD. |
throttle(identifier, millis) |
true at most once per interval, per identifier. |
timeSince(unit, a, optionalB?) |
Elapsed time in 's'/'m'/'h'/'d'. |
dateTimeSlug(optionalDate?) |
Filename-safe date-time string. |
unixTimestamp(optionalTimestamp?) |
Seconds since epoch. |
fromUtcString(string) |
Parse a UTC date string into a Date. |
fromMillis(millis) |
Date from epoch millis. |
getProgress(startedAt, current, total, now?) |
Progress stats: elapsed, ratio, per-item and remaining time. |
humanizeTime(millis) |
hh:mm:ss / mm:ss duration. |
humanizeProgress(state) |
One-line rendering of a getProgress result. |
createTimeDigits(value) |
Zero-pad a number to two digits. |
mapDayNumber(zeroBasedIndex) |
Day index → { zeroBasedIndex, day }. |
getDayInfoFromDate(date) |
Same, from a Date. |
getDayInfoFromDateTimeString(dateTimeString) |
Same, from a date-time string. |
seconds(value) |
Seconds → millis. |
minutes(value) |
Minutes → millis. |
hours(value) |
Hours → millis. |
days(value) |
Days → millis. |
make(numberWithUnit) |
Parse '2h', '30m', '1 day' into millis. |
normalizeTime(time) |
Clean up an 'H:m' string into a valid 'HH:MM'. |
absoluteDays(date) |
Whole days since epoch. |
| Function | Description |
|---|---|
safeParse(stringable) |
JSON.parse returning null instead of throwing. |
deleteDeep(object, path) |
Delete at a dotted path. |
getDeep(some, path) |
Read at a dotted path. |
setDeep(object, path, value) |
Write at a dotted path, creating intermediates. |
incrementDeep(object, path, amount?) |
Add to a number at a dotted path. |
ensureDeep(object, path, value) |
Read at a path, writing a default if absent. |
replaceDeep(object, path, value) |
Overwrite an existing path and return the old value; throws if absent. |
getFirstDeep(object, paths, fallbackToAnyKey?) |
First truthy value among several paths. |
deepMergeInPlace(target, source) |
Recursively merge into target. |
deepMerge2(target, source) |
Recursive merge of two objects into a new one. |
deepMerge3(target, source, third) |
Recursive merge of three objects. |
mapAllAsync(array, fn) |
Promise.all over a mapper. |
cloneWithJson(a) |
Deep clone via JSON round-trip. |
sortObject(object) |
Object with keys sorted, recursively. |
sortArray(array) |
Array sorted with nested values normalised. |
sortAny(any) |
sortObject or sortArray depending on the input. |
deepEquals(a, b) |
Structural equality. |
deepEqualsEvery(...values) |
Structural equality across many values. |
runOn(object, callable) |
Run a side effect and return the object. |
ifPresent(object, callable) |
Run a side effect only when non-nil. |
zip(objects, reducer) |
Merge objects key-wise with a reducer. |
zipSum(objects) |
Merge numeric objects by summing keys. |
removeEmptyArrays(object) |
Drop keys holding empty arrays. |
removeEmptyValues(object) |
Drop keys holding nil/empty values. |
flatten(object, arrays?, prefix?) |
Nested object → dotted-key map. |
unflatten(object) |
Dotted-key map → nested object. |
match(value, options, fallback) |
Table lookup with a default. |
sort(object, compareFn) |
Reorder entries with a comparator. |
map(object, mapper) |
Map values, keeping keys. |
mapIterable(iterable, mapper) |
Map any iterable into an array. |
filterKeys(object, predicate) |
Keep entries whose key passes. |
filterValues(object, predicate) |
Keep entries whose value passes. |
rethrow(asyncFn, throwable) |
Replace any thrown error with your own. |
setSomeOnObject(object, key, value) |
Assign only if the value is non-nil. |
setSomeDeep(target, targetPath, source, sourcePath) |
Copy between paths only if the source value exists. |
flip(object) |
Swap keys and values. |
getAllPermutations(object) |
Cartesian product of an object of option arrays. |
countTruthyValues(object) |
How many values are truthy. |
transformToArray(objectOfArrays) |
Columns → array of row objects. |
setMulti(objects, key, value) |
Set one key on many objects. |
incrementMulti(objects, key, step?) |
Increment one key on many objects. |
createBidirectionalMap() |
Empty two-way map structure. |
createTemporalBidirectionalMap() |
Two-way map whose values carry timestamps. |
pushToBidirectionalMap(object, key, item, limit?) |
Append to a bidirectional map, capped. |
unshiftToBidirectionalMap(object, key, item, limit?) |
Prepend to a bidirectional map, capped. |
addToTemporalBidirectionalMap(object, key, item) |
Add a timestamped entry. |
getFromTemporalBidirectionalMap(object, key) |
Read a timestamped entry, or null. |
createStatefulToggle(desiredValue) |
Function that fires true only on transitions into a value. |
diffKeys(objectA, objectB) |
Keys unique to each of two objects. |
pickRandomKey(object) |
A random key. |
mapRandomKey(object, mapFunction) |
Transform a random key's value in place; returns the key. |
fromObjectString(string) |
Parse loose JS object literal source (shorthands, trailing commas). |
toQueryString(object, questionMark?) |
Object → URL query string. |
parseQueryString(queryString) |
Query string → object. |
hasKey(object, key) |
Own-key check. |
selectMax(object, mapper) |
[key, value] with the highest score, or null. |
reposition(array, key, current, delta) |
Move a row by its order key and renumber the rest. |
unwrapSingleKey(object) |
The only value; throws if there is more than one key. |
parseKeyValues(lines, separator?) |
key: value lines → object. |
errorMatches(error, expected) |
Whether an unknown error's message matches. |
Guards (isX) return booleans; converters (asX) coerce and throw a TypeError on failure,
optionally with a field name and min/max bounds for better messages.
| Function | Description |
|---|---|
isFunction(value) |
Function check. |
isObject(value, checkForPlainObject?) |
Object check, plain-object by default. |
isStrictlyObject(value) |
Non-array, non-null object. |
isEmptyArray(value) |
Array with no elements. |
isEmptyObject(value) |
Object with no keys. |
isUndefined(value) |
undefined check. |
isString(value) |
String check. |
isNumber(value) |
Finite number check. |
isBoolean(value) |
Boolean check. |
isDate(value) |
Date check. |
isBlank(value) |
Not a string, or whitespace only. |
isId(value) |
Positive integer. |
isIntegerString(value) |
String holding an integer. |
isHexString(value) |
String holding hex. |
isUrl(value) |
Parseable URL. |
isBigint(value) |
Bigint-convertible. |
isNullable(typeFn, value) |
null or passing another guard. |
asString(value, options?) |
Coerce to string with length bounds. |
asHexString(value, options?) |
Coerce to a hex string. |
asSafeString(value, options?) |
Coerce to a string with unsafe characters rejected. |
asIntegerString(value, options?) |
Coerce to an integer string with bigint bounds. |
asNumber(value, options?) |
Coerce to number. |
asFunction(value, options?) |
Assert a function. |
asInteger(value, options?) |
Coerce to integer. |
asBoolean(value, options?) |
Coerce to boolean. |
asDate(value, options?) |
Coerce to Date. |
asNullableString(value) |
String or null. |
asEmptiableString(value, options?) |
String, allowing ''. |
asId(value, options?) |
Coerce to a positive integer id. |
asTime(value, options?) |
Validate an 'HH:MM' string. |
asArray(value, options?) |
Assert an array. |
asObject(value, options?) |
Assert a record. |
asNullableObject(value, options?) |
Record or null. |
asStringMap(value, options?) |
Assert a record of strings. |
asNumericDictionary(value, options?) |
Assert a record of numbers. |
asUrl(value, options?) |
Assert a URL string. |
asBigint(value, options?) |
Coerce to bigint with bounds. |
asEmptiable(typeFn, value) |
undefined for '', else apply the converter. |
asNullable(typeFn, value) |
null for nil, else apply the converter. |
asOptional(typeFn, value) |
undefined for nil, else apply the converter. |
enforceObjectShape(value, shape) |
Validate an object against per-key guards. |
enforceArrayShape(value, shape) |
Validate every element against per-key guards. |
isPng(bytes) |
PNG magic-byte check. |
isJpg(bytes) |
JPEG magic-byte check. |
isWebp(bytes) |
WebP magic-byte check. |
isImage(bytes) |
Any of the above. |
| Function | Description |
|---|---|
tokenizeByCount(string, count) |
Split into count pieces. |
tokenizeByLength(string, length) |
Split into pieces of length. |
searchHex(string, length) |
First hex run of a given length, or null. |
searchSubstring(string, predicate, separators?) |
First symbol-delimited part matching a predicate. |
randomHex(length, gen?) |
Random hex string. |
randomLetter(length, gen?) |
Random letters. |
randomAlphanumeric(length, gen?) |
Random letters and digits. |
randomRichAscii(length, gen?) |
Random printable ASCII including symbols. |
randomUnicode(length, gen?) |
Random tricky Unicode (emoji, CJK, combining marks). |
includesAny(string, substrings) |
Whether any substring occurs. |
slugify(string, shouldAllowToken?) |
URL slug. |
normalForm(string) |
Slug without separators, for loose comparison. |
enumify(string) |
SCREAMING_SNAKE_CASE. |
escapeHtml(string) |
Escape HTML entities. |
decodeHtmlEntities(string) |
Decode HTML entities. |
after(string, searchString) |
Text after the first occurrence, or null. |
afterLast(string, searchString) |
Text after the last occurrence. |
before(string, searchString) |
Text before the first occurrence. |
beforeLast(string, searchString) |
Text before the last occurrence. |
betweenWide(string, start, end) |
Text between the first start and the last end. |
betweenNarrow(string, start, end) |
Text between the first start and the next end. |
getPreLine(string) |
Collapse runs of spaces and strip leading indentation. |
containsWord(string, word) |
Whole-word check. |
containsWords(string, words, mode) |
Whole-word check for 'any' or 'all'. |
joinUrl(parts, relativeToFile?) |
Join URL/path segments without doubling slashes. |
getFuzzyMatchScore(string, input) |
Fuzzy relevance score. |
sortByFuzzyScore(strings, input) |
Filter and rank strings by fuzzy score. |
splitOnce(string, separator, last?) |
Split into a [before, after] pair. |
splitAll(string, separators) |
Split on any of several separators. |
randomize(string, gen?) |
Shuffle the characters. |
expand(input) |
Brace expansion: 'a{1,2}' → ['a1', 'a2']. |
shrinkTrim(string) |
Trim lines, collapse whitespace, drop empty lines. |
capitalize(string) |
Upper-case the first character. |
decapitalize(string) |
Lower-case the first character. |
csvEscape(string) |
Quote and escape a CSV field. |
parseCsv(string, delimiter?, quote?) |
Parse one CSV row, honouring quotes. |
surroundInOut(string, filler) |
Insert a filler around and between every character. |
getExtension(path) |
File extension. |
getBasename(path) |
Filename without directories. |
normalizeEmail(string) |
Canonical form of an email address. |
normalizeFilename(path) |
Filesystem-safe filename. |
parseFilename(string) |
Split a filename into its parts. |
camelToTitle(string) |
camelCase → Title Case. |
slugToTitle(string) |
some-slug → Some Slug. |
slugToCamel(string) |
some-slug → someSlug. |
joinHumanly(parts, separator?, lastSeparator?) |
'a, b and c'. |
findWeightedPair(string, start?, opening?, closing?) |
Index of the matching closing delimiter, respecting nesting. |
extractBlock(string, options) |
First balanced delimiter block, or null. |
extractAllBlocks(string, options) |
Every balanced block. |
replaceBlocks(string, replaceFn, options) |
Replace every balanced block. |
indexOfEarliest(string, searchStrings, start?) |
Earliest index among several needles. |
lastIndexOfBefore(string, searchString, start?) |
Last occurrence before a position. |
parseHtmlAttributes(string) |
Attribute string → object. |
readNextWord(string, index, allowedCharacters?) |
Word starting at an index. |
readWordsAfterAll(string, after, allowedCharacters?) |
The word following every occurrence of a marker. |
resolveVariables(string, variables, prefix?, separator?) |
Substitute $name placeholders, applying defaults for the rest. |
resolveVariableWithDefaultSyntax(string, key, value, prefix?, separator?) |
Substitute one variable, honouring $name:default. |
resolveRemainingVariablesWithDefaults(string, prefix?, separator?) |
Replace leftover placeholders with their defaults. |
isLetter(character) |
Letter check. |
isDigit(character) |
Digit check. |
isLetterOrDigit(character) |
Alphanumeric check. |
isValidObjectPathCharacter(character) |
Whether a character is legal in a dotted path. |
insert(string, index, length, before, after) |
Wrap a slice with prefix and suffix text. |
indexOfRegex(string, regex, start?) |
First regex match with its index, or null. |
allIndexOf(string, searchString, start?) |
Every index of a substring. |
lineMatches(haystack, needles, orderMatters?) |
Whether one line contains all needles (strings or regexes). |
linesMatchInOrder(lines, expectations, orderMatters?) |
Whether lines satisfy expectations in sequence. |
represent(value, strategy?, depth?) |
Compact loggable representation of any value. |
resolveMarkdownLinks(string, transformer) |
Rewrite every [label](link) through a transformer. |
buildUrl(baseUrl?, path?, query?) |
Compose base, path and query into a URL. |
isChinese(string) |
Whether the text contains CJK characters. |
replaceBetweenStrings(string, start, end, replacement, keepBoundaries?) |
Replace the text between two markers. |
describeMarkdown(string) |
Classify a markdown line (heading/list/paragraph, punctuation…). |
isBalanced(string, opening?, closing?) |
Whether delimiters are balanced. |
textToFormat(text) |
Reduce text to a shape signature (A, a, Z) for comparison. |
splitFormatting(string, symbol) |
Split into plain and marked-up segments (e.g. **bold**). |
splitHashtags(string) |
Split into text and hashtag segments. |
splitUrls(string) |
Split into text and URL segments. |
route(pattern, actual) |
Match /users/:id against a path, returning params or null. |
explodeReplace(string, substring, variants) |
One copy per variant substituted in. |
generateVariants(string, groups, count, gen?) |
Generate N randomised variants from replacement groups. |
replaceWord(string, search, replace, whitespaceOnly?) |
Whole-word replace. |
replacePascalCaseWords(string, replacer) |
Transform every PascalCase word. |
stripHtml(string) |
Remove tags. |
breakLine(string) |
Split at the last space into { line, rest }. |
measureTextWidth(string, characterWidths?) |
Width using per-character widths. |
toLines(string, maxWidth, characterWidths?) |
Word-wrap to a maximum width. |
levenshteinDistance(a, b) |
Edit distance. |
findCommonPrefix(strings) |
Longest shared prefix. |
findCommonDirectory(paths) |
Longest shared directory prefix. |
Inline assertions that return their input so they can be used in expressions.
| Function | Description |
|---|---|
asEqual(a, b) |
Assert equality, returning the pair. |
asTrue(data) |
Assert exactly true. |
asTruthy(data) |
Assert truthy. |
asFalse(data) |
Assert exactly false. |
asFalsy(data) |
Assert falsy. |
asEither(data, values) |
Assert the string is one of values. |
A process-wide TTL cache keyed by string.
| Function | Description |
|---|---|
get(key, ttlMillis, handler, callbacks?) |
Return the cached value or await and store a fresh one. |
getDeferred(key, ttlMillis, handler, callbacks?) |
Same, but serves a stale value while refreshing in the background. |
delete(key) |
Evict one key. |
deleteExpired() |
Evict everything past its TTL. |
size() |
Number of cached entries. |
clear() |
Evict everything. |
2D points, tile grids and raycasting.
| Function | Description |
|---|---|
addPoint(a, b) |
Vector addition. |
subtractPoint(a, b) |
Vector subtraction. |
multiplyPoint(point, scalar) |
Scale a vector. |
normalizePoint(point) |
Unit vector. |
pushPoint(point, angle, length) |
Move a point along an angle. |
filterCoordinates(grid, predicate, direction?) |
All grid coordinates matching a predicate. |
findCorners(tiles, tileSize, columns, rows) |
Corner points of a tile grid's solid regions. |
findLines(grid, tileSize) |
Wall segments bounding a tile grid. |
raycast(origin, lines, angle) |
Nearest intersection along a ray, or null. |
raycastCircle(origin, lines, corners) |
Visibility polygon points around an origin. |
getLineIntersectionPoint(a1, a2, b1, b2) |
Intersection of two segments, or null. |
Null-safe container. Construct with Optional.of(value) or Optional.empty().
| Member | Description |
|---|---|
map(fn) |
Transform the value if present. |
mapAsync(fn) |
Async map. |
ifPresent(fn) |
Side effect when present; chainable. |
ifPresentAsync(fn) |
Async ifPresent. |
ifAbsent(fn) |
Side effect when absent; chainable. |
ifAbsentAsync(fn) |
Async ifAbsent. |
getOrFallback(fn) |
Value or a computed default. |
getOrFallbackAsync(fn) |
Async getOrFallback. |
getOrThrow() |
Value, or throw when absent. |
new Lazy(supplier) / new AsyncLazy(supplier) — get() computes once and caches the result.
Cursor-based views over a Uint8Array. The reader offers read(size) and max() (bytes left); the
writer offers write(reader) (copies as much as fits, returns the count) and max() (space left).
A 4096-byte Swarm chunk with a 64-bit span.
| Member | Description |
|---|---|
new Chunk(span?) |
Empty chunk with a writable 4096-byte payload. |
writer |
The Uint8ArrayWriter used to fill the payload. |
build() |
Span bytes followed by payload. |
hash() |
Chunk address via the BMT root. |
encryptedHash(key?) |
{ address, key } for the encrypted form, generating a key if none. |
Chunk.hashFunction |
Swappable hash function, keccak256 by default. |
Chunk.encryptSpan(key, spanBytes) |
Encrypt span bytes. |
Chunk.encryptData(key, data) |
Encrypt payload bytes. |
Chunk.decrypt(encBytes, key) |
Decrypt into { span, data }. |
Streams data into a Swarm chunk tree, flushing batches through your callback.
| Member | Description |
|---|---|
new ChunkSplitter(onBatch, maxShards?, encrypted?, onIntermediateChunk?) |
Build a splitter that hands finished chunks to onBatch. |
append(data, level?, spanIncrement?) |
Feed more bytes into the tree. |
finalize(level?) |
Flush and return the root chunk. |
ChunkSplitter.root(data) |
One-shot root chunk for a buffer. |
ChunkSplitter.encryptedRoot(data) |
One-shot { address, key } for a buffer. |
ChunkSplitter.NOOP |
Batch callback that stores nothing. |
The inverse: walks a chunk tree and streams the reassembled data out.
| Member | Description |
|---|---|
new ChunkJoiner(fetch, onData, encrypted?) |
Joiner pulling chunks via fetch, emitting to onData. |
join(address, key?) |
Traverse the tree rooted at an address. |
ChunkJoiner.collect(address, fetch) |
Collect a whole file into one Uint8Array. |
ChunkJoiner.collectEncrypted(address, key, fetch) |
Same, for encrypted references. |
Also exported: the ChunkEntry type ({ chunk, key? }).
Exact scaled-integer arithmetic on bigint, for token amounts and money.
| Member | Description |
|---|---|
new FixedPointNumber(value, scale) |
From a bigint, string or number plus a decimal scale. |
FixedPointNumber.cast(other) |
Coerce an unknown value into a FixedPointNumber. |
FixedPointNumber.fromDecimalString(s, scale) |
Parse '1.25' at a given scale. |
FixedPointNumber.fromFloat(value, scale) |
Convert a float at a given scale. |
add(other) / subtract(other) |
Same-scale addition and subtraction. |
multiply(factor) |
Multiply by a bigint. |
divmod(divisor) |
[quotient, remainder]. |
exchange(direction, rate, targetScale) |
Convert through a rate, rescaling. |
compare(other) |
-1, 0 or 1. |
toDecimalString() / toString() / toJSON() |
Decimal string forms. |
toFloat() |
Lossy number conversion. |
assertSameScale(other) |
Throw when scales differ. |
Typed in-process event channel: subscribe(callback) (returns an unsubscribe function),
publish(data), clear(), getSubscriberCount().
new AsyncQueue(concurrency, capacity) — enqueue(fn) (awaits room when full), drain() (resolves
when idle), plus the onProcessed and onDrained channels.
Path router over segment tries: insert(pathSegments, handler) registers a handler (:name
segments become context variables), handle(pathSegments, request, response, context) dispatches and
reports whether anything matched.
new RollingValueProvider(values) — current() and next() cycle through a list forever.
Resumable multi-step workflow with a shared context map: addStep(step), setHooks(hooks) for
status/step/finish/error callbacks, getStatus(), createInitialState(), and execute() which runs
every step (with preconditions, retries and skips) and resolves to the final context.
Distributed lock over storage you supply: new Lock({ queryFunction, lockFunction, unlockFunction, timeoutMillis }) — couldLock() returns true after taking the lock or the Date it expires, and
unlock() releases it.