Skip to content

Instantly share code, notes, and snippets.

@justintaddei
Last active June 12, 2023 07:19
Show Gist options
  • Save justintaddei/affb148b066ea7296b93ff2fae1090ef to your computer and use it in GitHub Desktop.
Save justintaddei/affb148b066ea7296b93ff2fae1090ef to your computer and use it in GitHub Desktop.
Increment alphanumeric sequence in JavaScript
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)
@MarcoLasticot
Copy link

MarcoLasticot commented Nov 10, 2021

Well not exactly, but I figued out how to do it

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 areAllNine = (str) => {
    return str.split("").filter((char) => char.charCodeAt(0) === NINE).length === str.split("").length;
};

const areAllNineAndZ = (str) => {
    return str.split("").filter((char) => isDigit(char.charCodeAt(0))).length === str.split("").filter((char) => char.charCodeAt(0) === NINE).length && str.split("").filter((char) => !isDigit(char.charCodeAt(0))).length === str.split("").filter((char) => char.charCodeAt(0) === Z).length;
};

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;
	
    if (areAllNine(str)) {
        return str.replace("9", "A").replace(/\9/gi, "0");
    }
    if (areAllNineAndZ(str)) {
        return str.replace("Z9", "ZA").replace(/\9/gi, "0");
    }

    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