Last active
June 12, 2023 07:19
-
-
Save justintaddei/affb148b066ea7296b93ff2fae1090ef to your computer and use it in GitHub Desktop.
Increment alphanumeric sequence in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const A = 65 | |
const Z = 90 | |
const ZERO = 48 | |
const NINE = 57 | |
const isDigit = (char) => char >= 48 && char <= 57 | |
const codeToChar = (code) => String.fromCharCode(code) | |
const setChar = (index, char, str) => { | |
const charArr = [...str] | |
charArr.splice(index, 1, char) | |
return charArr.join('') | |
} | |
const incDigit = (char) => char + 1 > NINE ? ZERO : char + 1 | |
const incLetter = (char) => char + 1 > Z ? A : char + 1 | |
const increment = (str, place = str.length - 1) => { | |
if (place < 0) return str; | |
const char = str.charCodeAt(place) | |
const nextChar = isDigit(char) ? incDigit(char) : incLetter(char) | |
const carry = nextChar - char !== 1; | |
str = setChar(place, codeToChar(nextChar), str) | |
if (carry) | |
return increment(str, --place) | |
else return str | |
} | |
export const incrementAlphanumeric = (str) => increment(str) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Well not exactly, but I figued out how to do it