interpolate
EditReplaces nested placeholders with values from an object.
export type MissingInterpolationValue = "keep" | "empty" | "throw";export type InterpolateOptions = { missing?: MissingInterpolationValue;};
const readPath = (object: unknown, path: string): unknown => { let current = object; for (const segment of path.split(".")) { if (current === null || typeof current !== "object" || !Object.prototype.hasOwnProperty.call(current, segment)) return undefined; current = Reflect.get(current, segment); } return current;};
/** Replaces {{ dot.path }} placeholders with own properties from a values object. */export const interpolate = ( template: string, values: object, { missing = "keep" }: InterpolateOptions = {}): string => { return template.replace(/{{\s*([^{}]+?)\s*}}/g, (placeholder, path: string) => { const value = readPath(values, path.trim()); if (value !== undefined && value !== null) return String(value); if (missing === "empty") return ""; if (missing === "throw") throw new ReferenceError(`Missing interpolation value: ${path.trim()}`); return placeholder; });};Download
Section titled “Download”wget -O src/lib/interpolate.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/interpolate.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/functions "$temp_dir" && mv "$temp_dir/interpolate.ts" src/lib/interpolate.ts && rm -r "$temp_dir"Examples
Section titled “Examples”import { interpolate } from "./interpolate";
const message = interpolate( "Hello {{ user.name }}, you have {{ count }} tasks.", { user: { name: "Ada" }, count: 3 });template(string) — Text containing{{ dot.path }}placeholders.values(object) — Own properties used for replacements.missing—keep,empty, orthrow; defaults tokeep.