Skip to content

Instantly share code, notes, and snippets.

@ezcomenezgo
Created June 5, 2021 12:03
Show Gist options
  • Save ezcomenezgo/fbff9e3adfb8037dd49c4beab246647e to your computer and use it in GitHub Desktop.
Save ezcomenezgo/fbff9e3adfb8037dd49c4beab246647e to your computer and use it in GitHub Desktop.
function convToStr (num) {
const chars = [] // 設一個空陣列推入算好轉成 acsii 碼後的值
let _n = num
while(ture) { // Q: 為何要用while? A: 因為要創一個 loop 讓商數可以繼續除下去,不然永遠只能 return 一個值
if( _n < 26) {
chars.push(_n + calcItForIndex) // 小於 26 的值就能直接加 64,再透過 String.fromCharCode() 方法把 ascii 碼轉換成英文字
break // 沒有 break 掉的話,就會一直把 _n 推進去 chars 陣列裡面,形成無窮迴圈
} // 如果值大於 26 就進行下面動作
const p = parseInt(_n / base26, 10) // 取值除以 26 之後在十進位下的商數
const m = n % base26 // 取值除以 26 之後的餘數
if ( m === 0) {
chars.push(m + calcItForIndex + 26)
_n = p - 1
} else {
chars.push(m + calcItForIndex)
_n = p
}
return String.fromCharCode(...chars.reverse())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment