All files / Rindu/utils templateReplace.ts

87.5% Statements 21/24
66.66% Branches 6/9
100% Functions 1/1
87.5% Lines 21/24

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 40 41 42 43 44 45 4646x       11x       10x 10x 10x 10x 10x   10x 13x 13x 13x       13x 13x         13x 1x     13x         13x 13x     10x 10x   10x    
import { cloneElement, isValidElement, ReactNode } from "react";
 
type Replacements = ReactNode[] | string[] | Record<string, ReactNode | string>;
 
export function templateReplace(
  template: string,
  replacements: Replacements
): string | ReactNode[] {
  const pattern = /\{(\w+)\}/g;
  const result: ReactNode[] = [];
  let lastSubstrIndex = 0;
  let match: RegExpExecArray | null = null;
  let isReact = false;
 
  while ((match = pattern.exec(template))) {
    const [matchStr, key] = match;
    const index = match.index;
    const substring = template.substring(lastSubstrIndex, index);
 
    let el: ReactNode | string;
 
    if (Array.isArray(replacements)) {
      el = replacements[Number(key)];
    } else E{
      el = replacements[key];
    }
 
    if (!el && el !== "" && el !== 0) {
      el = matchStr;
    }
 
    Iif (isValidElement(el)) {
      isReact = true;
      el = cloneElement(el, { key });
    }
 
    result.push(substring, el);
    lastSubstrIndex = index + matchStr.length;
  }
 
  const tail = template.substring(lastSubstrIndex);
  result.push(tail);
 
  return isReact ? result : result.join("");
}