Skip to content

Instantly share code, notes, and snippets.

@brainysmurf
Last active January 4, 2019 17:47
Show Gist options
  • Save brainysmurf/8e453bb6b39de3c78320c46fe3d495fe to your computer and use it in GitHub Desktop.
Save brainysmurf/8e453bb6b39de3c78320c46fe3d495fe to your computer and use it in GitHub Desktop.
Descriptors for Google Apps Scripts

Descriptors for Google Apps Scripts

Get Started

Scroll down to the bottom and copy and paste into your project.

More info about the underlying technology

Explanation and usage

Been playing around with some design patterns, and wanted to see if getters and setters would prove useful.

These getters and setters are just a more manual way of defining namespaces, i.e. object.doSomething(). Using them is a bit of a pain to type, but yes very useful. I like them for being able to have a property of an object that is defined as a function, but does not need to be invoked with parentheses.

i.e. in your code "spreadsheet.currentSheet" would actually run a function and would resolve to whatever is returned in that function. That could make for some interesting design patterns.

Sharing with you now, though, is a mini library that makes it easier to do the above. All you need is this:

var spreadsheet = {};
spreadsheet.__descriptor = {
  property: 'currentSheet',
  getter: function () {
    return SpreadsheetApp.getActiveSheet();
  }
}

Use it:

var sheet = spreadsheet.currentSheet

The bit of code that enables this particular thing actually uses getters and setters. Quite neat!

Object.defineProperty(Object.prototype, '__descriptor', {
set: function (options) {
if (options.getter) {
Object.defineProperty(this, options.property, {
get: options.getter,
configurable: true,
enumerable: true
});
}
if (options.set) {
Object.defineProperty(this, options.property, {
set: options.setter,
configurable: true,
enumerable: true
});
}
},
configurable: true,
enumerable: false
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment