Home > Blockchain >  How to increment a set of 2 letters using GAS?
How to increment a set of 2 letters using GAS?

Time:04-29

How could this one be tweaked so that it could increment a set of two letters, so that it'd look like this:

AA, AB, AC...AZ, BA, BB, BC, etc

This is borrowed from tckmn, but it addresses one letter only.

var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
function incrementChar(c) {
    var index = alphabet.indexOf(c)
    if (index == -1) return -1 // or whatever error value you want
    return alphabet[index   1 % alphabet.length]
}

Appreciate your help!

CodePudding user response:

You just need two loops. One to iterate over the alphabet, and the second to iterate over the alphabet on each iteration of the first loop.

const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

const arr = [];

for (let i = 0; i < alphabet.length; i  ) {
  for (let j = 0; j < alphabet.length; j  ) {
    arr.push(`${alphabet[i]}${alphabet[j]}`);
  }  
}

console.log(arr);

CodePudding user response:

In your situation, how about the following modification? In this modification, I added a wrapper function for using 2 letters.

Modified script:

// This is from your showing script.
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
function incrementChar(c) {
  var index = alphabet.indexOf(c)
  if (index == -1) return -1 // or whatever error value you want
  return alphabet[index   1 % alphabet.length]
}

// I added this function.
function wrapper(str) {
  const [a, b] = [...str];
  const r1 = incrementChar(a);
  const r2 = incrementChar(b);
  return (r2 ? [a, r2] : (r1 ? [r1, "A"] : ["over"])).join("");
}

function main() {
  var samples = ["AA", "AY", "AZ", "ZY", "ZZ"]; // This is a sample value for testing this script.
  const res = samples.map(e => wrapper(e));
  console.log(res); // [ 'AB', 'AZ', 'BA', 'ZZ', 'over' ]
}

main();

  • When this script is run, [ 'AB', 'AZ', 'BA', 'ZZ', 'over' ] is returned. From your showing script, when Z is put, undefined is returned. So, in this sample, over is returned.
  • Related