Structure and Simplify Your Google Apps Script With V8

Photo by Karsten Würth on Unsplash

Apps Script now supports the V8 runtime. Time for an update to the story “Structure and simplify your Google Apps Script Apps script”. The V8 runtime brings modern ECMAScript syntax to Apps Script. So we can now use arrow functions and destructuring assignments. No more hoisting with let and const and my personal favorite, template literals.

In this story I will show the added value of the changes I made in the constructor pattern using the factory functions. I will also show how to implement chaining and a builder pattern in Apps Script.

The function now uses arrow functions for all functions and variables. All variables are now const unless they actually change. This solves one issue that I ran into several times. A function executes and the result is unexpected. This will happen in the code below.

This code can be saved and will execute in Apps Script V8. However, the following code won’t save

So what if we put the code in multiple files:

The code will save, but won’t execute. So just changing the way we write the functions will protect us from naming conflicts. There is a an issue when using this method for the main function in libraries, so please star issue and so Google will make it an priority.

The other item I would like to highlight is the logManager. The assignment to the variable now uses the standard console logger, or if specified a manager. In my case this is an object build by a factory function that also writes some log information to a Google sheet.

And, the usage of template literals logManager.log(Created ${objectName}); literal just makes the code a lot nicer.

The factory pattern also makes it easy to implement two other interesting concepts, method chaining and the builder pattern. These concepts are not new to V8, they were already possible in earlier versions. With V8 there are more options, still the factory functions eleminate the need for this or classes altogether.

Consider this example:

By simple assigning the current object to me and return me with the fucntion run, we can chain the function run as: appObjectV8({}).run().run();

Or implent the builder pattern to use the following construction appObjectV8({}).prepare().run();

In this story I have shown what is now possible in V8. Using const to declare your functions will make your code more resilient. Method chaining and builder patterns are easy to implement in factory functions.

A full working example of the old implementation can be found in my article Record time and activities with Google Sheets, Calendar and Apps Script. This solution is also available in the G Suite Solutions Gallery. The code for this solution will be updated soon.