0

This seems like a very basic question. But how do I create a class structure within Google Apps Script?

Lets say I want to call: myLibrary.Statistics.StandardDeviation(). I have to instead call: myLibrary.StandardDeviation().

I cannot seem to break it down any further, or organize it into classes.

How can I do this?

Douglas Gaskell
  • 9,017
  • 9
  • 71
  • 128
  • You can't really do that. But you could do `myLibrary.Statistics().StandardDeviation()` or you make several libraries and give them names like `myLibraryStatistics`, `myLibraryOtherStuff`, etc. – Tesseract Jan 04 '16 at 00:33
  • Thats too bad. If I try and put a function in a function it looks like I need an object instance to be able to do that. But as far as I know, I cannot create an instance of a function? When I try I get an error that StandardDeviation could not be found. – Douglas Gaskell Jan 04 '16 at 02:48

1 Answers1

0

I suspect there's something more that you're not telling us about your situation. It is possible to set up a function as a property of an object that is itself a property of an object, and thus support the calling structure you've described.

function test() {
  Logger.log( myLibrary.Statistics.StandardDeviation([5.3,5.2,5,2.0,3.4,6,8.0]) ); // 1.76021798279042
};

myLibrary.gs

var myLibrary = {};
myLibrary.Statistics = {}
myLibrary.Statistics.StandardDeviation = function( array ) {
  // adapted from http://stackoverflow.com/a/32201390/1677912
  var i,j,total = 0, mean = 0, diffSqredArr = [];
  for(i=0;i<array.length;i+=1){
     total+=array[i];
  }
  mean = total/array.length;
  for(j=0;j<array.length;j+=1){
     diffSqredArr.push(Math.pow((array[j]-mean),2));
  }
  return (Math.sqrt(diffSqredArr.reduce(function(firstEl, nextEl){
            return firstEl + nextEl;
          })/array.length));
}
Mogsdad
  • 44,709
  • 21
  • 151
  • 275