ไพๅฆ๏ผ26 ๅช่ฝ็จ Z ่กจ็คบ๏ผไธ่ฝ็จ A0 ่กจ็คบใ
,
/**
* convert column index to column name (A1 Notation).
*
* @param {number} col - column number of cell. (A = 1)
* @returns {string}
*
* @example
*
* columnName(4) // "D"
* columnName(27) // "AA"
* columnName(26*26 + 26) // "ZZ"
*
*/
function columnName(col) {
// integer division
function intDiv(a, b){
return [ Math.floor(a / b), a % b ]; // quotient, remaider
}
// 1 -> A, 2 -> B, ... 26 -> Z
function alphabet(i){
if ( i === 0 ) i = 26; // โญ๏ธ 0 -> Z
return String.fromCharCode(i - 1 + 'A'.charCodeAt())
}
const Z = 26;
let name = ``;
// example 1: n = ABC = A*Zยฒ + B*Z + C
// n % Z = C
// n / Z = A*Z + B = AB
//
// example 2: n = ZZ = Z*Z + Z
// n % Z = 0 (โญ๏ธ which means the last digit is 'Z')
// n / Z = Z + 1 (โญ๏ธ this extra 1 must be removed)
let n = col;
while (n >= 1) {
const [q, r] = intDiv(n, Z);
name = alphabet(r) + name;
n = q - (r === 0 ? 1 : 0); // โญ๏ธ
}
return name;
}