All files / string create-id-generator.ts

100% Statements 4/4
100% Branches 0/0
100% Functions 2/2
100% Lines 4/4

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                        3x 3x 5x 5x      
/**
 * Creates a generator of readable unique ids: `gauge-1`, `gauge-2`… for SVG gradients, clip paths or markers.
 * Each generator counts on its own: use one prefix per generator.
 *
 * @param prefix - The start of every id, such as the component name.
 * @returns A function returning the next id at each call.
 * @example
 * const nextGradientId = createIdGenerator('gauge-gradient');
 * gradient.id = nextGradientId(); // 'gauge-gradient-1'
 * arc.setAttribute('stroke', `url(#${gradient.id})`);
 */
export function createIdGenerator(prefix: string): () => string {
  let counter = 0;
  return (): string => {
    counter += 1;
    return `${prefix}-${counter}`;
  };
}