Generator

How to use Generator

js

function *gen() {
  yield 1;
  yield 2;
  yield 3;
}
const iter = gen();

iter.next(); // { value: 1, done: false }
iter.next(); // { value: 2, done: false }
iter.next(); // { value: 3, done: false }
iter.next(); // { value: undefined, done: true }

Example of Generator in practice

js

const idGenerator = (function* () {
  let i = 1;
  while (true) {
    yield `component-id-${i++}`;
  }
})();

export const useId = () => ({
  get() {
    return idGenerator.next().value;
  },
});