Increment a string with letters?

前端 未结 12 1283
礼貌的吻别
礼貌的吻别 2021-02-08 12:35

I need to increment a string from.. let\'s say aaa to zzz and write every incrementation in the console (is incrementation even a word?). It would go s

12条回答
  •  甜味超标
    2021-02-08 13:10

    Gets A-Z, AA-ZZ, AAA-ZZZ etc. until the number of cycles is up.

    function createList(maxCycles) {
      if (typeof maxCycles != "number") {
        console.log("number expected");
        return;
      }
    
      const alphaLen = 26;
      const alpha = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
    
      let list = [alpha];
    
      // go through all cycles
      for (let cycleNo = 1; cycleNo < maxCycles; cycleNo++) {
        list[cycleNo] = [];
        pastCollection = list[cycleNo - 1];
        pastLen = pastCollection.length;
    
        for (let i = 0; i < pastLen; i++) {
          for (let j = 0; j < alphaLen; j++) {
            // use past item then add a letter of the alphabet at the end
            list[cycleNo].push(pastCollection[i] + alpha[j]);
          }
        }
      }
    
      return list;
    }
    
    (function(maxCycles) {
      console.log(createList(maxCycles));
    })(3);

提交回复
热议问题