Skip to content

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

@borela-tech/ts-toolbox

CI npm version License: Apache-2.0 Node Version

Shared TypeScript utilities for Borela Tech projects.

A lightweight, zero-runtime-dependency collection of runtime functions and type-level utilities.

Install

npm install @borela-tech/ts-toolbox

Requires TypeScript ~5.9.3 as a peer dependency.

Runtime API

areArraysEqual

Check if two arrays have the same length and equal items in order. Uses Object.is as the default equality function: value equality for primitives (including NaN equal to itself) and reference equality for objects (-0 and 0 are distinct).

import {areArraysEqual} from '@borela-tech/ts-toolbox'

areArraysEqual(['a', 'b'], ['a', 'b']) // => true
areArraysEqual(['a'], ['a', 'b']) // => false

const caseInsensitive = (first: string, second: string) =>
  first.toLowerCase() === second.toLowerCase()
areArraysEqual(['A'], ['a'], caseInsensitive) // => true

assertFiniteAtLeast

Throw a RangeError when a value is not finite or is below a minimum.

  • name: name of the value, used in the error message.
  • value: the number to validate.
  • min: inclusive lower bound.
import {assertFiniteAtLeast} from '@borela-tech/ts-toolbox'

assertFiniteAtLeast('delay', 8, 0) // ok
assertFiniteAtLeast('delay', 0, 0) // ok
assertFiniteAtLeast('delay', -1, 0) // throws RangeError: delay (-1) must be a finite number >= 0
assertFiniteAtLeast('delay', Infinity, 0) // throws RangeError
assertFiniteAtLeast('delay', NaN, 0) // throws RangeError

CachedValue

Lazily computed value with manual invalidation. The compute function is only called on the first get (or after invalidate), and the result is cached — including falsy values and undefined.

import {CachedValue} from '@borela-tech/ts-toolbox'

const cache = new CachedValue<number>()
cache.get(() => 42) // => 42, compute called once
cache.get(() => 42) // => 42, cached

cache.invalidate()
cache.get(() => 43) // => 43, recomputed

capitalize

Capitalize the first letter of a string or template literal. When used as a template tag, the first line (after the opening `) and last line (before the closing `) are stripped.

import {capitalize} from '@borela-tech/ts-toolbox'

capitalize('hello') // => 'Hello'

// Template tag: first/last lines from formatting are stripped:
capitalize`
  hello world
`
// => 'Hello world'

clamp

Restrict a number to the inclusive range [min, max].

  • value: the number to clamp.
  • min: inclusive lower bound.
  • max: inclusive upper bound.

Non-finite values are coerced: +Infinity → max, -Infinity → min. NaN is returned as-is.

import {clamp} from '@borela-tech/ts-toolbox'

clamp(5, 0, 10)     // => 5
clamp(-5, 0, 10)    // => 0
clamp(15, 0, 10)    // => 10
clamp(NaN, 0, 10)   // => NaN
clamp(Infinity, 0, 10)  // => 10
clamp(-Infinity, 0, 10) // => 0

clampAndSnap

Snap a number to the nearest multiple of step, then clamp the result to the inclusive range [min, max].

  • value: the number to snap and clamp.
  • step: the snapping step; value is rounded to the nearest multiple of it.
  • min: inclusive lower bound.
  • max: inclusive upper bound.

Non-finite values are coerced: +Infinity → max, -Infinity → min. NaN is returned as-is.

import {clampAndSnap} from '@borela-tech/ts-toolbox'

clampAndSnap(7, 10, 0, 25)    // => 10
clampAndSnap(35, 10, 0, 25)   // => 25
clampAndSnap(-5, 10, 0, 25)   // => 0
clampAndSnap(NaN, 10, 0, 25)  // => NaN

debounce

Create a debounced function. Each call cancels the previous pending call. The target function automatically receives an AbortSignal as the last argument, but does not need to declare it if it is not used. Canceled calls resolve to debouncedCallCancelled.

  • delay: time in milliseconds to wait before invoking the target function.
  • ...args: the arguments passed to the target function (minus any trailing AbortSignal).
import {
  debounce, 
  debouncedCallCancelled,
} from '@borela-tech/ts-toolbox'

const DELAY = 100

const fn = async (x: number) => x * 2
const debouncedFn = debounce(fn)
const a = debouncedFn(DELAY, 1) // Cancelled.
const b = await debouncedFn(DELAY, 2) // Executed.

console.log(a === debouncedCallCancelled) // => true
console.log(b) // => 4

const fnWithSignal = async (x: number, signal: AbortSignal) => {
  if (signal.aborted)
    return
  return x * 2
}
const debouncedFnWithSignal = debounce(fnWithSignal)
const c = debouncedFnWithSignal(DELAY, 3) // Cancelled.
const d = await debouncedFnWithSignal(DELAY, 4) // Executed.

console.log(c === debouncedCallCancelled) // => true
console.log(d) // => 8

dedent

Remove common leading whitespace from all lines. The first and last lines for template literals are always stripped.

import {dedent} from '@borela-tech/ts-toolbox'

dedent`
    hello
      indented
    world
`
// => 'hello\n  indented\nworld'

dedent('    hello\n      indented\n    world') 
// => 'hello\n  indented\nworld'

dedentAndStrip

Like dedent, but also strips leading and trailing empty lines from the content itself (not just the template formatting lines).

import {dedentAndStrip} from '@borela-tech/ts-toolbox'

// The empty lines around hello/world are stripped:
dedentAndStrip`

    hello
    world

`
// => 'hello\nworld'

deepEqual

Deeply compare two values. Handles primitives, arrays, and plain objects. Primitives use Object.is semantics (NaN equals itself, -0 and 0 are distinct). Arrays compare element-wise in order; plain objects compare by keys. Mismatched kinds (e.g. array vs. object) are not equal.

import {deepEqual} from '@borela-tech/ts-toolbox'

deepEqual(1, 1) // => true
deepEqual(NaN, NaN) // => true
deepEqual(0, -0) // => false
deepEqual([1, [2]], [1, [2]]) // => true
deepEqual({a: 1, b: {c: 2}}, {a: 1, b: {c: 2}}) // => true
deepEqual({a: 1}, {a: 1, b: 2}) // => false

deepFreeze

Recursively freeze an object, making it deeply immutable. Uses a WeakSet for cycle detection.

import {deepFreeze} from '@borela-tech/ts-toolbox'

const obj = deepFreeze({a: 1, b: {c: 2}})
obj.a = 42 // TypeError (in strict mode)
obj.b.c = 3 // TypeError (in strict mode)

firstLine

Return the first line of a string.

import {firstLine} from '@borela-tech/ts-toolbox'

firstLine('hello\nworld\nfoo') // => 'hello'
firstLine('hello') // => 'hello'

indent

Add indentation to each line of a string. Works on both plain strings and template literals. When used as a template tag, the first and last formatting lines are stripped.

  • count: number of times to repeat the indent unit (default 1).
  • indentUnit: the string to repeat per level (default ' ').
import {indent} from '@borela-tech/ts-toolbox'

// Template tag mode: indent by 2 spaces (default):
indent`hello\nworld`
// => '  hello\n  world'

// Template tag with custom count and unit:
indent(1, '\t')`hello\nworld`
// => '\thello\n\tworld'

// Plain string mode:
indent('hello\nworld', 1, '  ')
// => '  hello\n  world'

interpolate

Template literal tag that aligns continuation lines of multiline interpolated values to match the indentation of the interpolation site. Leading and trailing empty lines in the template literal are stripped.

import {interpolate} from '@borela-tech/ts-toolbox'

// The line after the opening backtick and the line before the closing backtick
// are always stripped (they come from formatting the template across lines):
const value = 'Alice\nBob'
interpolate`
  hello ${value}!
`
// => '  hello Alice\n  Bob!'

const code = 'fn() {\n  return 1\n}'
interpolate`
  ${code}
`
// => '  fn() {\n    return 1\n  }'

isPlainObject

Check if a value is a plain object. Accepts object literals and objects with a null prototype. Rejects arrays, dates, maps, and class instances. The prototype (via Object.getPrototypeOf) must equal Object.prototype or null.

import {isPlainObject} from '@borela-tech/ts-toolbox'

isPlainObject({a: 1}) // => true
isPlainObject(Object.create(null)) // => true
isPlainObject([1, 2]) // => false
isPlainObject(new Date()) // => false
isPlainObject(new Map()) // => false

lastLine

Return the last line of a string.

import {lastLine} from '@borela-tech/ts-toolbox'

lastLine('hello\nworld\nfoo') // => 'foo'
lastLine('hello') // => 'hello'

getNearestParentPackageJson

Walk up the directory tree to find the nearest package.json.

import {getNearestParentPackageJson} from '@borela-tech/ts-toolbox'

getNearestParentPackageJson('/home/user/projects/my-app/src')
// => '/home/user/projects/my-app/package.json'
// or undefined if not found

snap

Round a number to the nearest multiple of step. Rounds half up.

  • value: the number to round.
  • step: the multiple to round to; if 0, value is returned as-is.
import {snap} from '@borela-tech/ts-toolbox'

snap(7, 10)   // => 10
snap(3, 10)   // => 0
snap(15, 10)  // => 20
snap(25, 10)  // => 30
snap(0.3, 0.25) // => 0.25

withTimeout

Create a time-limited version of a function. The target function automatically receives an AbortSignal as the last argument, but does not need to declare it if it is not used. The signal is aborted after timeoutMs. Aborting is cooperative, not a forced kill: a long-running function keeps running, and if it never settles the returned promise stays pending.

If the target function settles before the timeout fires, the call resolves or rejects with the normal result or error. If the timeout fires first (or the function settles after it), the call resolves to timedOutCallCancelled, regardless of whether the function later resolves or rejects.

  • timeoutMs: time in milliseconds before the call is aborted.
  • ...args: the arguments passed to the target function (minus any trailing AbortSignal).
import {
  withTimeout,
  timedOutCallCancelled,
} from '@borela-tech/ts-toolbox'

const TIMEOUT = 100

const fn = async (x: number) => {
  await new Promise((resolve) => setTimeout(resolve, 50))
  return x * 2
}
const abortableFn = withTimeout(fn)
const a = await abortableFn(TIMEOUT, 2) // Finishes in time.
const b = await abortableFn(10, 2) // Times out.

console.log(a) // => 4
console.log(b === timedOutCallCancelled) // => true

const fnWithSignal = async (x: number, signal: AbortSignal) => {
  if (signal.aborted)
    return
  return x * 2
}
const abortableFnWithSignal = withTimeout(fnWithSignal)
const c = await abortableFnWithSignal(TIMEOUT, 3)
const d = await abortableFnWithSignal(10, 4) // Aborted.

console.log(c) // => 6
console.log(d === timedOutCallCancelled) // => true

Type Utilities

AnyFunction

Any function signature.

import type {AnyFunction} from '@borela-tech/ts-toolbox'

function wrap<T extends AnyFunction>(fn: T) {
  return (...args: Parameters<T>) => fn(...args)
}

DebouncedCallResult<T>, DebouncedFunction<T>, DebouncedFunctionParameters<T>

Types associated with the debounce runtime function.

import type {
  DebouncedCallResult,
  DebouncedFunction,
  DebouncedFunctionParameters,
} from '@borela-tech/ts-toolbox'

type Fn = (x: number) => Promise<number>

type Params = DebouncedFunctionParameters<Fn> // [x: number]
type Debounced = DebouncedFunction<Fn>
// (delay: number, ...args: [x: number]) => Promise<DebouncedCallResult<Fn>>

type Result = DebouncedCallResult<Fn>
// number | typeof debouncedCallCancelled

// If the function declares AbortSignal as its last param, it's stripped:
type FnWithSignal = (x: number, signal: AbortSignal) => Promise<number>
type StrippedParams = DebouncedFunctionParameters<FnWithSignal> // [x: number]

Equals<X, Y>

Evaluate to true when two types are structurally equal, false otherwise.

import type {Equals} from '@borela-tech/ts-toolbox'

type A = Equals<{a: number}, {a: number}> // true
type B = Equals<{a: number}, {b: string}> // false

EqualityFunction<T>

An equality function that compares two values of the same type at runtime. Unlike Equals<X, Y>, which evaluates equality of two types at compile time, EqualityFunction<T> is a runtime callable returning a boolean.

import type {EqualityFunction} from '@borela-tech/ts-toolbox'

const fn: EqualityFunction<unknown> = Object.is
fn(1, 1) // => true

IsAbstract<T>

Returns true if T is an abstract constructor.

import type {IsAbstract} from '@borela-tech/ts-toolbox'

abstract class Animal {}
class Dog extends Animal {}

type A = IsAbstract<typeof Animal> // true
type B = IsAbstract<typeof Dog> // false

MaybePromise<T>

A type that may be synchronous or asynchronous.

import type {MaybePromise} from '@borela-tech/ts-toolbox'

type A = MaybePromise<number> // number | PromiseLike<number>

NotNullable<T>, NotNullish<T>, NotUndefinable<T>, Nullish<T>

Null-handling utility types.

import type {
  NotNullable,
  NotNullish,
  NotUndefinable,
  Nullish,
} from '@borela-tech/ts-toolbox'

type A = NotNullable<string | null>       // string
type B = NotNullish<string | null | undefined> // string
type C = NotUndefinable<string | undefined>    // string
type D = Nullish<string>                 // string | null | undefined

License

Apache-2.0

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages