Create a prefixed, zero-padded sequential ID generator
An invoicing screen creates draft rows before they are saved, and each row needs a readable, unique id such as INV-0007. Different kinds of records use different prefixes and start numbers, and the “New” button shows a preview of the next id before it is used.
Implement createIdGenerator(prefix, options). It returns a function that produces the next id each time it is called.
const nextId = createIdGenerator(prefix = '', { start = 1, width = 0 } = {});
nextId(); // => the next id (a string), and advances the counter
nextId.peek(); // => the id the next call will return, without advancing
nextId.reset(); // the next call returns the first id again
prefix followed by the counter. The first call uses start, and each call adds 1.width digits. Numbers that already have width digits or more are not cut: with width: 2, 100 stays 100.prefix defaults to '', start to 1, and width to 0 (no padding). Both options are optional, and so is the options object. start and width are non-negative integers.rows.map(nextId).peek() returns the id the next call will return, and changes nothing.reset() sets the counter back to start.peek and reset work when detached: const { peek } = nextId; peek();.const invoiceId = createIdGenerator('INV-', { start: 98, width: 4 });
invoiceId(); // => 'INV-0098'
invoiceId.peek(); // => 'INV-0099'
invoiceId(); // => 'INV-0099'
invoiceId(); // => 'INV-0100'
invoiceId.reset();
invoiceId(); // => 'INV-0098'
const plain = createIdGenerator();
plain(); // => '1'
['a', 'b'].map(plain); // => ['2', '3']
createIdGenerator('t', { start: 0 })(); // => 't0'