one day of code

Generate sequence for given index

January 04, 2021

Have you ever wondered how are those “a, b, c, …, aab, aac, … aaz” class names generated? Here’s the generalized snippet. You can literally put any char in the list and get the combination for the given index.

/**
* Generate combination from custom chars
* @param index {Number} Combination at index
* @param chars {String[]} Array of chars to be used
* @returns {String}
*/
function getCombination(index, chars) {
return index < 0
? ''
: getCombination(Math.floor(index / chars.length) - 1, chars) +
chars[index % chars.length].toString()
}

Written by Milan Miljkovic — a tech enthusiast and design system practitioner.