Skip to content

Documentation / @ripl/utilities

@ripl/utilities ​

npmlicensesize

The typed helper functions every Ripl package is built from: type guards, numeric helpers, collection joins, comparators, caches and shared types.

This is an internal dependency. Every other @ripl/* package installs it, so you already have it transitively. Install it directly only if you want these helpers in your own code.

Features ​

  • Category-prefixed names — every runtime export starts with its category (type*, number*, array*, object*, set*, string*, function*, comparitor*, predicate*, value*, time*), so related helpers group together in autocomplete.
  • arrayJoin — the left/inner/right join Ripl's charts diff data with. A keyof predicate takes a Map-backed path, so a keyed join is linear rather than quadratic.
  • Numeric helpers for axes and scales — numberExtent, numberNice (rounds to a 1/2/5/10 × power of ten), numberRoundTo, numberClamp, numberFormat.
  • Eight type guards — typeIsArray, typeIsBoolean, typeIsDate, typeIsFunction, typeIsNil, typeIsNumber, typeIsObject, typeIsString.
  • createLRUCache — a bounded Map subclass that evicts the least recently used entry when full. Iteration is least-recently-used first and does not itself affect recency.
  • Function helpers — functionCache (holds a result until invalidated), functionMemoize (keyed by a resolver, first argument by default), functionProduce, functionIdentity, functionNoop.
  • Shared types — OneOrMore<T>, AnyFunction, AnyObject, Disposable, Predicate<L, R>, Indexer<T>, Merge<A, B>, plus GetReadonlyKeys/GetMutableKeys.
  • Zero dependencies, tree-shakable — no runtime dependencies at all, and each helper is a separate export.

Native array methods (forEach, map, filter, reduce, find, flatMap) and Math.min/Math.max are faster than wrappers, so this package has none. It ships only helpers that do something the platform does not.

Installation ​

bash
# npm
npm install @ripl/utilities

# yarn
yarn add @ripl/utilities

# pnpm
pnpm add @ripl/utilities

Quick start ​

typescript
import {
    arrayJoin,
    numberExtent,
    numberNice,
} from '@ripl/utilities';

const {
    left: entries,
    inner: updates,
    right: exits,
} = arrayJoin(data, elements, (datum, element) => datum.id === element.data);

exits.forEach(element => element.destroy());

const [min, max] = numberExtent(data, datum => datum.value);
const axisMax = numberNice(max, true);

Key API ​

ExportWhat it does
arrayJoinLeft/inner/right join for diffing data against drawn elements
arrayGroup / arrayDedupe / arrayIntersection / arrayDifferenceGrouping and set operations over arrays
numberExtent / numberNice / numberClamp / numberFormatThe numeric helpers behind axes and scales
typeIsArray … typeIsStringThe eight type guards
createLRUCacheBounded, recency-ordered Map subclass
functionCache / functionMemoizeResult caching and keyed memoization
stringUniqueIdCryptographically random hex id, 8 characters by default
  • @ripl/core — the rendering core, this package's only direct consumer of note
  • @ripl/web — the browser entry point, and what most projects should install
  • @ripl/charts — where arrayJoin does its data diffing

Documentation ​

The full API reference is at ripl.run/docs/api/@ripl/utilities.

License ​

MIT

Classes ​

ClassDescription
LRUCacheA fixed-capacity Map that evicts the least recently used entry once it is full.

Interfaces ​

InterfaceDescription
ArrayJoinResult of an array join containing unmatched left items, matched pairs, and unmatched right items.
DisposableA resource that can be disposed to release underlying subscriptions or handles.
NumberFormatOptionsOptions for numberFormat: any Intl.NumberFormat option plus a locale and a precision shorthand.
TimeFormatOptionsOptions for timeFormat: any Intl.DateTimeFormat option plus a locale.

Type Aliases ​

Type AliasDescription
AnyAsyncFunctionA loosely-typed async function signature.
AnyFunctionA loosely-typed function signature that accepts and returns anything.
AnyObjectA loosely-typed object with string, number, or symbol keys.
ArrayGroupIdentityA property key or indexer function used to derive group identity from array items.
ArrayJoinPredicateA shared key or predicate function used to match items between two arrays in a join.
CachedFunctionA function wrapper that caches its result after the first invocation until explicitly invalidated.
CollectionIterateeCallback invoked for each item in a collection, receiving the value and its index.
GetMutableKeysExtracts the mutable (non-readonly) property keys from an object type.
GetReadonlyKeysExtracts the readonly property keys from an object type.
IfEqualsConditional type that resolves to A if X and Y are identical, otherwise B.
IndexerDerives a grouping key from a value.
IterableObjectAn object whose values are unknown, suitable for generic iteration.
MemoizedFunctionA function wrapper that caches results per unique key, exposing the underlying cache Map.
MemoizeResolverDerives a cache key from the arguments of a memoized function.
MergeMerges two types, with properties in TB overriding those in TA.
ObjectIterateeCallback invoked for each entry in an object, receiving the key and value.
ObjectReducerReducer callback for folding over object entries into an accumulated result.
OneOrMoreRepresents a single value or an array of values.
PredicateA comparison function that tests whether two values match.
UnionToIntersectionConverts a union type to an intersection type.

Functions ​

FunctionDescription
arrayDedupeReturns a new array with duplicate values removed, preserving insertion order.
arrayDifferenceReturns items from the left array that have no matching counterpart in the right array.
arrayGroupGroups array items by a property key or indexer function into a keyed record.
arrayIntersectionReturns items from the left array that have a matching counterpart in the right array.
arrayJoinPerforms a full join between two arrays, returning entries (left-only), updates (matched), and exits (right-only).
arrayMapRangeCreates an array of the given length by mapping each index through the iteratee.
comparitorDateDate comparator suitable for sorting dates in ascending chronological order.
comparitorNumericNumeric comparator suitable for sorting numbers in ascending order.
comparitorStringLocale-aware string comparator suitable for alphabetical sorting.
createLRUCacheCreates a bounded LRUCache, evicting the single least recently used entry when a write exceeds the limit.
functionCacheWraps a function so its result is computed once and then returned from cache on subsequent calls until invalidate() is called.
functionIdentityReturns the value it receives unchanged, useful as a default transform or placeholder.
functionMemoizeMemoizes a function by caching results keyed by the resolver (defaults to the first argument).
functionNoopA do-nothing function, useful as a default callback or placeholder.
functionProduceWraps a value or factory function into a consistent factory that always returns the value.
numberClampConstrains a value to the inclusive range between lower and upper bounds.
numberExtentComputes the [min, max] extent of an array using the given numeric accessor.
numberFormatFormats a number as a locale-aware string. Supports decimal, percent, and currency styles; compact/scientific/engineering notation; grouping; and fraction-digit control (with precision as a shorthand for maximumFractionDigits). Non-numeric values fall back to String.
numberFractionalReturns the fractional part of a number (e.g. numberFractional(3.7) → 0.7).
numberMaxOfReturns the maximum numeric value extracted from an array via the accessor (-Infinity when empty).
numberMinOfReturns the minimum numeric value extracted from an array via the accessor (Infinity when empty).
numberNextPowerOfNReturns the smallest power of base that is greater than or equal to minimum, starting from 1.
numberNiceRounds a value to a "nice" human-readable number (1, 2, 5, or 10 scaled by the appropriate power of ten).
numberRoundToRounds a number to at most precision decimal places, stripping any trailing zeros.
numberSumComputes the sum of an array of numbers, or of values mapped through an optional iteratee.
objectForEachIterates over the enumerable properties of an object, invoking the iteratee for each key-value pair.
objectFreezeCreates a shallow frozen copy of the given object.
objectMapMaps over the enumerable properties of an object, producing a new object with transformed values.
objectReduceReduces the enumerable properties of an object into a single accumulated value.
predicateIdentityTests strict reference equality between two values.
predicateKeyTests whether two objects share the same value at a given key.
setFilterFilters a Set, returning a new Set containing only values that satisfy the predicate.
setFindSearches a Set for the first value that satisfies the predicate.
setFlatMapFlat-maps over a Set, concatenating the arrays returned by the iteratee into a new Set.
setForEachIterates over each value in a Set, invoking the iteratee with the value and a running index.
setMapMaps over a Set, producing a new Set with each value transformed by the iteratee.
stringEqualsCase-insensitive string equality check.
stringUniqueIdGenerates a cryptographically random hexadecimal string of the specified length (default 8 characters / 32 bits).
timeFormatFormats a Date (or epoch millisecond value) as a locale-aware string via Intl.DateTimeFormat. With no field options a short year/month/day format is used. Passed values explicitly by axes and tooltips; never bound to a scale.
typeIsArrayChecks whether a value is an array.
typeIsBooleanChecks whether a value is a boolean.
typeIsDateChecks whether a value is a Date instance.
typeIsFunctionChecks whether a value is a function.
typeIsNilChecks whether a value is null or undefined.
typeIsNumberChecks whether a value is a number.
typeIsObjectChecks whether a value is a non-null object.
typeIsStringChecks whether a value is a string.
valueOneOrMoreNormalizes a single value or array into a guaranteed array.