createIdGenerator function
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.
ts
import { createIdGenerator } from 'utils';Signature
ts
export function createIdGenerator(prefix: string): () => stringParameters
| Name | Description |
|---|---|
prefix | The start of every id, such as the component name. |
Returns
A function returning the next id at each call.
Example
ts
const nextGradientId = createIdGenerator('gauge-gradient');
gradient.id = nextGradientId(); // 'gauge-gradient-1'
arc.setAttribute('stroke', `url(#${gradient.id})`);Tests
Line coverage: 100 %.
- ✅ generates increasing ids with the prefix
- ✅ counts separately for each generator
Source
src/string/create-id-generator.ts (on GitHub)
Source code
ts
/**
* 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}`;
};
}Test file
ts
import { createIdGenerator } from './create-id-generator';
describe(createIdGenerator, () => {
it('generates increasing ids with the prefix', () => {
const nextId = createIdGenerator('alarm');
expect([nextId(), nextId(), nextId()]).toStrictEqual(['alarm-1', 'alarm-2', 'alarm-3']);
});
it('counts separately for each generator', () => {
const first = createIdGenerator('a');
const second = createIdGenerator('b');
first();
expect(second()).toBe('b-1');
});
});Keywords: create, id, generator, strings, function