Documentation / @ripl/utilities
@ripl/utilities ​
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. Akeyofpredicate takes aMap-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 boundedMapsubclass 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>, plusGetReadonlyKeys/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) andMath.min/Math.maxare 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/utilitiesQuick 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 ​
| Export | What it does |
|---|---|
arrayJoin | Left/inner/right join for diffing data against drawn elements |
arrayGroup / arrayDedupe / arrayIntersection / arrayDifference | Grouping and set operations over arrays |
numberExtent / numberNice / numberClamp / numberFormat | The numeric helpers behind axes and scales |
typeIsArray … typeIsString | The eight type guards |
createLRUCache | Bounded, recency-ordered Map subclass |
functionCache / functionMemoize | Result caching and keyed memoization |
stringUniqueId | Cryptographically random hex id, 8 characters by default |
Related packages ​
@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— wherearrayJoindoes its data diffing
Documentation ​
The full API reference is at ripl.run/docs/api/@ripl/utilities.
License ​
Classes ​
| Class | Description |
|---|---|
| LRUCache | A fixed-capacity Map that evicts the least recently used entry once it is full. |
Interfaces ​
| Interface | Description |
|---|---|
| ArrayJoin | Result of an array join containing unmatched left items, matched pairs, and unmatched right items. |
| Disposable | A resource that can be disposed to release underlying subscriptions or handles. |
| NumberFormatOptions | Options for numberFormat: any Intl.NumberFormat option plus a locale and a precision shorthand. |
| TimeFormatOptions | Options for timeFormat: any Intl.DateTimeFormat option plus a locale. |
Type Aliases ​
| Type Alias | Description |
|---|---|
| AnyAsyncFunction | A loosely-typed async function signature. |
| AnyFunction | A loosely-typed function signature that accepts and returns anything. |
| AnyObject | A loosely-typed object with string, number, or symbol keys. |
| ArrayGroupIdentity | A property key or indexer function used to derive group identity from array items. |
| ArrayJoinPredicate | A shared key or predicate function used to match items between two arrays in a join. |
| CachedFunction | A function wrapper that caches its result after the first invocation until explicitly invalidated. |
| CollectionIteratee | Callback invoked for each item in a collection, receiving the value and its index. |
| GetMutableKeys | Extracts the mutable (non-readonly) property keys from an object type. |
| GetReadonlyKeys | Extracts the readonly property keys from an object type. |
| IfEquals | Conditional type that resolves to A if X and Y are identical, otherwise B. |
| Indexer | Derives a grouping key from a value. |
| IterableObject | An object whose values are unknown, suitable for generic iteration. |
| MemoizedFunction | A function wrapper that caches results per unique key, exposing the underlying cache Map. |
| MemoizeResolver | Derives a cache key from the arguments of a memoized function. |
| Merge | Merges two types, with properties in TB overriding those in TA. |
| ObjectIteratee | Callback invoked for each entry in an object, receiving the key and value. |
| ObjectReducer | Reducer callback for folding over object entries into an accumulated result. |
| OneOrMore | Represents a single value or an array of values. |
| Predicate | A comparison function that tests whether two values match. |
| UnionToIntersection | Converts a union type to an intersection type. |
Functions ​
| Function | Description |
|---|---|
| arrayDedupe | Returns a new array with duplicate values removed, preserving insertion order. |
| arrayDifference | Returns items from the left array that have no matching counterpart in the right array. |
| arrayGroup | Groups array items by a property key or indexer function into a keyed record. |
| arrayIntersection | Returns items from the left array that have a matching counterpart in the right array. |
| arrayJoin | Performs a full join between two arrays, returning entries (left-only), updates (matched), and exits (right-only). |
| arrayMapRange | Creates an array of the given length by mapping each index through the iteratee. |
| comparitorDate | Date comparator suitable for sorting dates in ascending chronological order. |
| comparitorNumeric | Numeric comparator suitable for sorting numbers in ascending order. |
| comparitorString | Locale-aware string comparator suitable for alphabetical sorting. |
| createLRUCache | Creates a bounded LRUCache, evicting the single least recently used entry when a write exceeds the limit. |
| functionCache | Wraps a function so its result is computed once and then returned from cache on subsequent calls until invalidate() is called. |
| functionIdentity | Returns the value it receives unchanged, useful as a default transform or placeholder. |
| functionMemoize | Memoizes a function by caching results keyed by the resolver (defaults to the first argument). |
| functionNoop | A do-nothing function, useful as a default callback or placeholder. |
| functionProduce | Wraps a value or factory function into a consistent factory that always returns the value. |
| numberClamp | Constrains a value to the inclusive range between lower and upper bounds. |
| numberExtent | Computes the [min, max] extent of an array using the given numeric accessor. |
| numberFormat | Formats 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. |
| numberFractional | Returns the fractional part of a number (e.g. numberFractional(3.7) → 0.7). |
| numberMaxOf | Returns the maximum numeric value extracted from an array via the accessor (-Infinity when empty). |
| numberMinOf | Returns the minimum numeric value extracted from an array via the accessor (Infinity when empty). |
| numberNextPowerOfN | Returns the smallest power of base that is greater than or equal to minimum, starting from 1. |
| numberNice | Rounds a value to a "nice" human-readable number (1, 2, 5, or 10 scaled by the appropriate power of ten). |
| numberRoundTo | Rounds a number to at most precision decimal places, stripping any trailing zeros. |
| numberSum | Computes the sum of an array of numbers, or of values mapped through an optional iteratee. |
| objectForEach | Iterates over the enumerable properties of an object, invoking the iteratee for each key-value pair. |
| objectFreeze | Creates a shallow frozen copy of the given object. |
| objectMap | Maps over the enumerable properties of an object, producing a new object with transformed values. |
| objectReduce | Reduces the enumerable properties of an object into a single accumulated value. |
| predicateIdentity | Tests strict reference equality between two values. |
| predicateKey | Tests whether two objects share the same value at a given key. |
| setFilter | Filters a Set, returning a new Set containing only values that satisfy the predicate. |
| setFind | Searches a Set for the first value that satisfies the predicate. |
| setFlatMap | Flat-maps over a Set, concatenating the arrays returned by the iteratee into a new Set. |
| setForEach | Iterates over each value in a Set, invoking the iteratee with the value and a running index. |
| setMap | Maps over a Set, producing a new Set with each value transformed by the iteratee. |
| stringEquals | Case-insensitive string equality check. |
| stringUniqueId | Generates a cryptographically random hexadecimal string of the specified length (default 8 characters / 32 bits). |
| timeFormat | Formats 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. |
| typeIsArray | Checks whether a value is an array. |
| typeIsBoolean | Checks whether a value is a boolean. |
| typeIsDate | Checks whether a value is a Date instance. |
| typeIsFunction | Checks whether a value is a function. |
| typeIsNil | Checks whether a value is null or undefined. |
| typeIsNumber | Checks whether a value is a number. |
| typeIsObject | Checks whether a value is a non-null object. |
| typeIsString | Checks whether a value is a string. |
| valueOneOrMore | Normalizes a single value or array into a guaranteed array. |