Today’s snippet is going to be shorter than usual, because there’s a really easy solution. Many objects have a default method like toString(). You may want to add one of those to your own functions – provide a default method if no method is specified. In this post I’ll cover one way to do that. In future posts, now that we have v8 in Apps Script, we’ll look at some more exotic alternatives using Proxy and Reflect.
While creating Sheets Workbook functions – converted to Apps Script I noticed that sometimes a function should return an Array version of its result and sometimes not. I wanted to find an easy way of detecting whether the .array() method was present.
A simple example
This example just counts the number of arguments, or stringifies them via 2 specific methods. However, I want the countArgs method to be the default when no method is specified
You can see from the above example that there’s an opportunity to generalize this to create a closure version with a default method.
Using the generalized closure
Here’s the original example, but this time using the generalizer
A separate default function
In the examples so far, the default method has been one that already exists in the object, but you can also make a completely separate default method.