In google app scripts I have a one dimensional data array that I can get values from like this:
data[0]
I'd love to be able to pass in the column name instead like this:
data("A")
That way I don't have to convert letters into their array position. So I'd like to extend the array object (extending isn't really risky since it's running in an isolated script environment).
I know I can add a function to the array prototype using this letter to number function and this object extension question like this:
<!-- begin snippet: js hide: false --> <!-- language: lang-js -->Array.prototype.byCol = function(colName) {
return this[getColumnNumber(colName) - 1];
}
function getColumnNumber(str) {
var out = 0, len = str.length;
for (pos = 0; pos < len; pos++) {
out += (str.charCodeAt(pos) - 64) * Math.pow(26, len - pos - 1);
}
return out;
}
var data = [1,2,3,4];
document.write(data.byCol("B"));
<!-- end snippet -->
But this is a slightly bulkier calling syntax than I wanted.
Based on this question on default functions, it looks like it's possible to assign a default function to an object, but they're doing so by just creating a function object like this:
<!-- language: lang-js -->var test = new func(function() {
// do something
});
Can I get extend the array so that it will execute a default function when called as a method?