Skip to content

interpolate

Edit

Replaces nested placeholders with values from an object.

interpolate.ts
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;
});
};
Terminal
wget -O src/lib/interpolate.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/interpolate.ts
interpolate.example.ts
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.
  • missingkeep, empty, or throw; defaults to keep.