Skip to content

Instantly share code, notes, and snippets.

@adam-kov
Last active October 11, 2022 06:26
Show Gist options
  • Save adam-kov/eae42890d94de0e2866ef87b85083802 to your computer and use it in GitHub Desktop.
Save adam-kov/eae42890d94de0e2866ef87b85083802 to your computer and use it in GitHub Desktop.
Alpha-numeric sub-list number generator in TypeScript
/**
The function takes care of numbering a sub-list with an arbitrary number of entries.
@param rowNumber The number of the entry in the main list. This will be prepended to the lettering.
Usage example:
```
const list = [['foo', 'bar'], ['bar', 'baz', 'foo']];
list.forEach((sub, i) => {
const generator = subListNumberGenerator(i + 1);
sub.forEach(() => console.log(generator.next().value));
});
```
The output is in the following format *(given that `rowNumber` is `1`)*:
- 1.a.
- 1.b.
...
- 1.aa.
- 1.ab.
...
- 1.az.
- 1.ba.
*/
function* subListNumberGenerator(rowNumber: number, separator = '.'): Generator<string, string, string> {
const letters = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ];
const l = letters.length;
const iterations = [0];
while (true) {
const letter = iterations
.map((i) => letters[i])
.toString()
.replace(/,/g, '');
let i = iterations.length - 1;
iterations[i]++;
if (iterations[i] === l) {
if (iterations.every((value) => value === l || value === l - 1)) iterations.push(0);
while (iterations[i] >= l) {
iterations[i--] = 0;
if (i >= 0) iterations[i]++;
}
if (iterations[0] === l) iterations[0] = 0;
}
yield rowNumber + separator + letter + separator;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment