Skip to content

Changelog — Helpers by version

FunctionCategoryDescription
DEFAULT_PERCENTAGE_TIERSciDefault tiers, geared towards coverage/quality-gate style percentages. Follows shields.io color conventions: brightgreen >= 100, green >= 90, yellow >= 80, orange >= 60.
formatProgressBarstringFormats a value as a text progress bar, repeating filledChar/emptyChar across width cells proportional to value / max. value is clamped to [0, max] before computing the ratio — out-of-range values (negative, above max) produce an empty or fully-filled bar instead of throwing. Non-finite max (NaN, Infinity) is treated as 0, yielding an empty bar.
incrementPrereleaseversionIncrements the prerelease portion of a semantic version — the semantics npm version prerelease --preid <id> uses, not covered by increment (which only handles 'major' | 'minor' | 'patch'). - No current prerelease (a release version) → bumps patch and starts a new prerelease line at <prereleaseId>.0 (a prerelease of the version itself, e.g. 1.2.3, would already be released). - Same prerelease type as the current version → increments its counter. - Different prerelease type (e.g. alphabeta) → resets the counter to 0. Input prerelease can be any shape, but only the first two parts are considered; output is always normalized to <prereleaseId>.<number>. Build metadata, if any, is dropped — it’s tied to the specific build that produced the input version, not the new one. A leading v is preserved if present, matching increment’s behavior (parse/ stringify alone would strip it — see their docs).
percentageToTierciMaps a numeric percentage to a tier (icon, color, label) using configurable thresholds. Tiers are matched by their highest min that is <= value; a value below every tier’s min (e.g. a negative percentage, or custom tiers that don’t cover down to 0) falls back to the tier with the lowest min — there’s always a match as long as tiers is non-empty.
FunctionCategoryDescription
argbToRgbcolorConverts a 32-bit packed ARGB integer (as used by e.g. Chromium’s Local State profile background_color field) into a CSS rgb() string. The alpha byte (top 8 bits) is read but discarded — the result is always opaque.
BrandtypeBrands a base type T with a phantom tag B to create a nominal type. Two Brand<string, 'UserId'> and Brand<string, 'Email'> are structurally identical strings at runtime, but TypeScript treats them as distinct types at the call site — preventing accidental mix-ups. Use a const-assertion cast at the creation boundary: ts type UserId = Brand<string, 'UserId'>; const toUserId = (s: string): UserId => s as UserId;
cloneobjectCreates a shallow copy of a value — one level deep, unlike cloneDeep. Unlike a plain { ...value } spread, this correctly reconstructs Date, Map, Set, and arrays instead of producing an empty (or wrong-shaped) plain object for them. Primitives are returned as-is. Any other object (including class instances not listed above) has its own enumerable string keys shallow-copied into a plain object — the same fallback cloneDeep uses, so the two stay consistent for types neither one special-cases.
combineSortFnsarrayChains multiple sort functions into a single comparator: the first function decides the order unless it reports a tie (0), in which case the next function is tried, and so on. Lets you compose comparators of different kinds — e.g. a boolean-property comparator from createSortByBooleanFn followed by a string-property comparator from createSortByStringFn — which a single multi-key call cannot express, since that coerces every key to the same comparison type.
createSortByBooleanFnarrayCreates a sort function for objects by a boolean property. Values are coerced with Boolean() before comparing, so null, undefined, 0, and '' behave as false, and any other truthy value behaves as true.
dedentstringStrips the common leading whitespace from every line of a multi-line string, and trims a single leading/trailing blank line if present. Lets you write readable, indented multi-line strings in source code (typically template literals) without that indentation leaking into the output.
DeepGettypeResolves the value type at a given Path within T. Returns unknown when any key in Path is not present in the corresponding level of T. An empty path resolves to T itself. A path segment that goes through an optional property keeps the result nullable (V | undefined) instead of degrading to unknown.
DeepSettypeProduces the type of T after replacing the value at Path with V. When a key in Path is absent from the corresponding level of T, that level (and everything below it) is added as a new field instead of resolving to never — mirroring how set() creates intermediate objects at runtime.
escapeRegExpstringEscapes regular expression metacharacters (. * + ? ^ $ { } ( ) | [ ] \\) in a string so it can be safely embedded in a RegExp pattern. Use this before building a RegExp from untrusted or dynamic input — without it, characters like . or ( change the pattern’s meaning instead of being matched literally.
flattenobjectFlattens a nested object into a single-level object whose keys are the dot-notation path to each leaf value. The inverse of unflatten. Only plain objects are recursed into — arrays, Date, Map, RegExp, class instances, and empty plain objects {} are kept as opaque leaf values. This keeps flatten/unflatten a clean, invertible pair: arrays can’t be losslessly told apart from plain objects once reduced to dotted keys, so this implementation doesn’t attempt it. Caveat shared by every dotted-path flattening scheme: a key that itself contains a literal . is indistinguishable from real nesting once flattened ({ 'a.b': 1 } and { a: { b: 1 } } both produce { 'a.b': 1 }).
hexToRgbcolorParses a hex color string (#rgb, #rgba, #rrggbb, #rrggbbaa — the leading # is optional) into its RGB(A) channels.
hslToRgbcolorConverts an HSL(A) color into RGB(A).
isCssColorguardChecks whether a value is a syntactically-safe, plain CSS color: a hex color (#rgb, #rgba, #rrggbb, #rrggbbaa), a functional notation (rgb(), rgba(), hsl(), hsla()), or a single-word named color (red, rebeccapurple). Intended to sanitize a color value before interpolating it into inline style/cssText — it does not implement the full CSS color grammar or validate named colors against the real keyword list, it only rejects characters ({, }, ;, “) or shapes that could smuggle extra CSS declarations into the surrounding rule.
isSetguardChecks if a value is a Set instance.
isWeakMapguardChecks if a value is a WeakMap instance.
isWeakSetguardChecks if a value is a WeakSet instance.
KeysOfTypetypeExtracts the keys of T whose values extend V. Optional properties are matched by their non-nullable value type, so an optional string property still counts as a string key.
NullabletypeAdds null to a type (T | null). Useful as a shorthand when explicit nullability should be expressed in function signatures or generic constraints.
NullishtypeAdds null and undefined to a type (T | null | undefined). Alias of Maybe.
omitByobjectCreates a new object without the own enumerable entries for which predicate returns true. Complements omit for when the keys to remove aren’t known ahead of time — omit takes an explicit key list, omitBy takes a predicate.
OmitByValuetypeConstructs a type by omitting all entries of T whose values extend V. Optional properties are matched by their non-nullable value type, so an optional string property is omitted the same as a required one.
OptionalKeystypeExtracts the optional keys of an object type T.
parseDurationdateParses a compact duration string (as produced by formatDuration, e.g. "1h 23m 45s") back into milliseconds. Accepts any combination/order of h/m/s segments, with or without spaces between them ("1h30m" and "1h 30m" both work). A single leading - negates the whole duration, matching formatDuration’s output. Returns null when no valid segment is found.
parsePropertyPathobjectParses a dot/bracket-notation property path into an array of string/number key segments — the same notation accepted by get and set. - Dot separators (.) split segments; each segment becomes a string key. - Bracket indices ([n]) become number keys. - A leading . is treated as “current level” and stripped before parsing, so .[0][0] and .a.ba.b. - Empty string (or a bare .) returns [''] (addresses the '' key on the root object). - Consecutive dots (a..b) produce an empty-string segment: ['a', '', 'b']. Results are cached (up to 500 distinct path strings, oldest evicted first) since real-world callers tend to reuse a small, fixed set of literal paths.
pickByobjectCreates a new object with only the own enumerable entries for which predicate returns true. Complements pick for when the keys to keep aren’t known ahead of time — pick takes an explicit key list, pickBy takes a predicate.
PickByValuetypeConstructs a type by picking all entries of T whose values extend V. Optional properties are matched by their non-nullable value type, so an optional string property is picked the same as a required one.
PrettifytypeFlattens an intersection type into a single readable object type. IDE tooltips for intersections like A & B & C often show the raw intersection instead of the resolved shape. Wrapping with Prettify forces TypeScript to expand and display the fully-resolved type. Distributes over unions, so each member is prettified independently instead of collapsing to their shared keys.
removeDiacriticsstringRemoves diacritical marks (accents) from a string, e.g. 'café''cafe'. Works by Unicode-decomposing each character into its base letter plus combining marks ('é''e' + a combining acute accent), then stripping the marks. Same technique already used internally by slugify.
replaceOrAppendarrayReturns a new array with the first item matching predicate replaced by item — or item appended at the end if no match is found. The common “upsert into a list” pattern.
RequiredKeystypeExtracts the required (non-optional) keys of an object type T.
rgbToHexcolorConverts an RGB(A) color into a hex color string. r/g/b are clamped to 0-255 and rounded to the nearest integer before formatting. The alpha channel is only appended (as #rrggbbaa) when it is below 1 — fully opaque colors format as the plain 6-digit #rrggbb.
rgbToHslcolorConverts an RGB(A) color into HSL(A). h/s/l are rounded to 1 decimal place to avoid floating-point noise.
settlepromiseRuns an array of promises concurrently and partitions the outcomes instead of rejecting on the first failure, unlike Promise.all. Built on top of Promise.allSettled, but returns fulfilled values and rejection reasons already split apart so callers don’t need to inspect status themselves.
symmetricDifferencearrayReturns the symmetric difference between two arrays: items present in exactly one of the two arrays (in either, but not both). null and undefined are treated as empty arrays.
togglearrayReturns a new array with item removed if present, or appended if absent — the common “toggle a selection” pattern. By default, presence is checked with SameValueZero equality (like Array.prototype.includes). Pass key to compare by a derived identity instead — useful for toggling objects by id rather than by reference.
unaryfunctionCreates a function that calls fn with only its first argument, discarding any others. Prevents the classic footgun where a callback expecting extra positional arguments is passed directly to Array.prototype.map: ['1', '2', '3'].map(parseInt) silently passes the array index as parseInt’s radix argument, producing [1, NaN, NaN].
unescapeHtmlstringUnescapes the HTML entities &amp;, &lt;, &gt;, &quot;, and &#39; back to &, <, >, ", and '. This is the exact inverse of escapeHtml — it only recognizes the five entities that function produces, not the full HTML entity set (no &nbsp;, no numeric code points beyond &#39;, etc.).
unflattenobjectRebuilds a nested object from a single-level object whose keys are dot-notation paths. The inverse of flatten. Uses set internally, so intermediate nodes are always created as plain objects (never arrays — see flatten’s doc for why), and any key segment equal to __proto__, constructor, or prototype is silently rejected (same prototype-pollution guard as set).
UnionToIntersectiontypeConverts a union type to an intersection type: A | B | CA & B & C. Uses conditional-type distribution and the contravariant position of a function parameter to collapse the union into an intersection.
unsetobjectRemoves the value at a dot/bracket-notation path or explicit key array, mutating the object in place. Uses the same path syntax as get/set. A missing intermediate segment is a no-op (nothing to remove), not an error. As with set, any path containing a string segment equal to __proto__, constructor, or prototype is rejected and the object is returned unchanged. The removed key stops appearing in Object.keys/for...in — unlike setting it to undefined, which would keep the key present.
updateobjectUpdates the value at a path by applying a function to its current value, creating intermediate objects as needed. Equivalent to set(obj, path, updater(get(obj, path))) in a single call. Uses the same path syntax and type-inference rules as get and set — see those for the full behavior (string vs. PropertyKey[] paths, prototype-pollution guarding, etc.).
ValueOftypeProduces a union of all value types of an object type T.

Looking for older releases? See the v2 changelog.