I'm trying to make a function that returns the next string. So if I input 'A' it returns 'B' etc. And i would like to pass as a parameter also an increment so 'AE' with an increment of 30 would be 'BI' and 'CM'(edit: it was 'CM' not 'ZM') would be 'AAQ'.
edit:
(input -> output)
Increment of 1
"A" -> "B"
"B" -> "C"
...
"Z" -> "AA"
...
"AZ" -> "BZ"
Increment of 30(the 30 is an example it can be anything)
"A" -> "AE"
"AE" -> "BI"
"BI" -> "CM"
"CM" -> "DQ"
Essentially, I want the next excel column. But i want to be able to increment. So with an increment of 30 i don't want the next one I want the 30 after if that makes sense.
CodePudding user response:
You're looking for an implementation of the bijective base 26 system, also known as "bijective hexavigesimal". There are many ways to do this; here's one possibility, involving converting such values to number
s before performing calculations on them, and then converting back from number
s afterward:
const baseCode = "A".charCodeAt(0) - 1;
function toBb26(n: number): string {
let chars: string[] = [];
while (n > 0) {
const d = ((n - 1) % 26) 1;
chars.unshift(String.fromCharCode(baseCode d));
n = (n - d) / 26;
}
return chars.join("");
}
function fromBb26(x: string): number {
let ret = 0;
for (const c of Array.from(x)) {
ret *= 26;
ret = (c.charCodeAt(0) - baseCode);
}
return ret;
}
function increment(x: string, n: number=1) {
return toBb26(fromBb26(x) n);
}
console.log(increment("A")) // B
console.log(increment("AE", 30)) // BI
console.log(increment("ZM", 30)) // AAQ
I haven't rigorously tested this, and it might not be performance-optimized for your use case, and there are probably existing JS libraries that do this, etc. etc.