0
\$\begingroup\$

Is there any way to make this function shorter? I want to calculate the characters up to 1.000.000. My reverse function looks like the same also...

function toABC(num) {
switch (num) {
    case 1: return 'A';
    case 2: return 'B';
    case 3: return 'C';
    case 4: return 'D';
    case 5: return 'E';
    case 6: return 'F';
    case 7: return 'G';
    case 8: return 'H';
    case 9: return 'I';
    case 10: return 'J';
    case 11: return 'K';
    case 12: return 'L';
    case 13: return 'M';
    case 14: return 'N';
    case 15: return 'O';
    case 16: return 'P';
    case 17: return 'Q';
    case 18: return 'R';
    case 19: return 'S';
    case 20: return 'T';
    case 21: return 'U';
    case 22: return 'V';
    case 23: return 'W';
    case 24: return 'X';
    case 25: return 'Y';
    case 26: return 'Z';
    case 27: return 'AA';
    default: return '-';
}}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Use an array of characters to return, loop the array, and return the index + 1, since A will = 1 not 0 \$\endgroup\$ Commented Aug 12, 2015 at 13:37
  • \$\begingroup\$ How to fill the array with characters? After 'Z' 'AA', then 'AB' comes. \$\endgroup\$
    – Sarkanyolo
    Commented Aug 12, 2015 at 13:39

1 Answer 1

3
\$\begingroup\$

take variable num and divide it by 26. The int value of that result will give you the number of As you need for your string. Then calculate the first result minus by the int value of it and then multiplied by 26. This will give you the last character for your string. If the given number is smaller than 1 or bigger than 1000000, return just a -.

Example:

num = 1337;
1337 / 26 = 51.42...
int value of that is 51 ---> 51 As
51.42... - 51 = 0.42... * 26 = 11 --> 11. character = K

So the result for num = 1337 would be 51xA and 1xK

Edit: you can also calculate intValue(num / 1000000) for the As and i mod 26 for the last character.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.