Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Generate invoice IDs with a generator in JavaScript

9 A generator-based id factory

fair

Write an id factory as a generator: it yields INV-0001, INV-0002 and so on for ever, and next(n) reseats the counter at n. Two factories must never collide, and the counter must not be reachable from outside.

Stuck? Three hints, smallest first
  1. 1. String(n).padStart(4, ‘0’) gives the zero padding.
  2. 2. Read the incoming value from the yield expression and decide between it and n + 1.
  3. 3. The counter is a local variable in a suspended frame, so there is no property on the generator object to find.

The answer

function* idFactory(prefix, start = 1) {
  let n = start;
  while (true) {
    const reseat = yield `${prefix}-${String(n).padStart(4, '0')}`;
    n = reseat === undefined ? n + 1 : reseat;
  }
}

const invoices = idFactory('INV');
const ids = [invoices.next().value, invoices.next().value, invoices.next().value];
const jumped = invoices.next(100).value;
const carriedOn = invoices.next().value;

const twoStreams = (() => {
  const a = idFactory('LAG');
  const b = idFactory('ABJ');
  return [a.next().value, b.next().value, a.next().value, b.next().value];
})();

const long = (() => { const g = idFactory('X'); g.next(); return g.next(99999).value; })();

console.log('sequential :', ids);
console.log('reseated   :', jumped, '->', carriedOn);
console.log('two streams:', twoStreams);
console.log('own keys on the generator object:', Object.keys(invoices));

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('ids are sequential and zero-padded', ids, ['INV-0001', 'INV-0002', 'INV-0003']);
test('sending a number reseats the counter', jumped, 'INV-0100');
test('and it carries on from there', carriedOn, 'INV-0101');
test('two factories never collide', twoStreams, ['LAG-0001', 'ABJ-0001', 'LAG-0002', 'ABJ-0002']);
test('the counter is private: there is no own property to poke', Object.keys(invoices).length, 0);
test('a factory is never done', invoices.next().done, false);
test('padStart only pads, it never truncates', long, 'X-99999');
test('a custom start is respected', idFactory('R', 42).next().value, 'R-0042');

This is the closure-plus-counter pattern from part 1, with the counter moved into a suspended frame instead of a closed-over variable. Both give privacy; the generator additionally gives you the iterator protocol for free, so take(idFactory(‘INV’), 5) works with no extra code and the factory can be handed to anything that consumes an iterable.

Object.keys(invoices).length === 0 is worth asserting because it is a genuine guarantee, not a convention. There is no underscore-prefixed field to reach in and set, and no way to observe the counter except by advancing it.

The reseat path is where care is needed. Testing reseat === undefined rather than truthiness is deliberate: next(0) should legitimately reseat to zero, and reseat || n + 1 would silently ignore it. That is the same class of bug as value || fallback eating a valid 0 or ‘’.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.