累加(递归)封装

 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
    }
  }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章