Recommended practices for JavaScript library formatting prior to publishing

coding-style, javascript

Solution

As your functions don't use classes, don't need a state, and are related to a simple topic, you could simply publish them as

myMath = {
   double: function(a){ return a*2; },
   root: function(a,b,c){ return -b+Math.sqrt(b*b-4*a*c)/(2*a); },
   hypotenuse: function(a,b){ return Math.sqrt(a*a+b*b); }
};

Now suppose you'd want to use a private function or a state, then you could use the module pattern :

myMath = (function(){
   var square = function(x){return x*x}; // private function
   return {
       double: function(a){ return a*2; },
       root: function(a,b,c){ return -b+Math.sqrt(square(b)-4*a*c)/(2*a); },
       hypotenuse: function(a,b){ return Math.sqrt(square(a)+square(b)); }
   }
})();

But there really is no reason here to use this construct.

Now note that publishing on github is much more than that (documentation, test units, readme.md, etc.) but that hardly can be discussed constructively on SO.

Problem

Say you have just implemented a JavaScript library that contains a few functions, ex: ``` double = function(a){ return a*2; }; root = function(a,b,c){ return -b+Math.sqrt(b*b-4*a*c)/(2*a); }; hypotenuse = function(a,b){ return Math.sqrt(a*a+b*b); }; ``` It's not a good idea to distribute it like that because that code pollutes the global namespace. What's a proper way to format a JavaScript library prior to publishing?

Original source

Related problems