Dimitris Vardoulakis has created a Doctor. A Doctor for JavaScript that does static analysis on your code to tease out the type information and more.
This is fantastic work, and is something that we were dreaming of when we first planned Bespin. What if the cloud was constantly analyzing your code and returning type metadata back to the clients that were accessing it? That metadata can be used for tasks such as code completion and documentation.
Give it a try to see what comes out the other end. The samples show you a lot, such as polymorphism:
function id(x) { return x;} id(42); id('hello, doctor!'); // returns id : function(<number | string>) → <number | string>
and prototypes:
function Rectangle(w, h) { this.w = w; this.h = h; } Rectangle.prototype.area = function() { return this.w * this.h; }; var a = (new Rectangle(2, 3)).area(); // returns Rectangle : function(number, number) → any area : function() → number
and exceptions:
function findLargest(a) { if (a.length === 0) throw new Error('empty array'); var max = a[0]; for (var i = 1, l = a.length; i < l; i++) if (a[i] > max) max = a[i]; return max; } function foo() { var a = [1,2,3]; try { return findLargest(a); } catch (e) { return e.message; } } foo(); // returns findLargest : function(Array[number]) → number foo : function() → <number | string>
and callbacks:
function call(f, x) { return f(x); } function add1(n) { return n + 1; } function truncate(s) { return s.substring(0, s.length - 1); } var n = call(add1, 41); var s = call(truncate, 'abcd'); // returns call : function(<function(number) → number | function(string) → string>, <number | string>) → <number | string> add1 : function(number) → number truncate : function(string) → string
Mike Shaver talked about the great work that is coming in JS land right now for Moz…. and it is showing. Can’t wait to see both Firefox and Bespin gain from this all!