All files fill-template.ts

100% Statements 15/15
100% Branches 4/4
100% Functions 1/1
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 401x                                               1x 4x 4x 4x 4x 4x   4x 4x 4x 5x 5x 5x 4x 4x  
import { empty } from './unicode.ts';
/**
 * Options for the {@link fillTemplate} function
 * @group String
 * @category Operations
 */
export type FillTemplateOptions = {
  /** The opening field delimiter */
  open?: string;
  /** The closing field delimiter */
  close?: string;
};
 
/**
 * Fill a template with supplied values
 * @param input - The template
 * @param values - A dictionary of name-values used to fill in values in the template
 * @param options - see {@link FillTemplateOptions}
 * @defaultValue open '\{\{'
 * @defaultValue close '\}\}'
 * @returns template with values replaced
 * @group String
 * @category Operations
 */
export function fillTemplate(
  input: string,
  values: Record<string, string | undefined>,
  { open = '{{', close = '}}' }: FillTemplateOptions = {},
): string {
  let argInput = input;
 
  for (const match of argInput.match(
    new RegExp(`${RegExp.escape(open)}(.+?)${RegExp.escape(close)}`, 'ug'),
  ) ?? []) {
    const key = match.slice(open.length, -close.length).trim();
    argInput = argInput.replace(match, values[key] ?? empty);
  }
  return argInput;
}