Skip to content

Instantly share code, notes, and snippets.

@fasiha
Created September 23, 2018 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fasiha/949be357833fbabf76c8e13b3714d3b2 to your computer and use it in GitHub Desktop.
Save fasiha/949be357833fbabf76c8e13b3714d3b2 to your computer and use it in GitHub Desktop.
TypeScript (and, for ES2015 and above, JavaScript) port of Python's `enumerate` to make index-value pairs.
/**
* Generates `[index, value]` 2-tuples, so you can `for (let [index, value] of enumerate(v) {...})`.
* @param v array or iterable iterator to enumerate
* @param n starting number (defaults to 0)
*
* Hat tip: https://docs.python.org/3/library/functions.html#enumerate
*/
export function* enumerate<T>(v: T[]|IterableIterator<T>, n: number = 0): IterableIterator<[number, T]> {
for (let x of v) { yield [n++, x]; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment