Need help converting ES6 syntax for Google Apps Script
I’m working on a script for Google Sheets that validates identification numbers, but I’m running into compatibility issues. The original code uses modern JavaScript features that aren’t supported in Google Apps Script environment.
The main problem seems to be with the arrow function syntax in the reduce method. I’m still learning JavaScript and while I can understand what the code does, rewriting it with older syntax is proving difficult for me.
Here’s my current code:
function validateIDNumber(idNum) {
var idNum = String(idNum).trim();
if (idNum.length > 9 || idNum.length < 5 || isNaN(idNum)) return false;
// Add leading zeros to make it 9 digits
idNum = idNum.length < 9 ? ("00000000" + idNum).slice(-9) : idNum;
return Array.from(idNum, Number)
.reduce(function(sum, num, index) {
var result = num * ((index % 2) + 1);
return sum + (result > 9 ? result - 9 : result);
}) % 10 === 0;
}
I think the issue is specifically with this part:
.reduce(function(sum, num, index) {
Could someone help me convert this to use regular function syntax instead of arrow functions? Any guidance would be really appreciated!
your code looks fine - ur already using regular function syntax, not arrow funcs. the problem’s probably Array.from() since older GAS versions don’t support it. just use a for loop to convert the string to nums instead.
You’re already using regular function syntax in your reduce call, not arrow functions. Arrow functions would look like (sum, num, index) => { ... }. The real problem is Array.from() - it’s not supported in the older V8 runtime that GAS uses. I hit this same issue last year when migrating validation code. Just work directly with the string using charAt() instead of converting to an array first. Saves you the compatibility headache. Your reduce logic is solid though - that alternating multiplier pattern shows up in tons of checksum algorithms.
Your function syntax is fine for Google Apps Script. The problem is Array.from() - it’s not available in older GAS environments. Replace that whole reduce chain with a simple for loop:
function validateIDNumber(idNum) {
var idNum = String(idNum).trim();
if (idNum.length > 9 || idNum.length < 5 || isNaN(idNum)) return false;
idNum = idNum.length < 9 ? ("00000000" + idNum).slice(-9) : idNum;
var sum = 0;
for (var i = 0; i < idNum.length; i++) {
var num = parseInt(idNum.charAt(i));
var result = num * ((i % 2) + 1);
sum += (result > 9 ? result - 9 : result);
}
return sum % 10 === 0;
}
This drops the problematic Array.from() call but keeps the same logic. I’ve hit similar issues porting modern JS to GAS.