dimanche 3 février 2019

Adjusting JS code to Apps Script in Google sheet

I have a working code in JS for my Web Application which generates custom-format report ID number. I was asked to transfer the same functionality to Google sheet, Apps Script (GAS) to enable users to generate same Rerport IDs through the custom function.

Although most of the code works fine, I get issues with "indexOf" methods in GAS.

My initial JS code looks like this:

let d = new Date();
const randomString = (length, chars) => {
  let mask = '';

      if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      if (chars.indexOf('#') > -1) mask += '0123456789';
      let result = '';
      for (let i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
      return result;
    }

    // Inserting report ID into appropriate fields
    const reportNS = () => {

      let reportIDNS = document.getElementById("reportIDNS");
      reportIDNS.value = 'NS' + randomString(2, 'A') + '-' + randomString(4, '#') + '-' + randomString(4, '#') + '-' +
        d.getFullYear();
    }

This function generates Reprot IDs in the format of "NSAA-1234-1234-YYYY".

My first idea was to put it in someting like this:

/**
 */

var d = new Date();
function randomString (length, chars) {
  var mask = '';

      if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      if (chars.indexOf('#') > -1) mask += '0123456789';
      var result = '';

      for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
      return result;
    }


I am not a pro, thus would appreciate a hint on this! Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire