All files / Rindu/utils conjuction.ts

95% Statements 19/20
100% Branches 9/9
100% Functions 2/2
95% Lines 19/20

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    18x         28x 28x   28x 28x   47x 32x 32x   15x   47x 47x     28x 28x 28x 28x 69x         28x 20x   8x            
import { ReactNode } from "react";
 
export function conjuction(
  value: ReactNode[] | string,
  locale: string,
  options: Intl.ListFormatOptions = { type: "unit" }
): ReactNode[] | string {
  const serializedValue: Array<string> = [];
  const reactNodes = new Map<string, ReactNode>();
 
  let index = 0;
  for (const item of value) {
    let serializedItem;
    if (typeof item === "object") {
      serializedItem = String(index);
      reactNodes.set(serializedItem, item);
    } else {
      serializedItem = String(item);
    }
    serializedValue.push(serializedItem);
    index++;
  }
 
  try {
    const listFormat = new Intl.ListFormat(locale, options);
    const formattedParts = listFormat.formatToParts(serializedValue);
    const result = formattedParts.map((part) =>
      part.type === "literal"
        ? part.value
        : (reactNodes.get(part.value) ?? part.value)
    );
 
    if (reactNodes.size > 0) {
      return result;
    } else {
      return result.join("");
    }
  } catch {
    return String(value);
  }
}