Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created March 22, 2019 19:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save miguelmota/021a84516c21fc71f043d0f988eb5866 to your computer and use it in GitHub Desktop.
Save miguelmota/021a84516c21fc71f043d0f988eb5866 to your computer and use it in GitHub Desktop.
Node.js iota (Golang iota equivalent)
const iota = (() => { let n = 0; return () => n++ })()
const myEnum = {
foo: iota(), // 0
bar: iota(), // 1
baz: iota(), // 2
qux: iota(), // 3
}
@fannyhasbi
Copy link

Thanks, this helps!

@crra
Copy link

crra commented Oct 15, 2020

If you want to set the start index:

const iota = (() => {
  let n;
  return (start = 0) => {
    n = (n !== undefined && n + 1) || start;
    return n;
  };
})();

const myEnum = Object.freeze({
  foo: iota(-1), // -1
  bar: iota(), // 0
  baz: iota(), // 1
  qux: iota(), // 2
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment