I am trying to work with closures to speed up my script code in Google Scripts. The concept is new to me but I am wondering if the closure is applied correctly in the code below. (the code works)
Background: the code is to calculate how much a month has progressed in percentages.
I don't want the now and month variables to update every time the function is called but only once if the document is opened. What I essentially want is that all variables are set only once and that the function will deliver an answer if it's called multiple times.
Is this a good reason to use a closure and am I using it correctly?
Thanks for your advice and patience.
// calculate progress with second precision
var progressCalc = (function() {
const stMonth = SpreadsheetApp.getActive()
.getRangeByName("pStartdate")
.getValue();
const eoMonth = SpreadsheetApp.getActive()
.getRangeByName("pEndOfMonthDate")
.getValue();
const now = new Date();
var unixProgressEoMonth = unixTime(eoMonth)-unixTime(stMonth)
var unixProgressNow = unixTime(now)-unixTime(stMonth)
return function () { return unixProgressNow/unixProgressEoMonth;};
})();
function progress() {
Logger.log(progressCalc());
return progressCalc();
}