Assuming that you will never need more than 9999 IDs, then you could modify your code with the following steps to accomplish this. Note that this solution will allow you to create a (nearly) unlimited number of ID numbers, but after 9999, the length of the id numbers will vary.
- Use the PropertiesService to initialize a counter for creating IDs
function createIdProperty() {
PropertiesService.getScriptProperties().setProperty('idCounter', '0');
}
// run this once to create the idCounter property
createIdProperty();
// To test that your property was created you can run this
Logger.log(PropertiesService.getScriptProperties().getProperty('idCounter')); // logs '0'
- Create a function to get the next counterId number from Script Properties as a string with 0s replacing empty digits ( 1 => '0001', 2 => '0002', 3 => '0003')
function getUniqueIdNumber() {
var currentIdNum = +PropertiesService.getScriptProperties().getProperty('idCounter'); //get counter as a number
currentIdNum++; // increment counter by 1
currentIdNum+=''; // convert counter back to a string
PropertiesService.getScriptProperties().setProperty('idCounter', currentIdNum); // store the new counter in properies
while (currentIdNum.length < 4) {
currentIdNum = '0'+currentIdNum;
}
return currentIdNum;
}
- modify your original code to use
getUniqueIdNumber
instead of date
for creating your id
Change
var newID = frontStr+date+backStr;
To
var idNumber = getUniqueIdNumber();
var newID = frontStr+idNumber;
Note that you can replace frontStr
and backStr
with any variables you want.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…