<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>Irakli Gozalishvili</title>
    <subtitle>?.</subtitle>
    <link href="http://www.jeditoolkit.com/atom.xml" rel="self" type="application/atom+xml" />
    <link href="http://www.jeditoolkit.com" rel="alternate" type="text/html" />
    <id>http://www.jeditoolkit.com</id>
    <updated>2013-01-29T16:34:38-08:00</updated>
    <author>
        <name>Irakli Gozalishvili</name>
    </author>
    
        <entry>
            <title>isolate.js via AST analysis</title>
            <link href="http://www.jeditoolkit.com/2013/01/23/isolate.js-via-AST-analysis.html" rel="alternate" type="text/html" />
            <updated>2013-01-23T00:00:00-08:00</updated>
            <id>http://www.jeditoolkit.com/2013/01/23/isolate.js-via-AST-analysis</id>
            <content type="html">&lt;p&gt;In the Add-on SDK we have a problem that is both annoying and confusing for a lot of our users. The problem is not SDK-specific though and maybe interesting for anyone dealing with JS in concurrent execution contexts.&lt;/p&gt;

&lt;h2 id='problem_overview'&gt;Problem overview&lt;/h2&gt;

&lt;p&gt;The Add-on SDK was designed to be compatible with browser architecture where chrome and content may be in a separate isolated processes. This imposes a lot of limitations on how add-on code can interact with a page / tab content, and the lack of concurrency constructs in Javascript make this problem a lot more irritating. In the SDK we ended up implementing an API that closely resembles &lt;a href='https://developer.mozilla.org/en-US/docs/DOM/Using_web_workers'&gt;web workers&lt;/a&gt;. The main add-on code can execute content scripts in a page context that acts like a worker and interaction between add-on and content scripts happen through a message passing &lt;em&gt;(for more details please take a look at &lt;a href='https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/guides/content-scripts/index.html'&gt;content script&lt;/a&gt; documention)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;We quickly discovered that not a lot of people are comfortable with message passing APIs, but even putting that aside it&amp;#8217;s really annoying to be creating separate content script files for a few lines of code (most of the add-ons have content scripts that consist of few lines of code, unless accompanied with external js libraries like jQuery):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!env/javascript
var pageMod = require(&amp;quot;sdk/page-mod&amp;quot;)

var mod = new pageMod.PageMod({
  include: [&amp;quot;*.co.uk&amp;quot;],
  contentScriptFile: require(&amp;quot;self&amp;quot;).data.url(&amp;quot;./my.js&amp;quot;)
}))&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As an option we also allow passing content scripts in form of JS string, which is far from ideal:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!env/javascript
var pageMod = require(&amp;quot;page-mod&amp;quot;)

pageMod.add(new pageMod.PageMod({
  include: [&amp;quot;*.co.uk&amp;quot;],
  contentScript: &amp;quot;document.body.innerHTML = &amp;quot; +
             	 &amp;quot;&amp;#39;&amp;lt;h1&amp;gt;this page has been eaten&amp;lt;/h1&amp;gt;&amp;#39;&amp;quot;
}))&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;What you would actully want is to just write a function that will be executed in the context of the content. Unfortunately it&amp;#8217;s not just matter of serialising function and then evaluating it in the context, since functions can access bindings from the outer scopes.&lt;/p&gt;

&lt;h2 id='idea'&gt;Idea&lt;/h2&gt;

&lt;p&gt;If we could prove that function does not refers to anything but arguments passed to it or definitions with in it, it would be pretty safe to transplant it into completely different execution context:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!env/javascript
var pageMod = require(&amp;quot;sdk/page-mod&amp;quot;)

var mod = new pageMod.PageMod({
  include: [&amp;quot;*.co.uk&amp;quot;],
  contentScript: isolate(function() {
    document.body.innerHTML = &amp;quot;&amp;lt;h1&amp;gt;this page has been eaten&amp;lt;/h1&amp;gt;&amp;quot;
}))&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As a matter of fact such &lt;code&gt;isolate&lt;/code&gt; function can be implemented relatively easy, all it has to do is serialise given function, parse it, perform static analyzes to verify no outer references are made and return some wrapping of source back. If given function does have prohibited references then throw &lt;code&gt;TypeError&lt;/code&gt; back.&lt;/p&gt;

&lt;h2 id='code'&gt;Code&lt;/h2&gt;

&lt;p&gt;With a great projects like &lt;a href='http://esprima.org/'&gt;Esprima&lt;/a&gt;, &lt;a href='http://marijnhaverbeke.nl/acorn/'&gt;Acorn&lt;/a&gt; parsing JS is no-brainer. Also for SDK we could / should just use &lt;a href='https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API'&gt;Spidermonkey parser API&lt;/a&gt;, but since all of them produce de facto standad &lt;a href='http://esprima.org/doc/index.html#ast'&gt;AST format&lt;/a&gt; we can swap parsers as we pleased. So the only remaining chunk of work was static analysis. I made few micro-libraries solving very specific problems.&lt;/p&gt;

&lt;h3 id='interset'&gt;&lt;a href='https://github.com/Gozala/interset'&gt;interset&lt;/a&gt;&lt;/h3&gt;

&lt;p&gt;While playing with AST I quickly discovered the need for binary operations for logical sets. So I end up writing &lt;a href='https://github.com/Gozala/interset'&gt;interset&lt;/a&gt; small library for doing exactly that:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!env/javascript
var union = require(&amp;quot;interset/union&amp;quot;)

union([1, 2], [2, 3], [3, 4])
// =&amp;gt; [1, 2, 3, 4]

var intersection = require(&amp;quot;interset/intersection&amp;quot;)
intersection([1, 2], [2, 3])
// =&amp;gt; [2]

var difference = require(&amp;quot;interset/difference&amp;quot;)
difference([1, 2, 3], [1], [1, 4], [3])
// =&amp;gt; [2]&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='episcope'&gt;&lt;a href='https://github.com/Gozala/episcope'&gt;episcope&lt;/a&gt;&lt;/h3&gt;

&lt;p&gt;ECMAScript scope analyzer. This Library provides set of functions that perform analyzes on the nodes of the AST in the de facto &lt;a href='http://esprima.org/doc/index.html#ast'&gt;AST format&lt;/a&gt;. All the API function take AST nodes denoting a lexical scope and performed static analyzes at the given scope level (Note: examples use esprima but library does not really cares about it and expects AST format implemented by all popular JS parsers):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!env/javascript
var esprima = require(&amp;quot;esprima&amp;quot;)
var references = require(&amp;quot;episcope/references&amp;quot;)

var ast = esprima.parse(&amp;quot;console.log(&amp;#39;&amp;gt;&amp;gt;&amp;gt;&amp;#39;, error)&amp;quot;)
references(ast)
// =&amp;gt;  [{ type: &amp;quot;Identifier&amp;quot;, name: &amp;quot;console&amp;quot; }, { type: &amp;quot;Identifier&amp;quot;, name: &amp;quot;error&amp;quot; }]

var bindings = require(&amp;quot;episcope/bindings&amp;quot;)
var ast = esprima.parse(&amp;quot;function foo(a, b) { var c = a + b; return c * c }&amp;quot;)
ast.body[0].id
// =&amp;gt; { type: &amp;#39;Identifier&amp;#39;, name: &amp;#39;foo&amp;#39; }
bindings(ast.body[0])
// =&amp;gt;  [ { type: &amp;#39;Identifier&amp;#39;, name: &amp;#39;a&amp;#39; },
//       { type: &amp;#39;Identifier&amp;#39;, name: &amp;#39;b&amp;#39; },
//       { type: &amp;#39;Identifier&amp;#39;, name: &amp;#39;c&amp;#39; } ]

var scopes = require(&amp;quot;episcope/scopes&amp;quot;)
var ast = esprima.parse(String(function root() {
  function nested() { /***/ }
  try { /***/ } catch(error) { /***/ }
}))
scopes(ast.body[0])
// =&amp;gt; [
//  { 
//    type: &amp;#39;FunctionDeclaration&amp;#39;,
//    id: { type: &amp;#39;Identifier&amp;#39;, name: &amp;#39;nested&amp;#39; },
//    // ...
//  },
//  {
//    type: &amp;#39;CatchClause&amp;#39;,
//    param: { type: &amp;#39;Identifier&amp;#39;, name: &amp;#39;error&amp;#39; },
//    body: { type: &amp;#39;BlockStatement&amp;#39;, body: [] }
//  }
//]&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id='isoscope'&gt;&lt;a href='https://github.com/Gozala/episcope'&gt;isoscope&lt;/a&gt;&lt;/h2&gt;

&lt;p&gt;ECMAScript function isolation analyzer. This is very alpha, but intention is to provide API for performing static analyzes on the JS AST nodes denoting a function definition / declaration and perform analyzes to gather info about their isolation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!env/javascript
var esprima = require(&amp;quot;esprima&amp;quot;)
var enclosed = require(&amp;quot;isoscope/enclosed&amp;quot;)

// Parse some code
var form = esprima.parse(String(function fn(a, b) {
  console.log(String(a) + b)
}))

// Get a function form we&amp;#39;ll be analyzing
var fn = form.body[0]
fn.id
// =&amp;gt; { type: &amp;quot;Identifier&amp;quot;, name: &amp;quot;fn&amp;quot; }

// Get names of enclosed references
enclosed(fn)
// =&amp;gt; [ &amp;quot;console&amp;quot;, &amp;quot;String&amp;quot; ]&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now the only thing left for &lt;code&gt;isolate&lt;/code&gt; to do is ensure that enclosed references are legit globals or built-ins and that nasty things like &lt;a href='https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/with'&gt;with&lt;/a&gt; and &lt;a href='https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval'&gt;eval&lt;/a&gt; are not used.&lt;/p&gt;

&lt;p&gt;If this experiment works out in practice that would allow us to &lt;a href='https://github.com/mozilla/addon-sdk/wiki/JEP-Content-scripts'&gt;explore a lot more&lt;/a&gt; to make new and brave concurrent world a lot more accessible and pleasant to use for our users.&lt;/p&gt;

&lt;p&gt;All the libraries mentioned are open source and work both in SDK and &lt;a href='http://nodejs.org/'&gt;Node&lt;/a&gt;, probably in browsers too. So feel free to play with them, break them and maybe even contribute fixes!&lt;/p&gt;</content>
        </entry>
    
        <entry>
            <title>interactivate</title>
            <link href="http://www.jeditoolkit.com/2012/11/12/interactivate.html" rel="alternate" type="text/html" />
            <updated>2012-11-12T00:00:00-08:00</updated>
            <id>http://www.jeditoolkit.com/2012/11/12/interactivate</id>
            <content type="html">&lt;p&gt;I have made a little live-coding experiment that is primarily inspired by &lt;a href='http://www.wolfram.com/mathematica/'&gt;Mathematica&lt;/a&gt; notepad, Bret Victor&amp;#8217;s &lt;a href='https://vimeo.com/36579366'&gt;Inventing on Principle&lt;/a&gt; and has being pioneered by othe cool projects like &lt;a href='http://www.lighttable.com/'&gt;light table&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I do write JS &amp;amp; HTML every single day and I can&amp;#8217;t even imagine doing that without a &lt;a href='http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop' title='Read Eval Print Loop'&gt;REPL&lt;/a&gt;. Although &lt;a href='https://developer.mozilla.org/en-US/docs/Tools/Scratchpad'&gt;scratchpad&lt;/a&gt; made me realized how I hate &lt;strong&gt;loop&lt;/strong&gt; part of &lt;a href='http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop' title='Read Eval Print Loop'&gt;REPL&lt;/a&gt;! Another problem is an amount of time one needs to waste, while being inspired, to get a glimpse of an idea, live on a screen. Creating HTML, JS files wiring them with each other, page refreshes, etc&amp;#8230; I&amp;#8217;m sure we can do better than that, here is a little demo of what I think it should be like:&lt;/p&gt;
&lt;iframe mozallowfullscreen='true' src='http://player.vimeo.com/video/53311490?badge=0' webkitAllowFullScreen='true' allowFullScreen='true' frameborder='0' height='341' width='500'&gt;
&lt;/iframe&gt;
&lt;p&gt;You can &lt;a href='http://jeditoolkit.com/interactivate/'&gt;give it a try&lt;/a&gt; yourself or check out the code &lt;a href='https://github.com/Gozala/interactivate'&gt;on github&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This expreiment was done in a couple of hours, so it&amp;#8217;s far from being stable. It has bunch of known bugs than I need to fix, but I still hope it was worth sharing.&lt;/p&gt;

&lt;p&gt;Making this would have being impossible without awesome open source projects like &lt;a href='http://www.codemirror.net/'&gt;codemirror&lt;/a&gt; &amp;amp; &lt;a href='https://github.com/substack/node-browserify'&gt;browserify&lt;/a&gt; who&amp;#8217;m I wish to give a good credit.&lt;/p&gt;

&lt;p&gt;Finally I really hope to see &lt;a href='https://developer.mozilla.org/en-US/docs/Tools/Scratchpad'&gt;Scratchpad&lt;/a&gt; picking up some of this soon!&lt;/p&gt;</content>
        </entry>
    
        <entry>
            <title>Recent changes in SDK</title>
            <link href="http://www.jeditoolkit.com/2012/10/29/Recent-changes-in-SDK.html" rel="alternate" type="text/html" />
            <updated>2012-10-29T00:00:00-07:00</updated>
            <id>http://www.jeditoolkit.com/2012/10/29/Recent-changes-in-SDK</id>
            <content type="html">&lt;p&gt;There have being some &lt;a href='https://github.com/mozilla/addon-sdk/commit/9f596b54573b10a1cfe3fc8d1eccdd2eb049891c'&gt;significant changes&lt;/a&gt; to the Add-on SDK lately, which is a step forward to landing and &lt;a href='https://github.com/mozilla/addon-sdk/wiki/JEP%20SDK%20in%20Firefox'&gt;shipping SDK in Firefox&lt;/a&gt;. In this post I&amp;#8217;ll try to cover what the changes are.&lt;/p&gt;

&lt;p&gt;Probably the most important detail is that SDK no longer uses packages. This is an improvement for two reasons:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;once SDK is in Firefox we won&amp;#8217;t be able to perform complicated &lt;a href='https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/guides/module-search.html'&gt;module search&lt;/a&gt; at compile time and even more so at runtime.&lt;/li&gt;

&lt;li&gt;We also see it as great improvement to current ambiguous behavior of &lt;code&gt;require&lt;/code&gt;. Now SDK is just a &lt;code&gt;lib&lt;/code&gt;rary of modules. Once it&amp;#8217;s in Firefox, all addons will be able to load any SDK module without needing to convert completely to an SDK-style project.&lt;/li&gt;

&lt;li&gt;We also hope to empower other Mozilla projects with &lt;a href='http://wiki.commonjs.org/wiki/Modules'&gt;CommonJS&lt;/a&gt; so that new APIs &amp;amp; features can be authored in de facto standard &lt;a href='http://wiki.commonjs.org/wiki/Modules'&gt;CommonJS&lt;/a&gt; module format.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Going forward, the idiomatic way to require an SDK modules now is: &lt;code&gt;require(&amp;quot;sdk/panel&amp;quot;)&lt;/code&gt;. Low level and usually less stable APIs will have longer require paths: &lt;code&gt;require(&amp;quot;sdk/window/utils&amp;quot;)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To ensure that addons built using the old layout are not affected by this change we have analyzed &lt;a href='https://docs.google.com/spreadsheet/ccc?key=0ApEBy-GRnGxzdHlRMHJ5RXN1aWJ4RGhINkxSd0FCQXc#gid=0'&gt;all the module requirements&lt;/a&gt; of all &lt;a href='https://addons.mozilla.org/en-US/firefox/'&gt;AMO&lt;/a&gt; hosted addons and created a &lt;a href='https://github.com/mozilla/addon-sdk/blob/master/mapping.json'&gt;mapping&lt;/a&gt; that maps module requirements used to a new style. &lt;strong&gt;CFX&lt;/strong&gt; - SDK&amp;#8217;s CLI tool uses this mapping to allow backwards compatible behavior, while we have no plans on breaking backwards compatibility in a visible future, we still would like to encourage authoring new add-ons in idiamatic style this will make your code a lot more portable!&lt;/p&gt;

&lt;p&gt;This new layout is currently on the Master branch and is scheduled to be released on December 11 as version 1.12.&lt;/p&gt;</content>
        </entry>
    
        <entry>
            <title>(feedback :clojurescript)</title>
            <link href="http://www.jeditoolkit.com/2012/09/16/coljurescript-feedback.html" rel="alternate" type="text/html" />
            <updated>2012-09-16T00:00:00-07:00</updated>
            <id>http://www.jeditoolkit.com/2012/09/16/coljurescript-feedback</id>
            <content type="html">&lt;p&gt;Lately I have being very entusiastic about &lt;a href='https://github.com/clojure/clojurescript/' title='Clojure for JS'&gt;clojurescript&lt;/a&gt;, but I keep running into small annoyances that I just can not get over with. I think it may be useful to provide a feedback form a user who&amp;#8217;s primary language for the past decade was JS, which brings me to a folloing point:&lt;/p&gt;

&lt;h2 id='1_enable_github_issues'&gt;1. Enable github issues&lt;/h2&gt;

&lt;p&gt;At the moment &lt;a href='https://groups.google.com/forum/?fromgroups#!forum/clojure'&gt;clojure discussion group&lt;/a&gt; is the only place for providing feedback. Group is very active and it&amp;#8217;s &lt;strong&gt;clojure&lt;/strong&gt; (not &lt;strong&gt;clojurescript&lt;/strong&gt;) discussion group so most of the discussions are not really relevant to me. I find keeping up with all the noise there hard, and would personally have created bunch of issues reports already if I could have submitted them on github.&lt;/p&gt;

&lt;h2 id='2_accessing_properties_with_computed_names'&gt;2. Accessing properties with computed names&lt;/h2&gt;

&lt;p&gt;I find API for accessing properties with computed names awkward:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!env/scheme
(aget js/require.extensions &amp;quot;.cljs&amp;quot;)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;At least because documentation of &lt;a href='http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/get' title='Returns the value mapped to key, not-found or nil if key not present.'&gt;get&lt;/a&gt; function, matches better my intent then &lt;a href='http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/aget' title='Returns the value at the index/indices.'&gt;aget&lt;/a&gt;&amp;#8217;s. Also I find use case common enough, that I think a syntax sugar would be more appropriate.&lt;/p&gt;

&lt;h2 id='3_setting_properties_with_computed_names'&gt;3. Setting properties with computed names&lt;/h2&gt;

&lt;p&gt;API for setting properties with computed names is even clunkier:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!env/scheme
(set! (aget js/require.extensions &amp;quot;.cljs&amp;quot;) compile)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I think extending &lt;a href='http://clojure.org/special_forms#set' title='set! special form'&gt;set!&lt;/a&gt; special form would make a lot more sense:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!env/scheme
(set! js/require.extensions &amp;quot;.cljs&amp;quot; compile)&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id='4_regural_expressions'&gt;4. Regural expressions&lt;/h2&gt;

&lt;p&gt;I really enjoy how simple regular expressions translate to JS:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!env/scheme
#&amp;quot;[^a-z\s]&amp;quot; ;; =&amp;gt; /[^a-z\s]/&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Although I could not find any way to create regular expressions with &lt;a href='https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions?redirectlocale=en-US&amp;amp;redirectslug=Core_JavaScript_1.5_Guide%2FRegular_Expressions#Advanced_Searching_With_Flags'&gt;advance search flags&lt;/a&gt;, other then by using &lt;code&gt;RegExp&lt;/code&gt; constructor:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!env/scheme
(js/RegExp. &amp;quot;\\w+\\s&amp;quot; &amp;quot;g&amp;quot;)        ;; =&amp;gt; /\w+\s/g
(js/RegExp. &amp;quot;^\\-\\-\\w*$&amp;quot; &amp;quot;m&amp;quot;)   ;; =&amp;gt; /^\-\-\w*$/m
(js/RegExp. &amp;quot;foo&amp;quot; &amp;quot;i&amp;quot;)            ;; =&amp;gt; /foo/i&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I wish literal syntax had support for search flags, maybe even via &lt;a href='https://github.com/edn-format/edn#tagged-elements'&gt;clojure tags&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id='5_try__catch'&gt;5. Try / catch&lt;/h2&gt;

&lt;p&gt;In clojure and inherently clojurscript &lt;code&gt;catch&lt;/code&gt; clause of the &lt;code&gt;try&lt;/code&gt; special form takes error type, error name and expressions:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!env/scheme
;; for Clojurescript use js/Object as type
(try
   (/ 1 0)
   (catch js/Object e
       (.log js/console e)))&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I do understad that it makes sence on JVM, but it definitely does not on JS. I really wish that error type was either optional or was removed entirely in clojurescript.&lt;/p&gt;

&lt;h2 id='7_less_dependency_on_jvm'&gt;7. Less dependency on JVM&lt;/h2&gt;

&lt;p&gt;While I fully understand rational behind dependency on &lt;a href='http://en.wikipedia.org/wiki/Java_virtual_machine' title='Java virtual machine'&gt;JVM&lt;/a&gt;, it&amp;#8217;s still painful for someone coming from JS who&amp;#8217;s not comfortable with configuring class paths. Tools like &lt;a href='https://github.com/technomancy/leiningen' title='Clojure package manager'&gt;leiningen&lt;/a&gt; also spend more time on booting JVM then on performing actual tasks. I think clojurscript could be significally more successful among JS developers if they could strat witout any dependencies (even if they will have to deal with them later once they&amp;#8217;re more comfortable).&lt;/p&gt;

&lt;p&gt;Overall I&amp;#8217;m pretty happy with clojurscript, it&amp;#8217;s pretty young project and I hope it will only get better and more accessible over time!&lt;/p&gt;</content>
        </entry>
    
        <entry>
            <title>nodeconf 2012</title>
            <link href="http://www.jeditoolkit.com/2012/07/05/nodeconf-2012.html" rel="alternate" type="text/html" />
            <updated>2012-07-05T00:00:00-07:00</updated>
            <id>http://www.jeditoolkit.com/2012/07/05/nodeconf-2012</id>
            <content type="html">&lt;p&gt;I had a great pleasure of attending &lt;a href='http://www.nodeconf.com/'&gt;nodeconf&lt;/a&gt; that took place in &lt;a href='https://maps.google.com/maps?q=portland&amp;amp;hl=en&amp;amp;sll=37.0625,-95.677068&amp;amp;sspn=37.273371,65.302734&amp;amp;t=v&amp;amp;hnear=Portland,+Multnomah,+Oregon&amp;amp;z=10'&gt;Portland&lt;/a&gt;. Conference far exceeded all my expectations. This post has no chance to capture all of the interesting things that happened there, but I still would like to make an effort and share some of the highlights.&lt;/p&gt;

&lt;p&gt;First off I would love to thank &lt;a href='http://www.mikealrogers.com/'&gt;Mikael Rogers&lt;/a&gt; and everyone who helped him to set a whole new standard of how conferences should be held! Theatrical feel was through the whole conference: venue at &lt;a href='http://www.imagotheatre.com/theatre.html'&gt;Imago theatre&lt;/a&gt;, talks that flowed into each other according to well crafted scenario. Remarkably single track (or single thread if you will :) model was used, which once again proved to be a perfect fit for event(ed) JS. Another novelty was in a &amp;#8220;save questions for the bar&amp;#8221; rule that worked out amazingly well.&lt;/p&gt;

&lt;h2 id='day_i'&gt;Day I&lt;/h2&gt;

&lt;p&gt;Both nodejs and conference was started by a &lt;a href='http://tinyclouds.org/'&gt;Ryah Dahl&lt;/a&gt;, who shared with us a little bit of a background story on how &amp;amp; why node was started. Then very first contributors took a scene to talk about very early days of project, when it was very unstable, but still very fun to hack on. That flowed into talks about how node was maturing and making it&amp;#8217;s way into production at &lt;a href='https://www.yammer.com/'&gt;Yammer&lt;/a&gt; and elsewhere. Was interesting to learn why companies like Microsoft invest into nodejs and how it became first class citizen on windows. That required core changes to an underline platform layer resulting into &lt;a href='https://github.com/joyent/libuv/' title='platform layer for node.js'&gt;libuv&lt;/a&gt;. There were several interesting talks about &lt;a href='https://github.com/joyent/libuv/' title='platform layer for node.js'&gt;libuv&lt;/a&gt;, specifically showing how node like servers can be written in &lt;strong&gt;C&lt;/strong&gt;, how much work is still ahead to be done, and how &lt;a href='https://github.com/joyent/libuv/' title='platform layer for node.js'&gt;libuv&lt;/a&gt; go life of it&amp;#8217;s own. Today it is used by other new projects, including Mozilla&amp;#8217;s own &lt;a href='http://www.rust-lang.org/' title='A safe, concurrent, practical language'&gt;rust&lt;/a&gt; language, by &lt;a href='http://luvit.io/' title='Lua + libUV + jIT = pure awesomesauce'&gt;Luvit&lt;/a&gt; - node for a Lua language. I was completely blown away by &lt;a href='https://github.com/indutny'&gt;Fedor Indutny&lt;/a&gt;&amp;#8217;s crazy simple language &lt;a href='https://github.com/indutny/candor' title='Experimental VM for a Candor language'&gt;candor&lt;/a&gt; with dedicated VM and JIT compiler he wrote. Unfortunately I did not get a chance to chat with him as he disappeared immediately after his talk.&lt;/p&gt;

&lt;p&gt;At the end of the day we all headed to a bar. It turned out there is a nodejs powered &lt;a href='http://voiceboxpdx.com'&gt;karaoke bar&lt;/a&gt; in portland, that even has a &lt;a href='http://voiceboxpdx.com/api/v1/documentation'&gt;public REST API&lt;/a&gt;. That is also where I was &lt;a href='http://voiceboxpdx.com/nodeconf-2012-aftermath/'&gt;rocking out&lt;/a&gt; with others until almost loosing a voice (My apologies to everyone who had to bare with that).&lt;/p&gt;

&lt;h2 id='day_ii'&gt;Day II&lt;/h2&gt;

&lt;p&gt;Node is all about &lt;a href='https://github.com/polotek/nodeconf-2012-streams-talk'&gt;streaming and piping&lt;/a&gt; data from one stream to another. That&amp;#8217;s what it&amp;#8217;s good at and that&amp;#8217;s what everyone writing node programs should embrace! We got some interesting talks on that topic. Although there was a talk that demoed that streams are not a magic dust that makes things fast, sometimes buffering is a better approach. Most important take away was that everyone should benchmark to make reasonable decisions based on numbers, not instincts (I feel people often tend to jump to conclusions without any mesures). It was also interesting to learn how streams and other node concepts had being used to drive innovation into browsers.&lt;/p&gt;

&lt;p&gt;Another section of talks covered scaling node. That involved talks about tools for benchmarking, profiling, memory leak hunting and real life experience from &lt;a href='http://voxer.com/'&gt;Voxer&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Final section of talks was about hardware that completely blew away everybody&amp;#8217;s minds! All kinds of crazy stuff, that I won&amp;#8217;t even attempt to describe, just make sure to watch videos once they&amp;#8217;re realized! Here is small teaser of &lt;a href='https://twitter.com/#!/rwaldron'&gt;Rick Waldron&lt;/a&gt;&amp;#8217;s amazing node powered &lt;a href='http://www.youtube.com/watch?v=GVGMjsKy3WQ&amp;amp;feature=youtu.be'&gt;robot&lt;/a&gt; to give you an idea.&lt;/p&gt;

&lt;p&gt;After party had an epic live performance from the band assembled of a fellow community members! You guys really rocked, I still don&amp;#8217;t understand how did you manage to put this amazing performance without much practice.&lt;/p&gt;

&lt;h2 id='socializing'&gt;Socializing&lt;/h2&gt;

&lt;p&gt;It was pleasure to finally meet friends from internet. I&amp;#8217;m also super happy I got a chance to share some of my ideas how I think node streams can be made &lt;a href='https://gist.github.com/2656978' title='Clojure like reducers in JS'&gt;even better&lt;/a&gt;, I&amp;#8217;m encouraged and plan to put more effort into this. Also, glad I got some folks excited about my recent obsession &lt;a href='http://jeditoolkit.com/lispyscript/' title='A javascript with lisp syntax &amp;amp; macros'&gt;lispyscript&lt;/a&gt;! Finally thanks for encouraging me to submit a talk for upcoming &lt;a href='http://2012.jsconf.eu/'&gt;jsconf.eu&lt;/a&gt;, I&amp;#8217;m motivated and plan on doing it this weekend!&lt;/p&gt;

&lt;p&gt;Speciall thanks to &lt;strong&gt;Mozilla&lt;/strong&gt; for letting me be part of this amazing event!&lt;/p&gt;</content>
        </entry>
    
        <entry>
            <title>Write logic, not mechanics</title>
            <link href="http://www.jeditoolkit.com/2012/04/26/code-logic-not-mechanics.html" rel="alternate" type="text/html" />
            <updated>2012-04-26T00:00:00-07:00</updated>
            <id>http://www.jeditoolkit.com/2012/04/26/code-logic-not-mechanics</id>
            <content type="html">&lt;p&gt;It strikes me that developers in JS community tend to choose patterns for solving recurring problems over abstractions.&lt;/p&gt;

&lt;p&gt;If we are not busy with &lt;a href='https://github.com/twitter/bootstrap/issues/3057'&gt;semicolon debates&lt;/a&gt;, we argue about widely used &amp;#8220;callback pattern&amp;#8221; for dealing with asynchronous API. Many have learned / invented ways to avoid &amp;#8220;pyramids of doom&amp;#8221;, but I believe they miss the point: pyramids are not the issue, it&amp;#8217;s an indication that we have one.&lt;/p&gt;

&lt;p&gt;In order to describe what I consider to be a real issues, I have to move back a little first:&lt;/p&gt;

&lt;h2 id='function'&gt;Function&lt;/h2&gt;

&lt;p&gt;In mathematics, a &lt;a href='http://en.wikipedia.org/wiki/Function_%28mathematics%29' title='Function in Mathematics'&gt;function&lt;/a&gt; is a relation between a set of &lt;strong&gt;inputs&lt;/strong&gt; and a set of potential &lt;strong&gt;outputs&lt;/strong&gt; with the property that each input is related to exactly one output.&lt;/p&gt;

&lt;h2 id='black_box'&gt;Black box&lt;/h2&gt;

&lt;p&gt;In science and engineering, a &lt;a href='http://en.wikipedia.org/wiki/Black_box' title='Black box abstraction'&gt;&amp;#8220;black box&amp;#8221;&lt;/a&gt; abstraction is used to model systems as set of components which can be viewed solely in terms of its &lt;strong&gt;input&lt;/strong&gt;, &lt;strong&gt;output&lt;/strong&gt; and &lt;a href='http://en.wikipedia.org/wiki/Transfer_function'&gt;transfer characteristics&lt;/a&gt;, without any knowledge of its internal workings. This components are opaque (black) boxes.&lt;/p&gt;

&lt;p&gt;&lt;img src='/resources/images/black-box.png' alt='black box' /&gt;&lt;/p&gt;

&lt;p&gt;Bigger boxes can be created out of smaller ones just by describing a data flow with in them (connecting inputs and outputs):&lt;/p&gt;

&lt;p&gt;&lt;img src='/resources/images/composite-black-box.png' alt='composite black box' /&gt;&lt;/p&gt;

&lt;p&gt;This allows one to reduce details as necessary and change internal implementation of any box without affecting other parts of the system as long as transfer characteristics remain same.&lt;/p&gt;

&lt;h2 id='functions_in_js'&gt;Functions in JS&lt;/h2&gt;

&lt;p&gt;In programing functions are modeled around the same concepts, even though we messed up an &lt;strong&gt;input&lt;/strong&gt; sets by adding implicit parts that may change over time. In JS function &lt;code&gt;input&lt;/code&gt; set consists of:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Given arguments.&lt;/li&gt;

&lt;li&gt;Pseudo-variable &lt;code&gt;this&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;Scope bindings.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id='problems'&gt;Problems&lt;/h2&gt;

&lt;h3 id='1_no_output'&gt;1. No output&lt;/h3&gt;

&lt;p&gt;Since functions in JS are first class, they can be part of both &lt;strong&gt;input&lt;/strong&gt; and &lt;strong&gt;output&lt;/strong&gt; sets. Most of the asynchronous APIs take advantage of this fact and require special &lt;code&gt;callback&lt;/code&gt; function argument for continuation passing:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/javascript
require(&amp;#39;fs&amp;#39;).open(path, &amp;#39;r+&amp;#39;, function(error, fd) {
  // ...
})&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see such functions no longer have have any useful output, which means that they can&amp;#8217;t be used for building systems as black boxes. Such functions don&amp;#8217;t return values that can be passed over to other boxes.&lt;/p&gt;

&lt;h3 id='2_error_handling_on_each_step'&gt;2. Error handling on each step&lt;/h3&gt;

&lt;p&gt;I have heard many times people criticizing how in Java exceptions are caught, wrapped and re-thrown again. This reminds me of following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/javascript
function readJSON(path, callback) {
  fs.readFile(path, function(error, content) {
    if (error) callback(error);
    else callback(null, JSON.parse(content));
  })
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Basically error propagation in &amp;#8220;callback&amp;#8221; style APIs is done manually. Note, that in some cases you may want to &lt;code&gt;try catch&lt;/code&gt; actual function body as well.&lt;/p&gt;

&lt;h3 id='3_polygamy'&gt;3. Polygamy&lt;/h3&gt;

&lt;p&gt;It easy to end up with two types of functions: synchronous and asynchronous. While it&amp;#8217;s possible to make sync function async it&amp;#8217;s not the case other way round. This usually means that if one the functions had being converted to be asynchronous all of it&amp;#8217;s users will have to be converted as well:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/javascript
function readJSON(path) {
  var data = fs.readFileSync(path)
  return JSON.parse(String(data))
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;You can&amp;#8217;t simply switch to &lt;code&gt;readFile&lt;/code&gt; if becomes necessary.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id='4_progress_tracking'&gt;4. Progress tracking&lt;/h3&gt;

&lt;p&gt;Finally if your function depends on multiple asynchronous inputs then you will have to manually track each.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/javascript
function makeView(templateURI, dataURI, callback) {
  var template, data, pending = 2
  readURI(templateURI, function(error, content) {
    if (error) return callback(error)
    template = content
    if (!--pending) Mustache.render(template, data)
  })
  readURI(dataURI, function(error, content) {
    if (error) return callback(error)
    data = content
    if (!--pending) Mustache.render(template, data)
  })
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Also note that this code assumes that &lt;code&gt;readURI&lt;/code&gt; will call a callback only once, which is not guaranteed.&lt;/p&gt;

&lt;h1 id='describe_logic_not_mechanics'&gt;Describe logic not mechanics&lt;/h1&gt;

&lt;p&gt;Now consider our last example. Most of the code there is for handling mechanics rather than describing a logic, which feels absolutely very wrong. As a matter of fact actual logic can be expressed as:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/javascript
function makeView(templateURI, dataURI) {
  var template = readURI(templateURI)
  var data = readURI(dataURI)
  return Mustache.render(template, data)
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So, would not it be better to abstract timing out of logic when it&amp;#8217;s not necessary rather than keep solving all this issues in each and every function ? As a mater of fact solution has being there for ages in a form of &lt;a href='http://wiki.commonjs.org/wiki/Promises/A'&gt;promises&lt;/a&gt;, but for some reason people and web standards tend to use callbacks instead. Maybe because they feel complicated, but that does not necessary has to be the case:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/javascript
// Everyone knows how to write a function:
function sum(a, b) { return a + b }
console.log(sum(1, 2))  // =&amp;gt; 3

// Working with promises should not require nothing more
// than marker telling that function can accept input in
// form of promises
sum = promised(sum)
console.log = promised(console.log)

// Will continue to work with plain old values
console.log(sum(1, 2))  // =&amp;gt; 3

// Will also accept promises as arguments
var deferred = defer()          // make promise
var a = deferred.promise
var b = sum(a, 1)
var c = sum(b, 5)
console.log(c)                  // eventually prints =&amp;gt; 17
deferred.resolve(11)            // fulfill promise&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We should not be handling and propagating exceptions manually in each function, we should only handle them when we plan to recover:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/javascript
// Utility funciton that throws exceptions
var raise = promised(function(_) { throw Error(_) })

var a = raise(&amp;#39;Boom !&amp;#39;)   // Now we got an exception
var b = sum(a, 2)         // Now it has propagated to b
var c = sum(b, 12)        // Now it has propagaed to c

// Finally if when ready we handle exception in computation
c.then(null, console.error) // =&amp;gt; Error: Boom !&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If we just want to group multiple values into one there is an &lt;code&gt;Array&lt;/code&gt; for that no need to track progress of each eventual value if we just care about a group!&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/javascript
Array = promised(Array)
var results = Array(readAsync(a), readAsync(b))
console.log(sum.apply(sum, rusults))&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Noticed a pattern ? We just write a logic, and if it needs to handle asynchronous input we wrap it into &lt;code&gt;promised(logic)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Whats really important here is that such functions can be used to build systems in black boxes, since they do have &lt;strong&gt;input&lt;/strong&gt; and &lt;strong&gt;output&lt;/strong&gt;. Demonstration of that is an example from above (assuming that &lt;code&gt;readURI&lt;/code&gt; returns promise):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/javascript
function makeView(templateURI, dataURI) {
  var template = readURI(templateURI)
  var data = readURI(dataURI)
  // Assuming Mustache.render = promised(Mustache.render)
  return Mustache.render(template, data)
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Implementing such a solution takes about 100 lines of code (ignoring comments), and that&amp;#8217;s more or less what any other control flow library costs anyway. I wish all of you to have more time to concentrate on logic of your program instead of mechanics &amp;amp; small &lt;a href='https://github.com/Gozala/micro-promise' title='Micro promise library'&gt;promise&lt;/a&gt; library may be a good first step!&lt;/p&gt;</content>
        </entry>
    
        <entry>
            <title>protocol based polymorphism</title>
            <link href="http://www.jeditoolkit.com/2012/03/21/protocol-based-polymorphism.html" rel="alternate" type="text/html" />
            <updated>2012-03-21T00:00:00-07:00</updated>
            <id>http://www.jeditoolkit.com/2012/03/21/protocol-based-polymorphism</id>
            <content type="html">&lt;p&gt;Not a long time ago I learned about &lt;a href='http://clojure.org/' title='Dynamic programming language targeting JVM, CLR &amp;amp;  JS'&gt;clojure&lt;/a&gt;&amp;#8217;s &lt;a href='http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29' title='Wikipedia: Polymorphism (computer science'&gt;polymorphism&lt;/a&gt; constructs and &lt;a href='https://vimeo.com/11236603' title='A quick overview of Clojure protocols by Stuart Halloway'&gt;protocols&lt;/a&gt;. I was so inspired by a porwer and flexibility of &lt;a href='http://www.infoq.com/interviews/hickey-clojure-protocols' title='Rich Hickey explains Clojure polymorphism'&gt;protocol based polymorphism&lt;/a&gt; that I decide to &lt;a href='https://github.com/Gozala/protocol' title='Protocol based polymorphism for javascript'&gt;prototyped it for JS&lt;/a&gt;. In this post I will try to give you a taste of protocols and maybe even motivate you give them a try.&lt;/p&gt;

&lt;h1 id='rationale'&gt;Rationale&lt;/h1&gt;

&lt;p&gt;In programing we usually write and consume various abstractions. Typically in OOP languages abstractions are defined via (class / object) interfaces and have a nasty expression problems. Imagine that you have &lt;code&gt;A&lt;/code&gt; and &lt;code&gt;B&lt;/code&gt; sets of abstractions and sets of implementations of those abstractions. &lt;code&gt;A&lt;/code&gt; should be able to work with &lt;code&gt;B&lt;/code&gt;&amp;#8217;s abstractions, and vice versa &lt;strong&gt;without modifications of the original code&lt;/strong&gt;. While it may not sound as a problem at first, it usually is in practice. Sometimes &lt;code&gt;A&lt;/code&gt; can&amp;#8217;t use &lt;code&gt;B&lt;/code&gt;, either because they were not designed to work with each other as they were written by a different authors or because one is newer than the other. Either way such cases require code changes, which may be difficult because code is old, or complicated or has a license restrictions and there could be millions of other reasons. Any code hits these issue in some form and it&amp;#8217;s just matter of time. When that happens we&amp;#8217;re left only with a few possible solutions:&lt;/p&gt;

&lt;h4 id='feature_detection'&gt;Feature detection&lt;/h4&gt;

&lt;p&gt;Typically this is a code that is written not in terms of abstractions, but entities, that do runtime branching by &amp;#8220;feature detection&amp;#8221;. Which may be a type (&lt;code&gt;if (value instanceof Type)&lt;/code&gt;) or shape (&lt;code&gt;if (value &amp;amp;&amp;amp; typeof(value.length) === &amp;#39;number&amp;#39;)&lt;/code&gt;) based. This not only makes code harder to read &amp;amp; reason about, but it also closed. In other words every new abstraction will require rewrite of those entities, in order to accumulate more conditions and branches.&lt;/p&gt;

&lt;h4 id='wrappers'&gt;Wrappers&lt;/h4&gt;

&lt;p&gt;Typically this means that entities implementing abstraction &lt;code&gt;A&lt;/code&gt; need to be wrapped by a &amp;#8220;glue code&amp;#8221; implementing abstraction from &lt;code&gt;B&lt;/code&gt; and vice versa, if consumption is bidirectional. Unfortunately this introduces lot&amp;#8217;s of incidental complexity as wrappers ruin identity &amp;amp; don&amp;#8217;t compose (every new abstraction requires wrappers for all existing ones and vice versa). Finally problem and required changes grow progressively with a number of abstractions used.&lt;/p&gt;

&lt;h4 id='monkey_patching'&gt;Monkey patching&lt;/h4&gt;

&lt;p&gt;Typically this means that implementation of &lt;code&gt;A&lt;/code&gt; abstraction is patched with a &amp;#8220;glue code&amp;#8221; implementing support for &lt;code&gt;B&lt;/code&gt; abstraction. This still introduces complexity by ruining namespacing (different abstractions may have conflicting names). Again problem gets worth with an amount of code. Also in some languages this is not even possible.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: For more details I would recommend watching a &amp;#8220;A quick overview of &lt;a href='https://vimeo.com/11236603' title='A quick overview of Clojure protocols by Stuart Halloway'&gt;clojure protocols&lt;/a&gt;&amp;#8221; by &lt;a href='https://twitter.com/#!/stuarthalloway'&gt;Stuart Halloway&lt;/a&gt;&lt;/em&gt;.&lt;/p&gt;

&lt;h1 id='protocols'&gt;Protocols&lt;/h1&gt;

&lt;p&gt;In &lt;a href='http://www.infoq.com/interviews/hickey-clojure-protocols' title='Rich Hickey explains Clojure polymorphism'&gt;Clojure polymorphism&lt;/a&gt; is achieved using protocols. They provide a powerful way for decoupling abstraction interface definition from an actual implementation per type, without risks of interference with other libraries. Protocols allow to add polymorphic behavior to things that already exist without changing them. I&amp;#8217;ll go into more details on protocols, but for code examples I will use my &lt;a href='https://github.com/Gozala/protocol' title='Protocol based polymorphism for javascript'&gt;JS prototype&lt;/a&gt; implementation instead of clojure code.&lt;/p&gt;

&lt;p&gt;There are several motivations for &lt;a href='https://github.com/Gozala/protocol' title='Protocol based polymorphism for javascript'&gt;JS protocol&lt;/a&gt; library:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Provide a high-performance, dynamic polymorphism construct as an alternative to an existing object inheritance that does not provides any mechanics for dealing with name conflicts.&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;Provide the best parts of interfaces:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Specification only, no implementation&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;Single type can implement multiple protocols&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;Allow independent extension of types, protocols and implementations of protocols on types, by different parties.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id='define_protocol'&gt;Define protocol&lt;/h2&gt;

&lt;p&gt;A protocol is a named set of functions and their signatures defined by calling &lt;code&gt;protocol&lt;/code&gt; function:&lt;/p&gt;
&lt;pre&gt;
&lt;span class='Comment'&gt;/*jshint asi:true */&lt;/span&gt;
&lt;span class='Comment'&gt;// module: ./event-protocol&lt;/span&gt;

&lt;span class='Identifier'&gt;var&lt;/span&gt; protocol &lt;span class='Operators'&gt;=&lt;/span&gt; &lt;span class='Keyword'&gt;require&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='String'&gt;'protocol/core'&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;&lt;span class='Operators'&gt;.&lt;/span&gt;protocol

&lt;span class='Comment'&gt;// Defining a protocol for working with an event listeners / emitters.&lt;/span&gt;
module&lt;span class='Operators'&gt;.&lt;/span&gt;&lt;span class='Keyword'&gt;exports&lt;/span&gt; &lt;span class='Operators'&gt;=&lt;/span&gt; protocol&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Braces'&gt;{&lt;/span&gt;
  &lt;span class='Comment'&gt;// Function on takes event `target` object implementing&lt;/span&gt;
  &lt;span class='Comment'&gt;// `Event` protocol as first argument, event `type` string&lt;/span&gt;
  &lt;span class='Comment'&gt;// as second argument and `listener` function as a third&lt;/span&gt;
  &lt;span class='Comment'&gt;// argument. Optionally forth boolean argument can be&lt;/span&gt;
  &lt;span class='Comment'&gt;// specified to use a capture. Function allows registration&lt;/span&gt;
  &lt;span class='Comment'&gt;// of event `listeners` on the event `target` for the given&lt;/span&gt;
  &lt;span class='Comment'&gt;// event `type`.&lt;/span&gt;
  on&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Braces'&gt;[&lt;/span&gt; protocol&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Type'&gt;String&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Type'&gt;Function&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Braces'&gt;[&lt;/span&gt; &lt;span class='Type'&gt;Boolean&lt;/span&gt; &lt;span class='Braces'&gt;]&lt;/span&gt; &lt;span class='Braces'&gt;]&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;

  &lt;span class='Comment'&gt;// Function allows registration of single shot event `listener`&lt;/span&gt;
  &lt;span class='Comment'&gt;// on the event `target` of the given event `type`.&lt;/span&gt;
  once&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Braces'&gt;[&lt;/span&gt; protocol&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='String'&gt;'type'&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='String'&gt;'listener'&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Braces'&gt;[&lt;/span&gt; &lt;span class='String'&gt;'capture=false'&lt;/span&gt; &lt;span class='Braces'&gt;]&lt;/span&gt; &lt;span class='Braces'&gt;]&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;

  &lt;span class='Comment'&gt;// Unregisters event `listener` of the given `type` from the given&lt;/span&gt;
  &lt;span class='Comment'&gt;// event `target` (implementing this protocol) with a given `capture`&lt;/span&gt;
  &lt;span class='Comment'&gt;// face. Optional `capture` argument falls back to `false`.&lt;/span&gt;
  off&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Braces'&gt;[&lt;/span&gt; protocol&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='String'&gt;'type'&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='String'&gt;'listener'&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Braces'&gt;[&lt;/span&gt; &lt;span class='String'&gt;'capture=false'&lt;/span&gt;&lt;span class='Braces'&gt;]&lt;/span&gt; &lt;span class='Braces'&gt;]&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;

  &lt;span class='Comment'&gt;// Emits given `event` for the listeners of the given event `type`&lt;/span&gt;
  &lt;span class='Comment'&gt;// of the given event `target` (implementing this protocol) with a given&lt;/span&gt;
  &lt;span class='Comment'&gt;// `capture` face. Optional `capture` argument falls back to `false`.&lt;/span&gt;
  emit&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Braces'&gt;[&lt;/span&gt; protocol&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='String'&gt;'type'&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='String'&gt;'event'&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Braces'&gt;[&lt;/span&gt; &lt;span class='String'&gt;'capture=false'&lt;/span&gt; &lt;span class='Braces'&gt;]&lt;/span&gt; &lt;span class='Braces'&gt;]&lt;/span&gt;
&lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;No implementations are provided&lt;/li&gt;

&lt;li&gt;Code above returns a set of polymorphic functions and a protocol object&lt;/li&gt;

&lt;li&gt;Resulting functions dispatch on the argument with an index denoted in a signature via special &lt;code&gt;protocol&lt;/code&gt; element.&lt;/li&gt;

&lt;li&gt;Other array elements of the signature represent interface definition, and does not yet carry any special meaning. (You could use functions to highlight types or strings to highlight names or come up with something more creative).&lt;/li&gt;

&lt;li&gt;Protocol implementations can be provided at any time from any scope that has access to defined protocol.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id='implement_protocol'&gt;Implement protocol&lt;/h2&gt;

&lt;p&gt;Defined protocols can be implemented per type bases. Since everything in JS is an &lt;code&gt;Object&lt;/code&gt; protocol implementation for &lt;code&gt;Object&lt;/code&gt; type can be though as a default, since all values will automatically support protocol via that implementation:&lt;/p&gt;
&lt;pre&gt;
&lt;span class='Comment'&gt;/*jshint asi:true */&lt;/span&gt;
&lt;span class='Comment'&gt;// module: ./event-object&lt;/span&gt;

&lt;span class='Identifier'&gt;var&lt;/span&gt; Event &lt;span class='Operators'&gt;=&lt;/span&gt; &lt;span class='Keyword'&gt;require&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='String'&gt;'./event-protocol'&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt; on &lt;span class='Operators'&gt;=&lt;/span&gt; Event&lt;span class='Operators'&gt;.&lt;/span&gt;on

&lt;span class='Comment'&gt;// Weak registry of listener maps associated&lt;/span&gt;
&lt;span class='Comment'&gt;// to event targets.&lt;/span&gt;
&lt;span class='Identifier'&gt;var&lt;/span&gt; map &lt;span class='Operators'&gt;=&lt;/span&gt; WeakMap&lt;span class='Parens'&gt;()&lt;/span&gt;

&lt;span class='Comment'&gt;// Returns listeners of the given event `target`&lt;/span&gt;
&lt;span class='Comment'&gt;// for the given `type` with a given `capture` face.&lt;/span&gt;
&lt;span class='Function'&gt;function&lt;/span&gt; getListeners&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
  &lt;span class='Comment'&gt;// If there is no listeners map associated with&lt;/span&gt;
  &lt;span class='Comment'&gt;// this target then create one.&lt;/span&gt;
  &lt;span class='Statement'&gt;if&lt;/span&gt; &lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Operators'&gt;!&lt;/span&gt;map&lt;span class='Operators'&gt;.&lt;/span&gt;has&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Parens'&gt;))&lt;/span&gt; map&lt;span class='Operators'&gt;.&lt;/span&gt;set&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Type'&gt;Object&lt;/span&gt;&lt;span class='Operators'&gt;.&lt;/span&gt;create&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Keyword'&gt;null&lt;/span&gt;&lt;span class='Parens'&gt;))&lt;/span&gt;

  &lt;span class='Identifier'&gt;var&lt;/span&gt; listeners &lt;span class='Operators'&gt;=&lt;/span&gt; map&lt;span class='Operators'&gt;.&lt;/span&gt;get&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Parens'&gt;)&lt;/span&gt;
  &lt;span class='Comment'&gt;// prefix event type with a capture face flag.&lt;/span&gt;
  &lt;span class='Identifier'&gt;var&lt;/span&gt; address &lt;span class='Operators'&gt;=&lt;/span&gt; &lt;span class='Parens'&gt;(&lt;/span&gt;capture &lt;span class='Operators'&gt;?&lt;/span&gt; &lt;span class='String'&gt;'!'&lt;/span&gt; &lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='String'&gt;'-'&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Operators'&gt;+&lt;/span&gt; type
  &lt;span class='Comment'&gt;// If there is no listeners array for the given type &amp;amp; capture&lt;/span&gt;
  &lt;span class='Comment'&gt;// face than create one and return.&lt;/span&gt;
  &lt;span class='Statement'&gt;return&lt;/span&gt; listeners&lt;span class='Braces'&gt;[&lt;/span&gt;address&lt;span class='Braces'&gt;]&lt;/span&gt; &lt;span class='Operators'&gt;||&lt;/span&gt; &lt;span class='Parens'&gt;(&lt;/span&gt;listeners&lt;span class='Braces'&gt;[&lt;/span&gt;address&lt;span class='Braces'&gt;]&lt;/span&gt; &lt;span class='Operators'&gt;=&lt;/span&gt; &lt;span class='Braces'&gt;[]&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
&lt;span class='Braces'&gt;}&lt;/span&gt;

Event&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Type'&gt;Object&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
  on&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Function'&gt;function&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; listener&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
    &lt;span class='Identifier'&gt;var&lt;/span&gt; listeners &lt;span class='Operators'&gt;=&lt;/span&gt; getListeners&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt;
    &lt;span class='Comment'&gt;// Add listener if not registered yet.&lt;/span&gt;
    &lt;span class='Statement'&gt;if&lt;/span&gt; &lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Operators'&gt;!&lt;/span&gt;~listeners&lt;span class='Operators'&gt;.&lt;/span&gt;indexOf&lt;span class='Parens'&gt;(&lt;/span&gt;listener&lt;span class='Parens'&gt;))&lt;/span&gt; listeners&lt;span class='Operators'&gt;.&lt;/span&gt;push&lt;span class='Parens'&gt;(&lt;/span&gt;listener&lt;span class='Parens'&gt;)&lt;/span&gt;
  &lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;
  once&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Function'&gt;function&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; listener&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
    on&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; listener&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt;
    on&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Function'&gt;function&lt;/span&gt; cleanup&lt;span class='Parens'&gt;()&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
      off&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; listener&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt;
    &lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt;
  &lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;
  off&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Function'&gt;function&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; listener&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
    &lt;span class='Identifier'&gt;var&lt;/span&gt; listeners &lt;span class='Operators'&gt;=&lt;/span&gt; getListeners&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt;
    &lt;span class='Identifier'&gt;var&lt;/span&gt; index &lt;span class='Operators'&gt;=&lt;/span&gt; listeners&lt;span class='Operators'&gt;.&lt;/span&gt;indexOf&lt;span class='Parens'&gt;(&lt;/span&gt;listener&lt;span class='Parens'&gt;)&lt;/span&gt;
    &lt;span class='Comment'&gt;// Remove listener if registered.&lt;/span&gt;
    &lt;span class='Statement'&gt;if&lt;/span&gt; &lt;span class='Parens'&gt;(&lt;/span&gt;~index&lt;span class='Parens'&gt;)&lt;/span&gt; listeners&lt;span class='Operators'&gt;.&lt;/span&gt;splice&lt;span class='Parens'&gt;(&lt;/span&gt;index&lt;span class='Operators'&gt;,&lt;/span&gt; 1&lt;span class='Parens'&gt;)&lt;/span&gt;
  &lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;
  emit&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Function'&gt;function&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Keyword'&gt;event&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
    &lt;span class='Identifier'&gt;var&lt;/span&gt; listeners &lt;span class='Operators'&gt;=&lt;/span&gt; getListeners&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt;&lt;span class='Operators'&gt;.&lt;/span&gt;slice&lt;span class='Parens'&gt;()&lt;/span&gt;
    &lt;span class='Comment'&gt;// &lt;/span&gt;&lt;span class='Todo'&gt;TODO&lt;/span&gt;&lt;span class='Comment'&gt;: Exception handling&lt;/span&gt;
    &lt;span class='Statement'&gt;while&lt;/span&gt; &lt;span class='Parens'&gt;(&lt;/span&gt;listeners&lt;span class='Operators'&gt;.&lt;/span&gt;length&lt;span class='Parens'&gt;)&lt;/span&gt; listeners&lt;span class='Operators'&gt;.&lt;/span&gt;shift&lt;span class='Parens'&gt;()&lt;/span&gt;&lt;span class='Operators'&gt;.&lt;/span&gt;call&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Keyword'&gt;event&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
  &lt;span class='Braces'&gt;}&lt;/span&gt;
&lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Note: Implementing protocol for &lt;code&gt;Object&lt;/code&gt; type is not a requirement&lt;/em&gt;.&lt;/p&gt;

&lt;h2 id='extend_existing_types'&gt;Extend existing types&lt;/h2&gt;

&lt;p&gt;Existing types (prototypes or constructors / classes) may be extended to implement certain protocol by providing type specific implementation. For example our protocol functions would work with &lt;a href='http://nodejs.org/' title='Platform for building fast, scalable network applications'&gt;node.js&lt;/a&gt;&amp;#8217;s &lt;a href='http://nodejs.org/api/events.html#events_class_events_eventemitter' title='EventEmitter API documentation'&gt;EventEmitter&lt;/a&gt; objects, but in a funny way. Listeners registered by a standard API won&amp;#8217;t be called when emitting events with protocol function and vice versa. To fix that we can implement our protocol for the &lt;a href='http://nodejs.org/api/events.html#events_class_events_eventemitter' title='EventEmitter API documentation'&gt;EventEmitter&lt;/a&gt; type:&lt;/p&gt;
&lt;pre&gt;
&lt;span class='Comment'&gt;/*jshint asi:true */&lt;/span&gt;
&lt;span class='Comment'&gt;// module: ./event-emitter&lt;/span&gt;

&lt;span class='Identifier'&gt;var&lt;/span&gt; EventProtocol &lt;span class='Operators'&gt;=&lt;/span&gt; &lt;span class='Keyword'&gt;require&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='String'&gt;'./event-protocol'&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
&lt;span class='Identifier'&gt;var&lt;/span&gt; EventEmitter &lt;span class='Operators'&gt;=&lt;/span&gt; &lt;span class='Keyword'&gt;require&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='String'&gt;'events'&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;&lt;span class='Operators'&gt;.&lt;/span&gt;EventEmitter

EventProtocol&lt;span class='Parens'&gt;(&lt;/span&gt;EventEmitter&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
  on&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Function'&gt;function&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; listener&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
    target&lt;span class='Operators'&gt;.&lt;/span&gt;on&lt;span class='Parens'&gt;(&lt;/span&gt;type&lt;span class='Operators'&gt;,&lt;/span&gt; listener&lt;span class='Parens'&gt;)&lt;/span&gt;
  &lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;
  once&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Function'&gt;function&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; listener&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
    target&lt;span class='Operators'&gt;.&lt;/span&gt;once&lt;span class='Parens'&gt;(&lt;/span&gt;type&lt;span class='Operators'&gt;,&lt;/span&gt; listener&lt;span class='Parens'&gt;)&lt;/span&gt;
  &lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;
  off&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Function'&gt;function&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; listener&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
    target&lt;span class='Operators'&gt;.&lt;/span&gt;removeListener&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Parens'&gt;)&lt;/span&gt;
  &lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;
  emit&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Function'&gt;function&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Keyword'&gt;event&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
    target&lt;span class='Operators'&gt;.&lt;/span&gt;emit&lt;span class='Parens'&gt;(&lt;/span&gt;type&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Keyword'&gt;event&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
  &lt;span class='Braces'&gt;}&lt;/span&gt;
&lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;Now this is cool, we managed to add support for our event abstraction to a type that was not designed to work with it without changing a single line of code. But this is just a tip of the iceberg, we could implement this protocol for more types, let&amp;#8217;s try to do it for &lt;a href='https://developer.mozilla.org/en/DOM/element'&gt;DOM elements&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;
&lt;span class='Comment'&gt;/*jshint asi:true latedef: true */&lt;/span&gt;
&lt;span class='Comment'&gt;// module: ./event-dom&lt;/span&gt;

&lt;span class='Identifier'&gt;var&lt;/span&gt; Event &lt;span class='Operators'&gt;=&lt;/span&gt; &lt;span class='Keyword'&gt;require&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='String'&gt;'./event-protocol'&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;

Event&lt;span class='Parens'&gt;(&lt;/span&gt;Element&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
  on&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Function'&gt;function&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; listener&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
    target&lt;span class='Operators'&gt;.&lt;/span&gt;addEventListener&lt;span class='Parens'&gt;(&lt;/span&gt;type&lt;span class='Operators'&gt;,&lt;/span&gt; listener&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt;
  &lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;
  off&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Function'&gt;function&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; listener&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
    target&lt;span class='Operators'&gt;.&lt;/span&gt;removeListener&lt;span class='Parens'&gt;(&lt;/span&gt;type&lt;span class='Operators'&gt;,&lt;/span&gt; listener&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt;
  &lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;
  emit&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Function'&gt;function&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;target&lt;span class='Operators'&gt;,&lt;/span&gt; type&lt;span class='Operators'&gt;,&lt;/span&gt; option&lt;span class='Operators'&gt;,&lt;/span&gt; capture&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
    &lt;span class='Comment'&gt;// Note: This is simplified implementation for demo purposes.&lt;/span&gt;
    &lt;span class='Identifier'&gt;var&lt;/span&gt; &lt;span class='Keyword'&gt;document&lt;/span&gt; &lt;span class='Operators'&gt;=&lt;/span&gt; target&lt;span class='Operators'&gt;.&lt;/span&gt;ownerDocument
    &lt;span class='Identifier'&gt;var&lt;/span&gt; &lt;span class='Keyword'&gt;event&lt;/span&gt; &lt;span class='Operators'&gt;=&lt;/span&gt; &lt;span class='Keyword'&gt;document&lt;/span&gt;&lt;span class='Operators'&gt;.&lt;/span&gt;createEvent&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='String'&gt;'UIEvents'&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
    &lt;span class='Keyword'&gt;event&lt;/span&gt;&lt;span class='Operators'&gt;.&lt;/span&gt;initUIEvent&lt;span class='Parens'&gt;(&lt;/span&gt;type&lt;span class='Operators'&gt;,&lt;/span&gt; option&lt;span class='Operators'&gt;.&lt;/span&gt;bubbles&lt;span class='Operators'&gt;,&lt;/span&gt; option&lt;span class='Operators'&gt;.&lt;/span&gt;cancellable&lt;span class='Operators'&gt;,&lt;/span&gt;
                      &lt;span class='Keyword'&gt;document&lt;/span&gt;&lt;span class='Operators'&gt;.&lt;/span&gt;defaultView&lt;span class='Operators'&gt;,&lt;/span&gt; 1&lt;span class='Parens'&gt;)&lt;/span&gt;
    &lt;span class='Keyword'&gt;event&lt;/span&gt;&lt;span class='Operators'&gt;.&lt;/span&gt;data &lt;span class='Operators'&gt;=&lt;/span&gt; option&lt;span class='Operators'&gt;.&lt;/span&gt;data
    target&lt;span class='Operators'&gt;.&lt;/span&gt;dispatchEvent&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Keyword'&gt;event&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
  &lt;span class='Braces'&gt;}&lt;/span&gt;
&lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;Think of all the different JS frameworks (&lt;a href='http://backbonejs.org/#Events-trigger' title='Backbone for JS Apps with Models, Views, Collections, and Events'&gt;Backbone&lt;/a&gt;, &lt;a href='http://yuilibrary.com/yui/docs/event/' title='YUI Library'&gt;YUI&lt;/a&gt;, &lt;a href='http://mrdoob.github.com/three.js/docs/48/#EventTarget' title='three.js - JavaScript 3D library'&gt;Three.js&lt;/a&gt;, &lt;a href='http://thejit.org/static/v20/Docs/files/Options/Options-Events-js.html' title='JavaScript InfoVis Toolkit'&gt;InfoVis&lt;/a&gt;, &lt;a href='http://raphaeljs.com/reference.html#eve' title='Raphaël - JavaScript library for working with vector graphics on the web'&gt;Raphaël&lt;/a&gt;, &lt;a href='http://mootools.net/docs/core/Types/DOMEvent' title='MooTools is a compact, modular, Object-Oriented JavaScript framework'&gt;Moo Tools&lt;/a&gt;, &amp;#8230;) that have their own flavored API for working with events, you could easily extend them to support our event protocol and make their abstractions interchangeable through the rest of the codebase (that makes use of protocols) without original code changes.&lt;/p&gt;

&lt;h2 id='multiple_protocols'&gt;Multiple protocols&lt;/h2&gt;

&lt;p&gt;All the examples above showed how support for a given protocol may be added to a different types, but it&amp;#8217;s not only that, any type may be extended to implement multiple protocols with absolutely no risks of naming conflicts. Here is pretty dummy, but still an example illustrating this point:&lt;/p&gt;
&lt;pre&gt;
&lt;span class='Comment'&gt;/*jshint asi:true latedef: true */&lt;/span&gt;
&lt;span class='Comment'&gt;// module: ./installable&lt;/span&gt;

&lt;span class='Comment'&gt;// Protocol for working with installable application components.&lt;/span&gt;
&lt;span class='Identifier'&gt;var&lt;/span&gt; Installable &lt;span class='Operators'&gt;=&lt;/span&gt; protocol&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Braces'&gt;{&lt;/span&gt;
  &lt;span class='Comment'&gt;// Installs given `component` implementing this protocol. Takes optional&lt;/span&gt;
  &lt;span class='Comment'&gt;// configuration options.&lt;/span&gt;
  install&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Braces'&gt;[&lt;/span&gt; protocol&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Braces'&gt;[&lt;/span&gt; &lt;span class='String'&gt;'options:Object'&lt;/span&gt; &lt;span class='Braces'&gt;]&lt;/span&gt; &lt;span class='Braces'&gt;]&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;
  &lt;span class='Comment'&gt;// Uninstall given `component` implementing this protocol.&lt;/span&gt;
  uninstall&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Braces'&gt;[&lt;/span&gt; protocol &lt;span class='Braces'&gt;]&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;
  &lt;span class='Comment'&gt;// Activate given `component` implementing this protocol.&lt;/span&gt;
  on&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Braces'&gt;[&lt;/span&gt; protocol &lt;span class='Braces'&gt;]&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;
  &lt;span class='Comment'&gt;// Disable given `component` implementing this protocol.&lt;/span&gt;
  off&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Braces'&gt;[&lt;/span&gt; protocol &lt;span class='Braces'&gt;]&lt;/span&gt;
&lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;

Installable&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Type'&gt;Object&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
  install&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Function'&gt;function&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;component&lt;span class='Operators'&gt;,&lt;/span&gt; options&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
    &lt;span class='Comment'&gt;// Implementation details...&lt;/span&gt;
  &lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;
  uninstall&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Function'&gt;function&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;component&lt;span class='Operators'&gt;,&lt;/span&gt; options&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
    &lt;span class='Comment'&gt;// Implementation details...&lt;/span&gt;
  &lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;
  on&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Function'&gt;function&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;component&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
    component&lt;span class='Operators'&gt;.&lt;/span&gt;enabled &lt;span class='Operators'&gt;=&lt;/span&gt; &lt;span class='Boolean'&gt;true&lt;/span&gt;
  &lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;
  off&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Function'&gt;function&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;component&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
    component&lt;span class='Operators'&gt;.&lt;/span&gt;enabled &lt;span class='Operators'&gt;=&lt;/span&gt; &lt;span class='Boolean'&gt;false&lt;/span&gt;
  &lt;span class='Braces'&gt;}&lt;/span&gt;
&lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;

module&lt;span class='Operators'&gt;.&lt;/span&gt;&lt;span class='Keyword'&gt;exports&lt;/span&gt; &lt;span class='Operators'&gt;=&lt;/span&gt; Installable
&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Note:&lt;/em&gt; That even though both &lt;code&gt;Event&lt;/code&gt; and &lt;code&gt;Installable&lt;/code&gt; protocols define functions &lt;code&gt;on&lt;/code&gt; and &lt;code&gt;off&lt;/code&gt;. Also &lt;code&gt;Object&lt;/code&gt; implements both still protocols, but there no conflicts arise and functions defined by both protocols can be used without any issues!&lt;/p&gt;

&lt;h1 id='summary'&gt;Summary&lt;/h1&gt;

&lt;p&gt;I hope you find this interesting &amp;amp; I&amp;#8217;m looking forward to your feedback. All the code examples from this post can be found in the &lt;a href='https://github.com/Gozala/protocol/tree/master/examples' title='Code examples'&gt;project repository&lt;/a&gt;. At the moment library is tested and can be used on node.js &amp;amp; browser, also there are no reasons why it would not work in other JS environments.&lt;/p&gt;

&lt;p&gt;I personally think that protocols are much better feet for a JS language than redundant &lt;a href='http://wiki.ecmascript.org/doku.php?id=harmony:classes' title='Classes proposal for ES.next'&gt;classes&lt;/a&gt; and I really wish &lt;a href='http://wiki.ecmascript.org/doku.php?id=harmony:proposals' title='ECMAScript Harmony proposals'&gt;ES.next&lt;/a&gt; was considering them instead!&lt;/p&gt;</content>
        </entry>
    
        <entry>
            <title>(clojurescripting :intro)</title>
            <link href="http://www.jeditoolkit.com/2012/03/17/clojurescripting-intro.html" rel="alternate" type="text/html" />
            <updated>2012-03-17T00:00:00-07:00</updated>
            <id>http://www.jeditoolkit.com/2012/03/17/clojurescripting-intro</id>
            <content type="html">&lt;p&gt;This is a first in a series of posts I&amp;#8217;m planning to write about my &lt;a href='https://github.com/clojure/clojurescript'&gt;clojurescript&lt;/a&gt; learning experience. If you have not heard of clojurescript yet, it&amp;#8217;s a &lt;a href='http://en.wikipedia.org/wiki/Lisp_%28programming_language%29'&gt;lispy&lt;/a&gt; programing language and a flavor of pretty popular &lt;a href='http://clojure.org/'&gt;clojure&lt;/a&gt; that compile targets JS.&lt;/p&gt;

&lt;p&gt;You can find a many impressive &lt;a href='http://clojurescriptone.com/' title='Build single-page, single-language app without refreshes from repl'&gt;demos&lt;/a&gt; and &lt;a href='http://www.chris-granger.com/2012/02/20/overtone-and-clojurescript/' title='Overtone controller in ClojureScript'&gt;blog posts&lt;/a&gt; about clojurescript, but most of them assume you&amp;#8217;re coming from clojure. Even though I read a &lt;a href='http://pragprog.com/book/shcloj/programming-clojure' title='Programming Clojure by Stuart Halloway'&gt;book&lt;/a&gt; and have watched all the &lt;a href='http://blip.tv/clojure' title='Screencasts, talks and tutorials on the Clojure programming language.'&gt;clojure screencasts&lt;/a&gt;, I never managed to dive into it. Now with clojurescript it&amp;#8217;s even more tempting, so I decided to start over again and document every iteration.&lt;/p&gt;

&lt;h2 id='objectives'&gt;Objectives&lt;/h2&gt;

&lt;h4 id='1_reduce_dependencies_to_minimum'&gt;1. Reduce dependencies to minimum&lt;/h4&gt;

&lt;p&gt;Most of the JS developers are spoiled by using a language that has a brilliant runtime, it requires absolutely nothing to get started. Also, nature of JS (everything usually comes over the wire) makes us pretty picky when it comes to introducing dependencies. No matter if it&amp;#8217;s a library or tool we&amp;#8217;d like to avoid it, unless absolutely necessary. So in order to be comfortable hacking with &lt;strong&gt;clojurescript&lt;/strong&gt; my first objective is to &lt;a href='https://github.com/emezeske/lein-cljsbuild/blob/eefe08fe165d6e998a235b20672ec108820abc44/example-projects/simple/project.clj#L4-8'&gt;reduce dependencies&lt;/a&gt; I&amp;#8217;ll use to an absolute minimum.&lt;/p&gt;

&lt;h4 id='2_write_hello_world'&gt;2. Write &amp;#8220;Hello world&amp;#8221;&lt;/h4&gt;

&lt;p&gt;Another objective is of course &amp;#8220;hello world&amp;#8221; application, which in this case will mean writing a clojurescript program that writes &amp;#8220;hello world&amp;#8221; into an html document.&lt;/p&gt;

&lt;h2 id='start_a_package'&gt;Start a package&lt;/h2&gt;

&lt;p&gt;First of all we need to create a project / package. Assuming you know and love &lt;a href='http://npmjs.org/' title='Node package manager'&gt;npm&lt;/a&gt; first thing you will consider doing is finding an equivalent for a given language, which turned out to be a &lt;a href='https://github.com/technomancy/leiningen' title='Leiningen is for automating Clojure projects without setting your hair on fire.'&gt;leiningen&lt;/a&gt;! There are multiple ways one can install it. I used &lt;code&gt;brew install leiningen&lt;/code&gt; since &lt;a href='http://mxcl.github.com/homebrew/' title='The missing package manager for OS X'&gt;homebrew&lt;/a&gt; is a package manager of my choice. Once leiningen is installed, &lt;code&gt;lein new clojurescripting&lt;/code&gt; can be run to generate a blank package. Generated &lt;a href='https://github.com/Gozala/clojurescripting/blob/889645f22b67a9f4c9e421e13cd081b2f24bce2f/project.clj' title='Simple package manifest'&gt;project.clj&lt;/a&gt; file is a package descriptor containing package metadata, equivalent of &lt;a href='http://package.json.nodejitsu.com/' title='CommonJS package descriptor'&gt;package.json&lt;/a&gt; in JS. After some tweaking I ended up with something like this:&lt;/p&gt;
&lt;pre&gt;
&lt;span class='Special'&gt;(&lt;/span&gt;defproject clojurescripting &lt;span class='String'&gt;&amp;quot;1.0.0-SNAPSHOT&amp;quot;&lt;/span&gt;
  &lt;span class='Operator'&gt;:description&lt;/span&gt; &lt;span class='String'&gt;&amp;quot;Learning clojurescript&amp;quot;&lt;/span&gt;
  &lt;span class='Operator'&gt;:url&lt;/span&gt; &lt;span class='String'&gt;&amp;quot;&lt;a href='http://documentup.com/gozala/clojurescripting/'&gt;http://documentup.com/gozala/clojurescripting/&lt;/a&gt;&amp;quot;&lt;/span&gt;
  &lt;span class='Operator'&gt;:license&lt;/span&gt; &lt;span class='Special'&gt;{&lt;/span&gt; &lt;span class='Operator'&gt;:name&lt;/span&gt; &lt;span class='String'&gt;&amp;quot;MIT&amp;quot;&lt;/span&gt;
             &lt;span class='Operator'&gt;:url&lt;/span&gt; &lt;span class='String'&gt;&amp;quot;&lt;a href='http://jeditoolkit.com/LICENSE'&gt;http://jeditoolkit.com/LICENSE&lt;/a&gt;&amp;quot;&lt;/span&gt; &lt;span class='Special'&gt;})&lt;/span&gt;
&lt;/pre&gt;
&lt;h2 id='write_some_code'&gt;Write some code&lt;/h2&gt;

&lt;p&gt;The most basic thing I could think of was an &lt;code&gt;alert&lt;/code&gt; dialog with &amp;#8220;Hello World&amp;#8221; message in it. Note that it requires calling JS function out from the clojurescript, which turned out to be trivial:&lt;/p&gt;
&lt;pre&gt;
&lt;span class='Special'&gt;(&lt;/span&gt;&lt;span class='PreProc'&gt;ns&lt;/span&gt; clojurescripting.core&lt;span class='Special'&gt;)&lt;/span&gt;

&lt;span class='Special'&gt;(&lt;/span&gt;js/alert &lt;span class='String'&gt;&amp;quot;Hello World!&amp;quot;&lt;/span&gt;&lt;span class='Special'&gt;)&lt;/span&gt;
&lt;/pre&gt;
&lt;h2 id='compile_to_js'&gt;Compile to JS&lt;/h2&gt;

&lt;p&gt;Now that the code is there, we need to compile it to JS. Clojurescript &lt;a href='https://github.com/clojure/clojurescript/wiki/Quick-Start' title='ClojureScript quick start wiki page'&gt;quick start&lt;/a&gt; document describes how to do that manually, but luckily there is a &lt;a href='https://github.com/emezeske/lein-cljsbuild' title='Leiningen plugin to make ClojureScript development easy.'&gt;lein-cljsbuild&lt;/a&gt; plugin for &lt;a href='https://github.com/technomancy/leiningen' title='Leiningen is for automating Clojure projects without setting your hair on fire.'&gt;leiningen&lt;/a&gt; which can be used to automates this process. To do that you need to configure &lt;a href='https://github.com/Gozala/clojurescripting/blob/043befbc8b73d7506a6742ad9b2fdc2e26830efe/project.clj#L6-10' title='Configuration for lein-cljsbuild'&gt;project.clj&lt;/a&gt; accordingly:&lt;/p&gt;
&lt;pre&gt;
&lt;span class='Special'&gt;(&lt;/span&gt;defproject clojurescripting &lt;span class='String'&gt;&amp;quot;1.0.0-SNAPSHOT&amp;quot;&lt;/span&gt;
  &lt;span class='Operator'&gt;:description&lt;/span&gt; &lt;span class='String'&gt;&amp;quot;Learning clojurescript&amp;quot;&lt;/span&gt;
  &lt;span class='Operator'&gt;:url&lt;/span&gt; &lt;span class='String'&gt;&amp;quot;&lt;a href='http://documentup.com/gozala/clojurescripting/'&gt;http://documentup.com/gozala/clojurescripting/&lt;/a&gt;&amp;quot;&lt;/span&gt;
  &lt;span class='Operator'&gt;:license&lt;/span&gt; &lt;span class='Special'&gt;{&lt;/span&gt; &lt;span class='Operator'&gt;:name&lt;/span&gt; &lt;span class='String'&gt;&amp;quot;MIT&amp;quot;&lt;/span&gt;
             &lt;span class='Operator'&gt;:url&lt;/span&gt; &lt;span class='String'&gt;&amp;quot;&lt;a href='http://jeditoolkit.com/LICENSE'&gt;http://jeditoolkit.com/LICENSE&lt;/a&gt;&amp;quot;&lt;/span&gt; &lt;span class='Special'&gt;}&lt;/span&gt;
  &lt;span class='Operator'&gt;:plugins&lt;/span&gt; &lt;span class='Special'&gt;[[&lt;/span&gt;lein-cljsbuild &lt;span class='String'&gt;&amp;quot;0.1.2&amp;quot;&lt;/span&gt;&lt;span class='Special'&gt;]]&lt;/span&gt;
  &lt;span class='Operator'&gt;:cljsbuild&lt;/span&gt; &lt;span class='Special'&gt;{&lt;/span&gt; &lt;span class='Operator'&gt;:builds&lt;/span&gt; &lt;span class='Special'&gt;[{&lt;/span&gt; &lt;span class='Operator'&gt;:source-path&lt;/span&gt; &lt;span class='String'&gt;&amp;quot;src&amp;quot;&lt;/span&gt;
                          &lt;span class='Operator'&gt;:compiler&lt;/span&gt; &lt;span class='Special'&gt;{&lt;/span&gt; &lt;span class='Operator'&gt;:output-to&lt;/span&gt; &lt;span class='String'&gt;&amp;quot;lib/app.js&amp;quot;&lt;/span&gt;
                                      &lt;span class='Operator'&gt;:optimizations&lt;/span&gt; &lt;span class='Operator'&gt;:whitespace&lt;/span&gt;
                                      &lt;span class='Operator'&gt;:pretty-print&lt;/span&gt; &lt;span class='Boolean'&gt;true&lt;/span&gt; &lt;span class='Special'&gt;}}]})&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;Once project is configured we need to tell leiningen to install all the dependencies by running &lt;code&gt;lein deps&lt;/code&gt;. The best way to compile cljs to JS is by running &lt;code&gt;lein cljsbuild auto&lt;/code&gt; which will watch source files and automatically recompile to JS on changes. This way ergonomics of refresh-driven development is preserved when working in clojurescript.&lt;/p&gt;

&lt;p&gt;Unfortunately I had to straggle for some time before I figured out why JS file was not generated. The problem is that &lt;code&gt;lein new&lt;/code&gt; generates &lt;code&gt;core.clj&lt;/code&gt; which is a clojure file not a clojurescript one, so one needs to make sure to rename it to &lt;code&gt;core.cljs&lt;/code&gt; instead.&lt;/p&gt;

&lt;h2 id='play'&gt;Play&lt;/h2&gt;

&lt;p&gt;In order to play with a result I needed an html page, so I&amp;#8217;ve created most basic &lt;a href='https://github.com/Gozala/clojurescripting/blob/intro/index.html'&gt;index.html&lt;/a&gt; in the root of the project directory:&lt;/p&gt;
&lt;pre&gt;
&lt;span class='Function'&gt;&amp;lt;&lt;/span&gt;&lt;span class='Statement'&gt;body&lt;/span&gt;&lt;span class='Function'&gt;&amp;gt;&lt;/span&gt;&lt;span class='Identifier'&gt;&amp;lt;/&lt;/span&gt;&lt;span class='Statement'&gt;body&lt;/span&gt;&lt;span class='Identifier'&gt;&amp;gt;&lt;/span&gt;
&lt;span class='Function'&gt;&amp;lt;&lt;/span&gt;&lt;span class='Exception'&gt;script&lt;/span&gt;&lt;span class='Function'&gt; &lt;/span&gt;&lt;span class='Type'&gt;src&lt;/span&gt;&lt;span class='Function'&gt;=&lt;/span&gt;&lt;span class='String'&gt;./lib/app.js&lt;/span&gt;&lt;span class='Function'&gt;&amp;gt;&lt;/span&gt;&lt;span class='Identifier'&gt;&amp;lt;/&lt;/span&gt;&lt;span class='Exception'&gt;script&lt;/span&gt;&lt;span class='Identifier'&gt;&amp;gt;&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;As you would expect opening it in a browser displayed alert dialog. But since I wanted to write more clojurescript code I have decided to advance my example just a little bit so it writes &amp;#8220;Hello World&amp;#8221; into document body:&lt;/p&gt;
&lt;pre&gt;
&lt;span class='Special'&gt;(&lt;/span&gt;&lt;span class='PreProc'&gt;ns&lt;/span&gt; clojurescripting.core&lt;span class='Special'&gt;)&lt;/span&gt;

&lt;span class='Special'&gt;(&lt;/span&gt;&lt;span class='Define'&gt;defn&lt;/span&gt; set-html
  &lt;span class='String'&gt;&amp;quot;Sets `.innerHTML` of the given tagert element to the give `html`&amp;quot;&lt;/span&gt;
  &lt;span class='Special'&gt;[&lt;/span&gt;target &lt;span class='Special'&gt;&amp;amp;&lt;/span&gt; html&lt;span class='Special'&gt;]&lt;/span&gt;
  &lt;span class='clojureParen1'&gt;(&lt;/span&gt;&lt;span class='Function'&gt;set!&lt;/span&gt; target.innerHTML &lt;span class='clojureParen2'&gt;(&lt;/span&gt;&lt;span class='Function'&gt;apply&lt;/span&gt; &lt;span class='Function'&gt;str&lt;/span&gt; html&lt;span class='clojureParen2'&gt;)&lt;/span&gt;&lt;span class='clojureParen1'&gt;)&lt;/span&gt;&lt;span class='Special'&gt;)&lt;/span&gt;

&lt;span class='Special'&gt;(&lt;/span&gt;&lt;span class='Define'&gt;defn&lt;/span&gt; set-text
  &lt;span class='String'&gt;&amp;quot;Sets `.textContent` of the given `tagret`  to the given `text`&amp;quot;&lt;/span&gt;
  &lt;span class='Special'&gt;[&lt;/span&gt;target &lt;span class='Special'&gt;&amp;amp;&lt;/span&gt; text&lt;span class='Special'&gt;]&lt;/span&gt;
  &lt;span class='clojureParen1'&gt;(&lt;/span&gt;&lt;span class='Function'&gt;set!&lt;/span&gt; target.textContent &lt;span class='clojureParen2'&gt;(&lt;/span&gt;&lt;span class='Function'&gt;apply&lt;/span&gt; &lt;span class='Function'&gt;str&lt;/span&gt; text&lt;span class='clojureParen2'&gt;)&lt;/span&gt;&lt;span class='clojureParen1'&gt;)&lt;/span&gt;&lt;span class='Special'&gt;)&lt;/span&gt;

&lt;span class='Comment'&gt;;; Ineject &amp;quot;Hello world!&amp;quot; into document body.&lt;/span&gt;
&lt;span class='Special'&gt;(&lt;/span&gt;set-html document.body
          &lt;span class='String'&gt;&amp;quot;&amp;lt;div style='background: black; color: white;'&amp;gt;&amp;quot;&lt;/span&gt;
          &lt;span class='String'&gt;&amp;quot;&amp;lt;p&amp;gt;Hello world!&amp;lt;/p&amp;gt;&amp;quot;&lt;/span&gt;
          &lt;span class='String'&gt;&amp;quot;&amp;lt;/div&amp;gt;&amp;quot;&lt;/span&gt;&lt;span class='Special'&gt;)&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;Just a refresh and changes are applied! In fact, clojurescript has a better alternative than page refresh but that&amp;#8217;s topic of the next post!&lt;/p&gt;

&lt;h1 id='summary'&gt;Summary&lt;/h1&gt;

&lt;p&gt;Overall I&amp;#8217;m pretty happy with amount of tooling I had to use in order to write this basic clojurescript powered page. I also really liked &lt;a href='https://github.com/technomancy/leiningen' title='Leiningen is for automating Clojure projects without setting your hair on fire.'&gt;leiningen&lt;/a&gt;&amp;#8217;s plugin system and I hope &lt;a href='http://npmjs.org/' title='Node package manager'&gt;npm&lt;/a&gt; will get something similar at some point in a future. Working with pure JS and DOM on the page is seamless and ergonomics of refresh driven development is preserved! On the flip side, I found leiningen to be a painfully slow (as it&amp;#8217;s written in clojure and runs on JVM). Hopefully they will speed it up by switch to &lt;a href='https://github.com/clojure/clojurescript/wiki/Quick-Start' title='Running ClojureScript on Node.js'&gt;clojurescript on node.js&lt;/a&gt; or &lt;a href='https://github.com/takeoutweight/clojure-scheme' title='Clojure to Scheme to C to the bare metal.'&gt;clojure on bare metal&lt;/a&gt; sometime in a future.&lt;/p&gt;

&lt;p&gt;Code used in this post can be found under my &lt;a href='https://github.com/gozala/clojurescripting/tree/intro'&gt;clojurescripting&lt;/a&gt; repository on github.&lt;/p&gt;</content>
        </entry>
    
        <entry>
            <title>namespaces</title>
            <link href="http://www.jeditoolkit.com/2012/03/15/namespaces.html" rel="alternate" type="text/html" />
            <updated>2012-03-15T00:00:00-07:00</updated>
            <id>http://www.jeditoolkit.com/2012/03/15/namespaces</id>
            <content type="html">&lt;p&gt;I have &lt;a href='/2011/04/11/shareable-private-properties.html#post'&gt;previously blogged&lt;/a&gt; about inability of haveing properties with limited, controlled accessibility &amp;amp; described a hack I prototyped to overcome this limitation. Unfortunately I have failed to explain why one would need such properties, so I plan to explain it in this post. In addition, we already have a &lt;a href='http://wiki.ecmascript.org/doku.php?id=harmony:weak_maps'&gt;WeakMaps&lt;/a&gt; in spidermonkey (and also in V8) that made it possible to implement sharable privates in a proper way, you&amp;#8217;ll find more details about how we did it in Add-on SDK also in this post.&lt;/p&gt;

&lt;h2 id='why_do_we_need_privates'&gt;Why do we need privates&lt;/h2&gt;

&lt;p&gt;Sometimes program is written to work with third party, potentially malicious, code which may use variety of &lt;a href='http://code.google.com/p/google-caja/wiki/AttackVectors'&gt;attack vectors&lt;/a&gt; in order to escalate privileges and do something harmful. This is exact scenario we have in add-on SDK, where we wrap &lt;a href='http://xkcd.com/149/'&gt;sudo powered&lt;/a&gt; browser internals into higher level APIs with reduced capabilities, such that by looking at add-on&amp;#8217;s module graph we&amp;#8217;re able to say what it&amp;#8217;s capable of doing. For example if add-on only requires &lt;a href='https://addons.mozilla.org/en-US/developers/docs/sdk/latest/packages/addon-kit/docs/notifications.html'&gt;notifications module&lt;/a&gt; we know that at most it can spam user with notifications. Now if we&amp;#8217;ve just stored &lt;a href='http://xkcd.com/149/'&gt;sudo powered&lt;/a&gt; components used to implement these API under &lt;strong&gt;pseudo private&lt;/strong&gt; (&lt;code&gt;_&lt;/code&gt; prefixed) properties we would&amp;#8217;ve had no way of saying what it&amp;#8217;s capable of. There would be no guarantee that add-on code won&amp;#8217;t use those &lt;strong&gt;pseudo privates&lt;/strong&gt; to wipe users hard drive (accidentally or intentionally).&lt;/p&gt;

&lt;p&gt;This is not the only scenario where one would need to have controlled access to the implementation details. Any JS library may be used in an environment where it&amp;#8217;s exposed to code that wishes to override it&amp;#8217;s behavior by monkey-patching it&amp;#8217;s &lt;strong&gt;pseudo privates&lt;/strong&gt;, which is absolutely fine as long as, there is no other code that tries to do the same in a conflicting way. It&amp;#8217;s not to say that we should be paranoid about it, it&amp;#8217;s just there may be things that are not meant to be exposed in order to guarantee desired behavior.&lt;/p&gt;

&lt;h2 id='controlled_access_via_namespaces'&gt;Controlled access via namespaces&lt;/h2&gt;

&lt;p&gt;In Add-on SDK we have a &lt;a href='https://addons.mozilla.org/en-US/developers/docs/sdk/latest/packages/api-utils/docs/namespace.html'&gt;namespace&lt;/a&gt; module, that may be used to create a namespace functions. These functions are used to access any objects namespaced sub-objects where properties, that are not part of public interface, may be saved:&lt;/p&gt;
&lt;pre&gt;
&lt;span class='Identifier'&gt;let&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt; ns &lt;span class='Braces'&gt;}&lt;/span&gt; &lt;span class='Operators'&gt;=&lt;/span&gt; &lt;span class='Keyword'&gt;require&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='String'&gt;'namespace'&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
&lt;span class='Identifier'&gt;let&lt;/span&gt; foo &lt;span class='Operators'&gt;=&lt;/span&gt; ns&lt;span class='Parens'&gt;()&lt;/span&gt;

foo&lt;span class='Parens'&gt;(&lt;/span&gt;myObject&lt;span class='Parens'&gt;)&lt;/span&gt;&lt;span class='Operators'&gt;.&lt;/span&gt;secret &lt;span class='Operators'&gt;=&lt;/span&gt; secret
&lt;/pre&gt;
&lt;p&gt;Now only parties that have access to both &lt;code&gt;foo&lt;/code&gt; and &lt;code&gt;myObject&lt;/code&gt; are capable of seeing a &lt;code&gt;secret&lt;/code&gt;. This approach allows us to create groups of internal properties that may be shared with other components of the program by giving access to the namespace functions. Also note that not only we can use &lt;code&gt;foo&lt;/code&gt; namespace with multiple objects, but we also can use multiple namespaces with the same object:&lt;/p&gt;
&lt;pre&gt;
&lt;span class='Identifier'&gt;let&lt;/span&gt; bar &lt;span class='Operators'&gt;=&lt;/span&gt; ns&lt;span class='Parens'&gt;()&lt;/span&gt;

bar&lt;span class='Parens'&gt;(&lt;/span&gt;myObject&lt;span class='Parens'&gt;)&lt;/span&gt;&lt;span class='Operators'&gt;.&lt;/span&gt;baz &lt;span class='Operators'&gt;=&lt;/span&gt; secret&lt;span class='Operators'&gt;.&lt;/span&gt;baz

&lt;/pre&gt;
&lt;p&gt;This way we can create namespace per role that objects play in the program and associate properties to that objects in groups based on the roles. As a side effect we also eliminated naming conflicts with in the role object plays as properties are defined in different namespaces. This is very powerful, as we can define &lt;a href='https://github.com/mozilla/addon-sdk/blob/master/packages/api-utils/docs/event/core.md'&gt;event emitter&lt;/a&gt; and many other APIs that may work with a same object safely no matter what&amp;#8217;s their prototypes or own properties look like and no matter how many roles they play at the same time in program.&lt;/p&gt;

&lt;h2 id='under_the_hood'&gt;Under the hood&lt;/h2&gt;

&lt;p&gt;&lt;a href='https://github.com/mozilla/addon-sdk/blob/master/packages/api-utils/lib/namespace.js#L31-39'&gt;Implementation&lt;/a&gt; under the hood is very trivial. In nutshell namespace functions are sugared wrappers around &lt;code&gt;WeakMap&lt;/code&gt; instances, each holding a reference to a &lt;code&gt;WeakMap&lt;/code&gt; instance, which are used to map objects to an associated &amp;#8220;namespaced sub-objects&amp;#8221;, where namespaced properties are stored. Also, since objects are used as keys associated &amp;#8220;namespaced sub-objects&amp;#8221; can be claimed by garbage collector as soon as objects are collected. As an early adopters we had to face a &lt;a href='https://bugzilla.mozilla.org/show_bug.cgi?id=673468'&gt;platform bug&lt;/a&gt; requiring an &lt;a href='https://github.com/mozilla/addon-sdk/blob/master/packages/api-utils/lib/namespace.js#L7-20'&gt;ugly workaround&lt;/a&gt;, but now it&amp;#8217;s fixed and it&amp;#8217;s just matter of time when it ships!&lt;/p&gt;

&lt;h2 id='future'&gt;Future&lt;/h2&gt;

&lt;p&gt;While this is a good enough solution that we plan to migrate all the existing SDK code to, it still has limitations. For example properties are instance specific, or in other words namespaced properties of ancestors (objects in the prototype chain) are not inherited and have to be explicitly accessed, which may feel bit awkward:&lt;/p&gt;
&lt;pre&gt;
&lt;span class='Identifier'&gt;let&lt;/span&gt; decedent &lt;span class='Operators'&gt;=&lt;/span&gt; &lt;span class='Type'&gt;Object&lt;/span&gt;&lt;span class='Operators'&gt;.&lt;/span&gt;create&lt;span class='Parens'&gt;(&lt;/span&gt;myObject&lt;span class='Parens'&gt;)&lt;/span&gt;&lt;span class='Operators'&gt;;&lt;/span&gt;
&lt;span class='String'&gt;'secret'&lt;/span&gt; &lt;span class='Statement'&gt;in&lt;/span&gt; foo&lt;span class='Parens'&gt;(&lt;/span&gt;decedent&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Comment'&gt;// =&amp;gt; false&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;In a future we may have even better solution via &lt;a href='http://wiki.ecmascript.org/doku.php?id=harmony:private_name_objects'&gt;private names&lt;/a&gt;, implementation for spidermonkey is &lt;a href='https://bugzilla.mozilla.org/show_bug.cgi?id=645416'&gt;in progress&lt;/a&gt; so we&amp;#8217;re looking forward!&lt;/p&gt;</content>
        </entry>
    
        <entry>
            <title>JS Guards</title>
            <link href="http://www.jeditoolkit.com/2011/07/03/guards.html" rel="alternate" type="text/html" />
            <updated>2011-07-03T00:00:00-07:00</updated>
            <id>http://www.jeditoolkit.com/2011/07/03/guards</id>
            <content type="html">&lt;p&gt;I’ve written micro library, to solve a very common problem in JS code today. Most likely following example looks familiar:&lt;/p&gt;
&lt;pre&gt;
&lt;span class='Function'&gt;function&lt;/span&gt; Constructor&lt;span class='Parens'&gt;(&lt;/span&gt;options&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
  options &lt;span class='Operators'&gt;=&lt;/span&gt; options &lt;span class='Operators'&gt;||&lt;/span&gt; &lt;span class='Braces'&gt;{}&lt;/span&gt;
  &lt;span class='Statement'&gt;if&lt;/span&gt; &lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Operator'&gt;typeof&lt;/span&gt; options&lt;span class='Operators'&gt;.&lt;/span&gt;url &lt;span class='Operators'&gt;!==&lt;/span&gt; &lt;span class='String'&gt;'string'&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
    &lt;span class='Exception'&gt;throw&lt;/span&gt; &lt;span class='Operator'&gt;new&lt;/span&gt; &lt;span class='Error'&gt;TypeError&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='String'&gt;'url is required!'&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;

  &lt;span class='Comment'&gt;// Finally, your logic here!&lt;/span&gt;
&lt;span class='Braces'&gt;}&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;First of all, code is wrong. If falsy value is passed to a function it will misbehave. Secondly, boilerplate code makes it less readable. It takes three lines to validate just one property (very likely to have more) of the given data structure. Finally, validation code does not even belongs there, as it has nothing to do with an actual logic of a function.&lt;/p&gt;

&lt;p&gt;What we actually need is an annotation enforcing certain constraints. We don&amp;#8217;t have annotations in JS, but we have functions that are omnipotent! Just about everything can be solved everything using functions.&lt;/p&gt;
&lt;pre&gt;
&lt;span class='Function'&gt;function&lt;/span&gt; ConstructorOptions&lt;span class='Parens'&gt;(&lt;/span&gt;options&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
  &lt;span class='Statement'&gt;if&lt;/span&gt; &lt;span class='Parens'&gt;(&lt;/span&gt;options &lt;span class='Operators'&gt;===&lt;/span&gt; &lt;span class='Keyword'&gt;null&lt;/span&gt; &lt;span class='Operators'&gt;||&lt;/span&gt; options &lt;span class='Operators'&gt;===&lt;/span&gt; &lt;span class='Keyword'&gt;undefined&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
    options &lt;span class='Operators'&gt;=&lt;/span&gt; &lt;span class='Braces'&gt;{}&lt;/span&gt;
  &lt;span class='Statement'&gt;if&lt;/span&gt; &lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Operator'&gt;typeof&lt;/span&gt; options &lt;span class='Operators'&gt;!==&lt;/span&gt; &lt;span class='String'&gt;'object'&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
    &lt;span class='Exception'&gt;throw&lt;/span&gt; &lt;span class='Operator'&gt;new&lt;/span&gt; &lt;span class='Error'&gt;TypeError&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='String'&gt;'Options must an object!'&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;

  &lt;span class='Statement'&gt;if&lt;/span&gt; &lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Operator'&gt;typeof&lt;/span&gt; options&lt;span class='Operators'&gt;.&lt;/span&gt;url &lt;span class='Operators'&gt;!==&lt;/span&gt; &lt;span class='String'&gt;'string'&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
    &lt;span class='Exception'&gt;throw&lt;/span&gt; &lt;span class='Operator'&gt;new&lt;/span&gt; &lt;span class='Error'&gt;TypeError&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='String'&gt;'url is required!'&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
&lt;span class='Braces'&gt;}&lt;/span&gt;

&lt;span class='Function'&gt;function&lt;/span&gt; Constructor&lt;span class='Parens'&gt;(&lt;/span&gt;options&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
  options &lt;span class='Operators'&gt;=&lt;/span&gt; ConstructorOptions&lt;span class='Parens'&gt;(&lt;/span&gt;options&lt;span class='Parens'&gt;)&lt;/span&gt;

  &lt;span class='Comment'&gt;// Your logic here!&lt;/span&gt;
&lt;span class='Braces'&gt;}&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;This example is much better, because reader of &lt;code&gt;Constructor&lt;/code&gt; function can concentrate on function logic, without being distracted by a validation boilerplate. In addition, &lt;code&gt;options&lt;/code&gt;&amp;#8217; validation code can be independently unit tested and in some cases reused.&lt;/p&gt;

&lt;p&gt;JS &lt;a href='https://github.com/Gozala/guards' title='JS library for data type &amp;amp; data structure validations'&gt;guards&lt;/a&gt;, is a small library that takes this idea to the next level. It provides declarative and recomposable way to define data type &amp;amp; data structure validations.&lt;/p&gt;
&lt;pre&gt;
&lt;span class='Identifier'&gt;var&lt;/span&gt; guards &lt;span class='Operators'&gt;=&lt;/span&gt; &lt;span class='Keyword'&gt;require&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='String'&gt;'&lt;a href='https://raw.github.com/Gozala/guards/v0.3.0/guards.js'&gt;https://raw.github.com/Gozala/guards/v0.3.0/guards.js&lt;/a&gt;'&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;

&lt;span class='Comment'&gt;// Define a { x, y } data structure, where x and y fallback to 0.&lt;/span&gt;
&lt;span class='Identifier'&gt;var&lt;/span&gt; Point &lt;span class='Operators'&gt;=&lt;/span&gt; guards&lt;span class='Operators'&gt;.&lt;/span&gt;Schema&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Braces'&gt;{&lt;/span&gt;
  x&lt;span class='Operators'&gt;:&lt;/span&gt; guards&lt;span class='Operators'&gt;.&lt;/span&gt;&lt;span class='Type'&gt;Number&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;0&lt;span class='Parens'&gt;)&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt;
  y&lt;span class='Operators'&gt;:&lt;/span&gt; guards&lt;span class='Operators'&gt;.&lt;/span&gt;&lt;span class='Type'&gt;Number&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;0&lt;span class='Parens'&gt;)&lt;/span&gt;
&lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;

&lt;span class='Comment'&gt;// Define any type of guard as a function&lt;/span&gt;
&lt;span class='Function'&gt;function&lt;/span&gt; color&lt;span class='Parens'&gt;(&lt;/span&gt;value&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt;
  &lt;span class='Comment'&gt;// If validates just return value&lt;/span&gt;
  &lt;span class='Statement'&gt;if&lt;/span&gt; &lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Operator'&gt;typeof&lt;/span&gt; value &lt;span class='Operators'&gt;===&lt;/span&gt; &lt;span class='String'&gt;&amp;quot;number&amp;quot;&lt;/span&gt; &lt;span class='Operators'&gt;&amp;amp;&amp;amp;&lt;/span&gt; value &lt;span class='Operators'&gt;&amp;lt;=&lt;/span&gt; 255 &lt;span class='Operators'&gt;&amp;amp;&amp;amp;&lt;/span&gt; value &lt;span class='Operators'&gt;&amp;gt;=&lt;/span&gt; 0&lt;span class='Parens'&gt;)&lt;/span&gt; &lt;span class='Statement'&gt;return&lt;/span&gt; value
  &lt;span class='Comment'&gt;// If not throw TypeError&lt;/span&gt;
  &lt;span class='Exception'&gt;throw&lt;/span&gt; &lt;span class='Operator'&gt;new&lt;/span&gt; &lt;span class='Error'&gt;TypeError&lt;/span&gt;&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='String'&gt;&amp;quot;Color is a number between 0 and 255&amp;quot;&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
&lt;span class='Braces'&gt;}&lt;/span&gt;

&lt;span class='Comment'&gt;// Define a [0-255, 0-255, 0-255] data structure guard.&lt;/span&gt;
&lt;span class='Identifier'&gt;var&lt;/span&gt; RGB &lt;span class='Operators'&gt;=&lt;/span&gt; guards&lt;span class='Operators'&gt;.&lt;/span&gt;Tuple&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Braces'&gt;[&lt;/span&gt; color&lt;span class='Operators'&gt;,&lt;/span&gt; color&lt;span class='Operators'&gt;,&lt;/span&gt; color &lt;span class='Braces'&gt;]&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;

&lt;span class='Comment'&gt;// Compose data structure out of existing guards.&lt;/span&gt;
&lt;span class='Identifier'&gt;var&lt;/span&gt; Segment &lt;span class='Operators'&gt;=&lt;/span&gt; guards&lt;span class='Operators'&gt;.&lt;/span&gt;Schema&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Braces'&gt;{&lt;/span&gt;
  start&lt;span class='Operators'&gt;:&lt;/span&gt; Point&lt;span class='Operators'&gt;,&lt;/span&gt;
  end&lt;span class='Operators'&gt;:&lt;/span&gt; Point&lt;span class='Operators'&gt;,&lt;/span&gt;
  color&lt;span class='Operators'&gt;:&lt;/span&gt; RGB&lt;span class='Operators'&gt;,&lt;/span&gt;
&lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;

Segment&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Braces'&gt;{&lt;/span&gt; end&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt; y&lt;span class='Operators'&gt;:&lt;/span&gt; 23 &lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt; color&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Braces'&gt;[&lt;/span&gt;17&lt;span class='Operators'&gt;,&lt;/span&gt; 255&lt;span class='Operators'&gt;,&lt;/span&gt; 0&lt;span class='Braces'&gt;]&lt;/span&gt; &lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
&lt;span class='Comment'&gt;// { start: { x: 0, y: 0 }, end: { x: 0, y: 23 }, color: [ 17, 255, 0 ] }&lt;/span&gt;
Segment&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Braces'&gt;{&lt;/span&gt; start&lt;span class='Operators'&gt;:&lt;/span&gt; 0&lt;span class='Operators'&gt;,&lt;/span&gt; end&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Braces'&gt;{&lt;/span&gt; y&lt;span class='Operators'&gt;:&lt;/span&gt; 23 &lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Operators'&gt;,&lt;/span&gt; color&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Braces'&gt;[&lt;/span&gt;17&lt;span class='Operators'&gt;,&lt;/span&gt; 255&lt;span class='Operators'&gt;,&lt;/span&gt; 0&lt;span class='Braces'&gt;]&lt;/span&gt; &lt;span class='Braces'&gt;}&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
&lt;span class='Comment'&gt;// TypeError: Object expected instead of number `0`&lt;/span&gt;
Segment&lt;span class='Parens'&gt;(&lt;/span&gt;&lt;span class='Braces'&gt;{&lt;/span&gt; color&lt;span class='Operators'&gt;:&lt;/span&gt; &lt;span class='Braces'&gt;[&lt;/span&gt; 10&lt;span class='Operators'&gt;,&lt;/span&gt; 40&lt;span class='Operators'&gt;,&lt;/span&gt; &lt;span class='String'&gt;'30'&lt;/span&gt; &lt;span class='Braces'&gt;]}&lt;/span&gt;&lt;span class='Parens'&gt;)&lt;/span&gt;
&lt;span class='Comment'&gt;// TypeError: Color is a number between 0 and 255&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;You can use this library in browsers, jetpack and nodejs. Also, you can try it out right now via &lt;a href='http://jsfiddle.net/gozala/pfnAM/' title='JSFiddle interactive example'&gt;interactive example&lt;/a&gt; on JSFiddle. For more details and examples check out library &lt;a href='http://jeditoolkit.com/guards/docs/' title='Documentation'&gt;documentation&lt;/a&gt;. Finally, there is a &lt;a href='http://wiki.ecmascript.org/doku.php?id=strawman:guards' title='EcmaScript proposal'&gt;guards proposal&lt;/a&gt; for EcmaScript and chances are we&amp;#8217;ll get a syntax sugar some day (It will take a while though as it&amp;#8217;s not even in &lt;a href='http://wiki.ecmascript.org/doku.php?id=harmony:proposals'&gt;Harmony&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;As always I&amp;#8217;m more than happy to hear your feedback!&lt;/p&gt;</content>
        </entry>
    
</feed>