1.應用場景
- 字母和數字組合累加1
1. 常規累加
'123' => '124' 129 => '130'
2. 字母累加
aaa => 'aab'
AAA => 'AAB'
3. 字母加數字
'123a' => '123b' '12a9' => '12b0' '19z9' => '20a0'
4. 極限數字 (根據需求可自行更改)
'999' => '000' 'zz' => 'aa'
/*
* 處理編碼
*@ params 編碼字符串
*/
function dealCode(params) {
let str
if (typeof params === 'string' || typeof params === 'number') {
str = String(params)
} else {
console.error('請傳入字符串或者數值')
return
}
// 截取最後一位
return cumulative(str, 1)
}
function cumulative(str, n) {
const strLeng = str.length
let lastStr = str.substr(strLeng - n, 1)
const numStr = '0123456789'
const letterStr = 'abcdefghijklmnopqrstuvwxyz'
const upLetterStr = 'ABCDEFGHIJKMLNOPQRSTUVWXYZ'
if (numStr.includes(lastStr)) {
// 數字
const length = numStr.indexOf(lastStr)
if (length === 9) {
// 需要進位的情況
lastStr = '0'
str = str.substr(0, strLeng - n) + lastStr + str.substr(strLeng - n + 1)
// 遞歸
if (n < strLeng) {
n = n + 1
return cumulative(str, n)
} else {
// 最大的時候
return '1'+str
}
} else {
// 不需要進位的情況,截取後面一位賦值
lastStr = numStr.substr(length + 1, 1)
str = str.substr(0, strLeng - n) + lastStr + str.substr(strLeng - n + 1)
}
return str
} else {
// 字母
if (letterStr.includes(lastStr)) {
const length = letterStr.indexOf(lastStr)
if (length === 25) {
// 需要進位的情況
lastStr = 'a'
str = str.substr(0, strLeng - n) + lastStr + str.substr(strLeng - n + 1)
// 遞歸
if (n < strLeng) {
n = n + 1
return cumulative(str, n)
} else {
// 最大的時候
return 'a'+str
}
} else {
// 不需要進位的情況,截取後面一位賦值
lastStr = letterStr.substr(length + 1, 1)
str = str.substr(0, strLeng - n) + lastStr + str.substr(strLeng - n + 1)
}
return str
} else {
// 大寫字符
const length = upLetterStr.indexOf(lastStr)
if (length === 25) {
// 需要進位的情況
lastStr = 'A'
str = str.substr(0, strLeng - n) + lastStr + str.substr(strLeng - n + 1)
// 遞歸
if (n < strLeng) {
n = n + 1
return cumulative(str, n)
} else {
// 最大的時候
return 'A'+str
}
} else {
// 不需要進位的情況,截取後面一位賦值
lastStr = upLetterStr.substr(length + 1, 1)
str = str.substr(0, strLeng - n) + lastStr + str.substr(strLeng - n + 1)
}
return str
}
}
}