JavaScript polymorphism in Google Apps Script
Bruce Axtens
Posted on June 3, 2020
(Updated 2020-06-04 to include Boolean)
Here I am betraying my lack of understanding of polymorphism and thus feeding my imposter syndrome experience.
String.prototype.quoted = function () {
return "'" + this.replace(/'/g,"\\'") + "'";
}
Number.prototype.quoted = function () {
return String(this);
}
Boolean.prototype.quoted = function () {
return this ? "true" : "false";
}
There you have the same method name on three different data types. That's probably a boot-camp fail straight up, especially extending core objects like String, Number and Boolean.
With those in mind, I have this Google Apps Script function that I use to log the attributes of a subset of DocumentApp
elements.
function LogChildren(body) {
function getInnerText(child) {
switch (child.getType().toString()) {
case "PARAGRAPH":
return child.asParagraph().getText();
break;
case "TABLE":
return child.asTable().getText();
break;
default:
return child.asText().getText();
break;
}
}
function getStyles(child) {
const attribs = child.getAttributes();
const attribList = [];
for (let att in attribs) {
try {
if (null !== attribs[att])
attribList.push(att.quoted() + " : " + attribs[att].quoted());
}
catch (E) {
}
}
return "{" + attribList.join(", ") + "}";
}
const childCount = body.getNumChildren();
for (let c = 0; c < childCount; c++) {
const child = body.getChild(c);
Logger.log("[%s] %s = %s %s", c, child.getType().toString(), getInnerText(child), getStyles(child));
}
}
The use of the three versions of .quoted()
is in the getStyles
function above, namely
if (null !== attribs[att])
attribList.push(att.quoted() + " : " + attribs[att].quoted());
So sometimes attribs[att]
is a String or a Number or a Boolean. One way of handling whether to put quotes around attribs[att]
or not would be to write a function which uses typeof
to decide what the data type is and then handle it appropriately. Instead of doing it that way I'm banking on the interpreter already knowing the data type and then running the appropriate .quoted
.
This works now, but sure as anything there's going to be a time when there'll be other things to quote that aren't as amenable to having their objects extended. As it stands, however, this is diagnostic code and won't be appearing in production.
Posted on June 3, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.