<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>James Padolsey</title>
	
	<link>http://james.padolsey.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Tue, 21 May 2013 22:08:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/JamesPadolsey" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="jamespadolsey" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">JamesPadolsey</feedburner:emailServiceId><feedburner:feedburnerHostname xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://feedburner.google.com</feedburner:feedburnerHostname><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://add.my.yahoo.com/rss?url=http%3A%2F%2Ffeeds.feedburner.com%2FJamesPadolsey" src="http://us.i1.yimg.com/us.yimg.com/i/us/my/addtomyyahoo4.gif">Subscribe with My Yahoo!</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FJamesPadolsey" src="http://www.newsgator.com/images/ngsub1.gif">Subscribe with NewsGator</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://feeds.my.aol.com/add.jsp?url=http%3A%2F%2Ffeeds.feedburner.com%2FJamesPadolsey" src="http://o.aolcdn.com/favorites.my.aol.com/webmaster/ffclient/webroot/locale/en-US/images/myAOLButtonSmall.gif">Subscribe with My AOL</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.bloglines.com/sub/http://feeds.feedburner.com/JamesPadolsey" src="http://www.bloglines.com/images/sub_modern11.gif">Subscribe with Bloglines</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.netvibes.com/subscribe.php?url=http%3A%2F%2Ffeeds.feedburner.com%2FJamesPadolsey" src="http://www.netvibes.com/img/add2netvibes.gif">Subscribe with Netvibes</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://fusion.google.com/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2FJamesPadolsey" src="http://buttons.googlesyndication.com/fusion/add.gif">Subscribe with Google</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.pageflakes.com/subscribe.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FJamesPadolsey" src="http://www.pageflakes.com/ImageFile.ashx?instanceId=Static_4&amp;fileName=ATP_blu_91x17.gif">Subscribe with Pageflakes</feedburner:feedFlare><item>
		<title>Freelancing</title>
		<link>http://james.padolsey.com/general/freelancing/</link>
		<comments>http://james.padolsey.com/general/freelancing/#comments</comments>
		<pubDate>Wed, 01 May 2013 16:01:45 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[My Life]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=2259</guid>
		<description><![CDATA[The last three years have been a whirlwind of amazing experiences. I taught English and IT in Thailand, <a href="http://james.padolsey.com/general/isaras-new-management-system/">developing a web application</a> for a charity while I was there. I worked for <a href="http://buildabrand.com/bb/">Buildabrand</a>, a logo-generation startup in Notting Hill, London. I helped the awesome folks at&#8230;]]></description>
			<content:encoded><![CDATA[<p>The last three years have been a whirlwind of amazing experiences. I taught English and IT in Thailand, <a href="http://james.padolsey.com/general/isaras-new-management-system/">developing a web application</a> for a charity while I was there. I worked for <a href="http://buildabrand.com/bb/">Buildabrand</a>, a logo-generation startup in Notting Hill, London. I helped the awesome folks at <a href="http://uxebu.com">Uxebu</a> build <a href="http://pixelplant.com">Pixelplant</a>, their Flash-to-HTML5 conversion platform, and even got to work on the open-sourced <a href="https://github.com/uxebu/bonsai">Bonsai graphics library</a>. I also worked for <a href="http://www.lab49.com">Lab49</a> building large and complex HTML5 web applications for desktop and mobile devices.</p>

<p>It is with great excitement that as of May 2013, I will be moving on to the next endeavor. I am part of a very exciting project that I can&#8217;t spill the beans on quite yet but while it&#8217;s growing I still need to make a living, and so I&#8217;m happy to be able to accept freelance work.</p>

<p>I am primarily looking for work of the following kinds:</p>

<ul>
 <li>Front-end development: HTML5/CSS3/JavaScript</li>
 <li>Consulting on HTML/CSS/JS best practices and performance concerns.</li>
 <li>Training over Skype.</li>
 <li>Canvas / SVG / CSS3 graphic-rich interface work</li>
 <li>Gardening (<em>North London only, sorry&#8230;</em>)</li>
</ul>

<p>I can do remote work or part-time on-site work in London. If you&#8217;re interested please check out <a href="http://padolsey.net/cv/cv.pdf">my CV</a> and <a href="http://github.com/padolsey">my Github profile</a>.</p>

<p>Please <a href="/contact">contact me here</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/general/freelancing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sonic &amp; The State Of Spinners</title>
		<link>http://james.padolsey.com/javascript/sonic-the-state-of-spinners/</link>
		<comments>http://james.padolsey.com/javascript/sonic-the-state-of-spinners/#comments</comments>
		<pubDate>Sun, 31 Mar 2013 18:35:06 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=2229</guid>
		<description><![CDATA[Over a year ago I released <a href="http://padolsey.net/p/Sonic/repo/demo/demo.html">Sonic</a>, a JavaScript Canvas utility for making loading spinners. I&#8217;ve used it in a couple of my own projects and was pleased with the result but I quickly became aware that others may not be happy to:


Include a&#8230;]]></description>
			<content:encoded><![CDATA[<p>Over a year ago I released <a href="http://padolsey.net/p/Sonic/repo/demo/demo.html">Sonic</a>, a JavaScript Canvas utility for making loading spinners. I&#8217;ve used it in a couple of my own projects and was pleased with the result but I quickly became aware that others may not be happy to:</p>

<ul>
<li>Include a 1.5k JS utility + specific sonic configuration</li>
<li>Depend on HTML5 Canvas: lacking browser support &amp; potential performance costs</li>
</ul>

<p>Not long after releasing Sonic, Github user <a href="https://github.com/cadc">cadc</a> made <a href="https://github.com/cadc/SonicGIF">SonicGIF</a>, introducing me to a novel concept &#8212; converting images in an HTML5 Canvas to an animated GIF on the fly using <a href="https://github.com/antimatter15/jsgif">jsgif</a>. </p>

<p>Fast forward to this week and I&#8217;ve been working on a <a href="http://padolsey.github.com/sonic-creator/">live Sonic editor</a> so you can create spinners using JavaScript, immediately have them converted to GIF, and even a PNG Sprite (<em><a href="http://james.padolsey.com/wp-content/uploads/spinner-example-sprite.png">example</a></em>), for you to use via a CSS3 steps Animation.</p>

<p>The spinner you use should be tailored to your needs though. This particular niche of graphic animation is split between various different techniques, each with merits of their own, so choose wisely&#8230;</p>

<h3>State of spinners 2013</h3>

<ul>
<li>GIF
<ul><li>Good: simple, widely supported</li>
<li>Bad: limited FPS <em>(depends on browser)</em>, 256 colours, difficult to change</li></ul></li>
<li><a href="http://en.wikipedia.org/wiki/APNG">APNG</a>
<ul><li>Good: More colors than GIF, 8-bit transparency</li>
<li>Bad: Support <a href="http://caniuse.com/apng">very limited</a>, difficult to change</li></ul></li>
<li>SVG via <code>&lt;animate&gt;</code>, <code>&lt;animateTransform&gt;</code> etc.
<ul><li>Good: Vector based, easily editable</li>
<li>Bad: <a href="http://caniuse.com/svg-smil">No IE support</a>, continually recalculated <sup><a href="#fnote-1">[1]</a></sup></li></ul></li>
<li>SVG via JavaScript
<ul><li>Good: Vector based, easily editable, <a href="http://caniuse.com/svg">widely supported</a></li>
<li>Bad: Only IE9+, continually recalculated <sup><a href="#fnote-1">[1]</a></sup></li></ul></li>
<li>Canvas via JavaScript
<ul><li>Good: <a href="http://caniuse.com/canvas">Widely supported</a>, easily editable, pixel control, can cache rendered frames</li>
<li>Bad: Only IE9+, can be slow if frames aren&#8217;t cached</li></ul></li>
<li>Sprite animated via JavaScript (i.e. setInterval + mutating backgroundPosition)
<ul><li>Good: Widely supported, relatively quick</li>
<li>Bad: Little opportunity for browser to optimise, difficult to change</li></ul></li>
<li>DOM+CSS Animated via JavaScript
<ul><li>Good: Widely supported, easily editable</li>
<li>Bad: Little opportunity for browser to optimise, continually recalculated <sup><a href="#fnote-1">[1]</a></sup></li></ul></li>
<li>Sprite animated via CSS3
<ul><li>Good: GPU acceleration (depending on browser, device)</li>
<li>Bad: Difficult to edit (Sprite), IE9 and below not supported</li></ul></li>
<li>DOM+CSS Animated via CSS3
<ul><li>Good: GPU acceleration (depending on browser, device), easily editable</li>
<li>Bad: IE9 and below not supported</li></ul></li>
</ul>

<p id="fnote-1"><small>[1]: By &#8220;continually recalculated&#8221;, I mean that the animated property values need to be recalculated on each frame and then the corresponding graphic needs to be drawn (even if you cache property values, individual elements need to be drawn for each frame). As far as I know this is unavoidable with traditional JavaScript DOM Animations (including SVG Animations). This is in contrast to Canvas, for example, where you have the opportunity to cache rendered frames and simply re-run them indefinitely.</small></p>

<p>The graphical capabilities of each technique should also be taken in account. If it&#8217;s a straightforward circling snake or dots then you&#8217;re probably best going with either SVG or DOM+CSS. If, on the other hand, it&#8217;s a more complex animation (e.g. gradients, blur, unique pathing) you may want to venture into Canvas territory or even developing your own PNG Sprite in Photoshop (<em>or <a href="http://padolsey.github.com/sonic-creator/">Sonic Creator</a>!!</em>). That said, a straightforward GIF may be the best solution if you&#8217;re not too fussed about 256 colours, lack of alpha transparency or a lower FPS.</p>

<h3>Performance</h3>

<p>From <a href="https://github.com/h5bp/lazyweb-requests/issues/103#issuecomment-15640605">limited testing</a> the most performant spinners are those using CSS3, either to animate DOM elements, or to animate through a PNG Sprite. Of course, a single spinner on a page will cost very little, so it&#8217;s not necessarily something you need to worry about.</p>

<h3>Resources</h3>

<p>For CSS+DOM Animation where all you want is a basic spinner (<em>i.e. lines arranged in a circular fashion pulsating with frequency</em>) I suggest using <a href="http://fgnass.github.com/spin.js/">spin.js</a> which utilises CSS3 Animations and falls-back to VML in older versions of IE.</p>

<p>If you do need more control and are happy using either HTML5 Canvas, GIFs or PNG Sprites (with CSS3) then I reckon you should try out <a href="http://padolsey.github.com/sonic-creator/">Sonic Creator</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/sonic-the-state-of-spinners/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>How to deal with bad code</title>
		<link>http://james.padolsey.com/general/how-to-deal-with-bad-code/</link>
		<comments>http://james.padolsey.com/general/how-to-deal-with-bad-code/#comments</comments>
		<pubDate>Sat, 23 Mar 2013 20:56:43 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Opinion]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=2217</guid>
		<description><![CDATA[
  This is some humble advice on how I believe people should deal with bad code.
  It&#8217;s not technical advice. Actually it&#8217;s not really advice. It&#8217;s just stuff I&#8217;ve
  been thinking of lately.



  Typically, the first thing a person does when encountering bad code is determining&#8230;]]></description>
			<content:encoded><![CDATA[<p>
  This is some humble advice on how I believe people should deal with bad code.
  It&#8217;s not technical advice. Actually it&#8217;s not really advice. It&#8217;s just stuff I&#8217;ve
  been thinking of lately.
</p>

<p>
  Typically, the first thing a person does when encountering bad code is determining
  who they should blame.
</p>
<p>
  Immediately it becomes a personal or tribal vendetta.
</p>

<blockquote><p>
  &#8220;Who could be so foolish?&#8221; <br />
  &#8220;Who is responsible for exposing my brain to such incoherence and blasphemy?&#8221;<br />
  &#8220;Who insults the house of &lt;Insert Team Name&gt;!?&#8221;
</p></blockquote>

<p>
  This is wrong. This should not be the first step. A deeper understanding of the code
  is necessary before we identify the poor soul who should suffer your wrath.
</p>

<h3>Understand the code</h3>

<p>
  Too often a programmer is sure. People generally are quite stubborn, but I find programmers
  to be more-so. Programmers mostly deal in absolutes so I guess such confidence is understandable.
</p>

<p>
  Approach the code with curiosity and a yearning to understand. Empathy for the person
  who wrote the code would help too. Imagine yourself in their shoes. They may not be
  anything like you. They probably care about different things too. They probably don&#8217;t have
  the same streak of what you call perfectionism. Their capacity for caring may be directed 
  somewhere other than the whitespace that nestles their parentheses or the seemingly incoherent
  naming of their variables. Maybe they have a life.
</p>

<p>
  Without empathy you are not going to understand the code, nor how it came about.
  You will simply sit there vocally festering in your self-appointed superiority.
</p>

<h3>Really understand the code</h3>

<p>
  Do you want to understand why there are such rampant GOTOs, such deeply nested switch statements,
  such obtuse naming, such ugly spacing?
</p>

<p>
  <strong>It&#8217;s dead easy to understand</strong>. Just imagine that the code is yours and that you&#8217;re
  trying to rationalise your own stupidity. Eventually your mind will fathom sensible
  defenses: &#8220;I was being rushed&#8221;, &#8220;I didn&#8217;t understand the API&#8221;, &#8220;I didn&#8217;t have sufficient overview of the domain&#8221; &#8230;
</p>

<p>
  Before you know it you&#8217;ll have a battery of excuses, and quite a few of them will probably
  touch on the truth. You could have written code this bad. It&#8217;s not beneath you.
</p>

<h3>Question the approach, form an inquiry </h3>

<p>
  As if you were a biologist discovering a new species that had evolved through millenia,
  without a watchful eye nor guiding hand. Such a creature begs questions. Such a creature
  begs inquiry. Of course, with code, you can just ask the author what their intentions were,
  and this is probably what you should do.
</p>

<p>
  Yes, it&#8217;s crazy, but true. You can approach the author and ask them. I must warn you though:
  this may force you to take a slice of humble pie.
</p>

<p>
  But what if there is no good reason. What if it is, in fact, laziness, or ignorance, or worse,
  malice?
</p>

<h3>Educate</h3>

<p>
  Yep, I&#8217;m afraid so. Now that you&#8217;ve discovered the error it falls on you to spread
  your wise words so that nobody may befall such crappy code again.
</p>

<p>
  Don&#8217;t let your ego play you though. Don&#8217;t email the entire team. Don&#8217;t shout from the 
  rooftop. Don&#8217;t write another blog post. Your biggest mistake is believing that:
</p>

<ol>
  <li>People don&#8217;t already know the pearl of wisdom you&#8217;re about to share</li>
  <li>People will sit there are willfully accept your patronising tone</li>
</ol>

<blockquote><p>
  <em><small>And if you have to email everyone. If you have to shout from the rooftops. If you
  must write a blog post about a topic that annoys you so, please remember 
  to inject parody and hints of self-deprecation so as to to disguise your ego&#8217;s intent.
  If you were to write an article you should title it genuinely though, so as to entice
  the stubborn programmer to read your post&#8230; something like &#8220;how to deal with bad code&#8221; would work well.</small></em>
</p></blockquote>

<h3>Seriously, you&#8217;re crap too</h3>

<p>Yep, sorry. You&#8217;re crap at many things. Yeh, yeh, you&#8217;re good at some stuff, but you&#8217;re pretty
crap at everything else. Don&#8217;t blame others for not being as great
as you think you are. The truth will hurt in the end. That you are in-fact the same blubbery
mamallian mass as every other programmer,.. as every other person.</p>

<p><em>Now for some more delicious humble pie&#8230;</em></p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/general/how-to-deal-with-bad-code/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>Building SIML: A new markup language</title>
		<link>http://james.padolsey.com/javascript/building-siml-a-new-markup-language/</link>
		<comments>http://james.padolsey.com/javascript/building-siml-a-new-markup-language/#comments</comments>
		<pubDate>Sun, 17 Mar 2013 22:22:04 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML/XHTML]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=2210</guid>
		<description><![CDATA[A few weeks ago I set about creating a new markup language. I wanted to learn more about language parsing, grammars, and the various difficulties involved.

I also had a very specific idea of what I wanted to create: a dead simple alternative to HTML.&#8230;]]></description>
			<content:encoded><![CDATA[<p>A few weeks ago I set about creating a new markup language. I wanted to learn more about language parsing, grammars, and the various difficulties involved.</p>

<p>I also had a very specific idea of what I wanted to create: a dead simple alternative to HTML. I&#8217;d recently picked up SASS and tried to draw on its succinctness to inspire me. CSS itself is quite succinct in how it declares elements, IDs, classes and attributes. And SASS, drawing on its own inspiration, HAML, adds the elegance of tabbed nesting.</p>

<p>I&#8217;d done <a href="https://github.com/padolsey/satisfy">something similar</a> a while ago, allowing you to get DOM structures from basic CSS selectors:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">ul li:5 span[innerHTML=&quot;item&quot;]</pre></div></div>





<p>Using <a href="https://github.com/padolsey/satisfy">satisfy()</a> this becomes:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">&lt;ul&gt;
    &lt;li&gt;&lt;span&gt;item&lt;/span&gt;&lt;/li&gt;
    &lt;li&gt;&lt;span&gt;item&lt;/span&gt;&lt;/li&gt;
    &lt;li&gt;&lt;span&gt;item&lt;/span&gt;&lt;/li&gt;
    &lt;li&gt;&lt;span&gt;item&lt;/span&gt;&lt;/li&gt;
    &lt;li&gt;&lt;span&gt;item&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;</pre></div></div>




<p>But I didn&#8217;t want to stop there; I wanted to create a way to define entire HTML documents with minimal syntax. i.e. allowing you write stuff like:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">html
  head
    title 'something'
  body
    h1 a[href=/] 'something'</pre></div></div>




<h3>Creating the parser</h3>

<p>I began by looking into <a href="http://pegjs.majda.cz/">PEGjs</a>, a really impressive parser generator for JavaScript. It allows you to specify the rules of your grammar like so:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">Single
  = Attribute
  / Element
  / Text
  / Directive
&nbsp;
//...
&nbsp;
Attribute
  = name:AttributeName _ &quot;:&quot; _ value:Value (_ &quot;;&quot;)? {
    // This bit is just regular JavaScript...
    return ['Attribute', [name, value]];
  }</pre></div></div>




<p>Above specifies the grammar rule, Single, which defines various valid &#8220;Single&#8221; definitions, such as Attribute, which is also specified above. The Attribute rule references AttributeName:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">AttributeName
  = name:[A-Za-z0-9-_]+ { return name.join(''); }
  / String</pre></div></div>




<p>An AttributeName can be a string of characters matching the pattern <code>[A-Za-z0-9-_]+</code> or a String (wrapped in quotes), which is also specified in the grammar.</p>

<p>It&#8217;s seemingly dead-simple, although there are gotchas like left-hand-side recursion and poisonously inefficient backtracking. At one point it was taking my parser 700ms to parse this:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">a {
  b {
    c {}
  }
}</pre></div></div>




<p>I found that I was writing rules in such a way that meant there was <em>a lot</em> of backtracking happening. I.e. when the parser tried a rule and failed on it, it would go back to the initial character trying the next alternate rule. In a nutshell, don&#8217;t do this:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">SomeRule
  = [a-zA-Z]+ '::' [0-9]+ ';'
  / [a-zA-Z]+ '::' [0-9]+</pre></div></div>




<p>Instead, just make the semi-colon optional:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">SomeRule
  = [a-zA-Z]+ '::' [0-9]+ ';'?</pre></div></div>




<p>This may seem trivial but it&#8217;s not always easier to spot for higher level rules. Small optimisations like this matter.</p>

<p>I was able to get that ridiculous 700ms down to 5ms! And there are still improvements to be made.</p>

<h3>Creating the generator</h3>

<p>The generator would have to be able to take output from the parser and generate HTML from it. From a string like <code>a b c</code> the parser outputs a structure like this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="br0">&#91;</span>
   <span class="st0">&quot;Element&quot;</span><span class="sy0">,</span>
   <span class="br0">&#91;</span>
      <span class="br0">&#91;</span>
         <span class="br0">&#91;</span>
            <span class="st0">&quot;Tag&quot;</span><span class="sy0">,</span>
            <span class="st0">&quot;a&quot;</span>
         <span class="br0">&#93;</span>
      <span class="br0">&#93;</span><span class="sy0">,</span>
      <span class="br0">&#91;</span>
         <span class="br0">&#91;</span>
            <span class="st0">&quot;Element&quot;</span><span class="sy0">,</span>
            <span class="br0">&#91;</span>
               <span class="br0">&#91;</span>
                  <span class="br0">&#91;</span>
                     <span class="st0">&quot;Tag&quot;</span><span class="sy0">,</span>
                     <span class="st0">&quot;b&quot;</span>
                  <span class="br0">&#93;</span>
               <span class="br0">&#93;</span><span class="sy0">,</span>
               <span class="br0">&#91;</span>
                  <span class="br0">&#91;</span>
                     <span class="st0">&quot;Element&quot;</span><span class="sy0">,</span>
                     <span class="br0">&#91;</span>
                        <span class="br0">&#91;</span>
                           <span class="br0">&#91;</span>
                              <span class="st0">&quot;Tag&quot;</span><span class="sy0">,</span>
                              <span class="st0">&quot;c&quot;</span>
                           <span class="br0">&#93;</span>
                        <span class="br0">&#93;</span>
                     <span class="br0">&#93;</span>
                  <span class="br0">&#93;</span>
               <span class="br0">&#93;</span>
            <span class="br0">&#93;</span>
         <span class="br0">&#93;</span>
      <span class="br0">&#93;</span>
   <span class="br0">&#93;</span>
<span class="br0">&#93;</span></pre></div></div>




<p>The HTML generation was quite simple to do. Essentially, I treated every Element as an entity that can have children. An Element&#8217;s children could be other Elements, Attributes, Text or even custom directives. So, this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">label <span class="br0">&#123;</span>
  label<span class="sy0">:</span> foo<span class="sy0">;</span>
  input#foo
<span class="br0">&#125;</span></pre></div></div>




<p>Would parse to:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="br0">&#91;</span>
   <span class="st0">&quot;Element&quot;</span><span class="sy0">,</span>
   <span class="br0">&#91;</span>
      <span class="br0">&#91;</span>
         <span class="br0">&#91;</span>
            <span class="st0">&quot;Tag&quot;</span><span class="sy0">,</span>
            <span class="st0">&quot;label&quot;</span>
         <span class="br0">&#93;</span>
      <span class="br0">&#93;</span><span class="sy0">,</span>
      <span class="br0">&#91;</span>
         <span class="br0">&#91;</span>
            <span class="st0">&quot;IncGroup&quot;</span><span class="sy0">,</span>
            <span class="br0">&#91;</span>
               <span class="br0">&#91;</span>
                  <span class="st0">&quot;Attribute&quot;</span><span class="sy0">,</span>
                  <span class="br0">&#91;</span>
                     <span class="st0">&quot;label&quot;</span><span class="sy0">,</span>
                     <span class="st0">&quot;foo&quot;</span>
                  <span class="br0">&#93;</span>
               <span class="br0">&#93;</span><span class="sy0">,</span>
               <span class="br0">&#91;</span>
                  <span class="st0">&quot;Element&quot;</span><span class="sy0">,</span>
                  <span class="br0">&#91;</span>
                     <span class="br0">&#91;</span>
                        <span class="br0">&#91;</span>
                           <span class="st0">&quot;Tag&quot;</span><span class="sy0">,</span>
                           <span class="st0">&quot;input&quot;</span>
                        <span class="br0">&#93;</span><span class="sy0">,</span>
                        <span class="br0">&#91;</span>
                           <span class="st0">&quot;Id&quot;</span><span class="sy0">,</span>
                           <span class="st0">&quot;foo&quot;</span>
                        <span class="br0">&#93;</span>
                     <span class="br0">&#93;</span>
                  <span class="br0">&#93;</span>
               <span class="br0">&#93;</span>
            <span class="br0">&#93;</span>
         <span class="br0">&#93;</span>
      <span class="br0">&#93;</span>
   <span class="br0">&#93;</span>
<span class="br0">&#93;</span></pre></div></div>




<p>Essentially, the hiararchy that you originally write is reflected in the tree outputted by the parser. The generator can then just recurse through this structure creating HTML strings as it goes along.</p>

<p>For example, this is the default generator for HTML attributes:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="co1">//...</span>
    _default<span class="sy0">:</span> <span class="br0">&#123;</span>
      type<span class="sy0">:</span> <span class="st0">'ATTR'</span><span class="sy0">,</span>
      make<span class="sy0">:</span> <span class="kw2">function</span><span class="br0">&#40;</span>attrName<span class="sy0">,</span> value<span class="br0">&#41;</span> <span class="br0">&#123;</span>
        <span class="kw1">if</span> <span class="br0">&#40;</span>value <span class="sy0">==</span> <span class="kw2">null</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
          <span class="kw1">return</span> attrName<span class="sy0">;</span>
        <span class="br0">&#125;</span>
        <span class="kw1">return</span> attrName <span class="sy0">+</span> <span class="st0">'=&quot;'</span> <span class="sy0">+</span> escapeHTML<span class="br0">&#40;</span>value<span class="br0">&#41;</span> <span class="sy0">+</span> <span class="st0">'&quot;'</span><span class="sy0">;</span>
      <span class="br0">&#125;</span>
    <span class="br0">&#125;</span><span class="sy0">,</span>
  <span class="co1">//...</span></pre></div></div>




<p>This would make `for:foo;` output the HTML, `for=&#8221;foo&#8221;`.</p>

<h3>Fun feature: Exclusives</h3>

<p>The fake power you feel when creating a language frequently manifests in strange features and syntax. That&#8217;s what happened here. Although I do genuinely feel that this particular one is useful.</p>

<p>I&#8217;m talking about &#8220;Exclusive Groups&#8221;. When writing your CSS-style selectors, it allows you to specify alternates within braces and then these will then be expanded so that the resulting HTML conforms to all the potential combinations. An example:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">x (a/b) // expands to: &quot;x a, x b&quot;</pre></div></div>




<p>That would give you:</p>


<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;x&gt;
  &lt;a&gt;&lt;/a&gt;
&lt;/x&gt;
&lt;x&gt;
  &lt;b&gt;&lt;/b&gt;
&lt;/x&gt;</pre></div></div>




<p>A more complex example:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">(a/b) (x/y)</pre></div></div>




<p>That would give you:</p>


<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;a&gt;&lt;x&gt;&lt;/x&gt;&lt;/a&gt;
&lt;a&gt;&lt;y&gt;&lt;/y&gt;&lt;/a&gt;
&lt;b&gt;&lt;x&gt;&lt;/x&gt;&lt;/b&gt;
&lt;b&gt;&lt;y&gt;&lt;/y&gt;&lt;/b&gt;</pre></div></div>




<p>The original selector <code>(a/b)(x/y)</code> expanded to <code>a x, a y, b x, b y</code>.</p>

<p>A little nifty, a little pointless.. perhaps. Although it can be useful:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">ul li ('A'/'List'/'Of'/'Stuff')</pre></div></div>




<p><em>(becomes)</em></p>


<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;ul&gt;
  &lt;li&gt;A&lt;/li&gt;
  &lt;li&gt;List&lt;/li&gt;
  &lt;li&gt;Of&lt;/li&gt;
  &lt;li&gt;Stuff&lt;/li&gt;
&lt;/ul&gt;</pre></div></div>




<h3>Indentation</h3>

<p>I wanted there to be the option to use traditional CSS curlies to demarcate nestings. I.e.</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">div {
  ul {
    li {
      //...
    }
  }
}</pre></div></div>




<p>But I also wanted auto-nesting via indentation, like in SASS:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">div
  ul
    li
      //...</pre></div></div>




<p>Stuff became tricky, quickly. The problem with auto-nesting is that the expected behaviour can become ambiguous:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">section
    h1
        em
      span
    div
        p</pre></div></div>




<p>Furthermore, you have to contend with spaces and tabs. Which one counts as a single level of indentation?</p>

<p>The solution I eventually rested on was simply letting the user mess stuff up themselves, if they wanted. The parser will count levels of indentation by how many whitespace characters you have. I&#8217;d like to add an error that&#8217;s thrown if the user&#8217;s silly enough to mix tabs and spaces. For now, though, they&#8217;ll have to suffer. There is an inherent ambiguity in this kind of magic. What should the parser do with this? &#8211;</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">body
  div
    p {
    span
  em
    }</pre></div></div>




<p>Right now, we assume, because the user has opted to use curlies on the <code>p</code> element, that the auto-nesting should be turned off until the curly closes. Another option would be to reset the indentation counter to zero and try to resolve children regularily. But the above code is still ambiguous. Should an error be thrown? Maybe &#8220;<code>SyntaxError: What on earth are you doing?</code>&#8220;</p>

<h3>Is it done? What is it?</h3>

<p>Yeh, it&#8217;s done, more or less.</p>

<ul>
  <li><strong><a href="https://github.com/padolsey/SIML">It&#8217;s called SIML</a></strong>.</li>
  <li><strong><a href="http://padolsey.github.com/SIML/">You can try it here!</a></strong></li>
</ul>

<p>Technically, it&#8217;s an HTML preprocessor. It&#8217;s not a templating engine. It doesn&#8217;t do that. Reasons are as follows:</p>

<ol>
  <li>Feature bloat</li>
  <li>People still write plain ol&#8217; HTML</li>
  <li>Pure DOM templates are on the rise. See AngularJS or Knockout.</li>
</ol>

<p>Also: client-side templating is a minefield of different approaches. I&#8217;ll stay out if I can.</p>

<p>SIML can cater to the DOM template style quite gracefully. This is using SIML&#8217;s Angular generator:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">ul#todo-list &gt; li
  @repeat( todo in todos | filter:statusFilter )
  @class({
    completed: todo.completed,
    editing: todo == editedTodo
  })</pre></div></div>




<p>That produces:</p>


<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;ul id=&quot;todo-list&quot;&gt;
  &lt;li
    ng-repeat=&quot;todo in todos | filter:statusFilter&quot;
    ng-class=&quot;{ completed: todo.completed, editing: todo == editedTodo }&quot;
  &gt;&lt;/li&gt;
&lt;/ul&gt;</pre></div></div>




<p>The <code>@foo</code> things you see above are directives. You can create your own in a new generator, if you so wish. The Angular generator, by default, will create <code>ng-</code> HTML attributes from undefined psueod-classes and directives. So I could do:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">div:cloak
  @show(items.length)</pre></div></div>




<p>And that would generate:</p>


<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;div ng-cloak ng-show=&quot;items.length&quot;&gt;&lt;/div&gt;</pre></div></div>




<h3>Ideas and paths</h3>

<p>It&#8217;s early days and I&#8217;m not even sure if SIML provides enough value as-is, but I do think it could serve devs quite well for the following use-cases:</p>

<ul>
  <li>Creating boilerplate HTML code quickly</li>
  <li>Creating cleaner AngularJS/Knockout markup (<a href="https://github.com/padolsey/SIML/wiki/AngularJS">Example</a>)</li>
  <li>Creating bespoke directives/pseudo-classes/attributes to serve your needs</li>
</ul>

<p>The last point is quite powerful, I think. Imagine having a bunch of pre-defined directives that would allow you to do stuff like:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">#sidebar
  input
    @datepicker({
      start: [2013,01,01]
    })</pre></div></div>




<h3>Closing remarks</h3>

<p>As a learning exercise it was very valuable. I hope, as a happy accident, I&#8217;ve created something potentially useful to others.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/building-siml-a-new-markup-language/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Permissive user input validation</title>
		<link>http://james.padolsey.com/javascript/permissive-user-input-validation/</link>
		<comments>http://james.padolsey.com/javascript/permissive-user-input-validation/#comments</comments>
		<pubDate>Sun, 27 Jan 2013 10:23:49 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Usability]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=2197</guid>
		<description><![CDATA[A <a href="http://ux.stackexchange.com/q/33564/6264">ux.stackexchange question</a> prompted me to consider how one might implement a more permissive type of input validation. It&#8217;s not rare for a form to punish the user if they add an extra space before typing in a date, or accidentally use a comma instead of&#8230;]]></description>
			<content:encoded><![CDATA[<p>A <a href="http://ux.stackexchange.com/q/33564/6264">ux.stackexchange question</a> prompted me to consider how one might implement a more permissive type of input validation. It&#8217;s not rare for a form to punish the user if they add an extra space before typing in a date, or accidentally use a comma instead of a period when typing in an IP address. After-all, we employ strict validation to keep the data correct.</p>

<p>Garbage In &#8212; Garbage Out. It rings true but maybe, taken too literally, it makes us form strict validation and a no-exceptions policy to rebels. We punish a user typing &#8217;12&#8242; instead of the fully-qualified &#8217;2012&#8242;,&#8230; why? Either it&#8217;s our thoughtlessness or it&#8217;s the very unlikely (depending on context) possibility that the user did in-fact mean the year &#8217;1912&#8242; or &#8217;1812&#8242; or &#8217;1012&#8242;&#8230;</p> 

<p>If we start down the road of permissive input validation then we need to also explore input correction. We can&#8217;t allow a rogue comma to slip in and not correct it. It&#8217;s probably best to correct it straight away (not too soon &#8212; possibly on blur) so that the actual data stored conforms to the correct format.</p>

<p>William Hudson <a href="http://www.syntagm.co.uk/design/datesstudy.htm">executed a date survey</a> in 2009 to discover all the various ways <em>American</em> users like to enter dates. The results show that users use a variety of formats. It makes perfect sense to accept all these variants and let the computer figure out what is what.</p>

<p>For the specific problem of entering dates, I would like to recommend <a href="http://www.datejs.com/">Date.js</a>, because it can successfully parse most of those variants. However, there is a big caveat when it comes to dates, especially on international forms. The American style of entering a date, MM/DD/YY, is technically impossible to differentiate from the other standard of DD/MM/YY, unless the <code>DD</code> portion happens to be above 12. For this reason I guess it would be best to cater to your localized users as best as possible.</p>

<p>An alternative is to retain rigidity in your validation but allow for some minor mistakes. For example, insist upon the ISO format of YYYY-MM-DD but don&#8217;t make a fuss if the user separates with a slash or a space (or heck, anything) instead of a dash.</p>

<p>My point is: Maybe formal validation with permissive aspects mixed in gives us the best of both worlds. We don&#8217;t punish the user for minor mistakes, and we don&#8217;t end up with ambiguous data.</p>

<p>In an attempt to practice this technique of mixing rigidity with leniency, I created <strong><a href="http://github.com/padolsey/vic.js">vic.js</a></strong>.</p>

<p>Currently validation in JavaScript can be quite an ugly affair, plagued with remnants of DHTML and overly invasive input masks. It&#8217;s not uncommon to see stuff like this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">someInput.<span class="me1">onkeyup</span> <span class="sy0">=</span> <span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
  <span class="kw1">if</span> <span class="br0">&#40;</span><span class="sy0">!</span><span class="kw1">this</span>.<span class="me1">value</span>.<span class="me1">match</span><span class="br0">&#40;</span><span class="co2">/some rigid regex/</span><span class="br0">&#41;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw3">alert</span><span class="br0">&#40;</span><span class="st0">'Enter the right value, you fool'</span><span class="br0">&#41;</span><span class="sy0">;</span>
  <span class="br0">&#125;</span>
<span class="br0">&#125;</span><span class="sy0">;</span></pre></div></div>




<p>Typically the rules are strict, the characters non-negotiable, the regular expression unyielding, and the presented invalidation UI annoying.</p>

<p><em title="Validation &amp; Input Correction">vic.js (a.k.a Vic, <acronym title="Validation &amp; Input Correction">VIC</acronym>)</em> allows you to define a lenient regular expression, and it expects you to extract your important data from the captured groups.</p>

<p>Vic&#8217;s signature goes something like this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">vic<span class="br0">&#40;</span>
  LENIENT_PATTERN_WITH_CAPTURED_GROUPS<span class="sy0">,</span>
  PER_GROUP_PROCESSOR<span class="sy0">,</span>
  POST_PROCESSOR
<span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>The simple example would be a &#8216;year&#8217; field:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> yearVic <span class="sy0">=</span> vic<span class="br0">&#40;</span>
  <span class="co2">/^\s*(\d{1,4})\s*$/</span><span class="sy0">,</span>
  <span class="kw2">function</span><span class="br0">&#40;</span>year<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="co1">// Let's assume anything between 14 and 99 is from the 1900s:</span>
    <span class="kw1">return</span> vic.<span class="me1">pad</span><span class="br0">&#40;</span>year <span class="sy0">&gt;</span> <span class="nu0">13</span> <span class="sy0">&amp;&amp;</span> year <span class="sy0">&lt;=</span> <span class="nu0">99</span> <span class="sy0">?</span> <span class="st0">'1900'</span> <span class="sy0">:</span> <span class="st0">'2000'</span> <span class="br0">&#41;</span><span class="br0">&#40;</span>year<span class="br0">&#41;</span><span class="sy0">;</span>
  <span class="br0">&#125;</span><span class="sy0">,</span>
  Number <span class="co1">// cast full output to a Number</span>
<span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
yearVic<span class="br0">&#40;</span><span class="st0">'2012'</span><span class="br0">&#41;</span><span class="sy0">;</span>   <span class="co1">// =&gt; 2012</span>
yearVic<span class="br0">&#40;</span><span class="st0">'01'</span><span class="br0">&#41;</span><span class="sy0">;</span>     <span class="co1">// =&gt; 2001</span>
yearVic<span class="br0">&#40;</span><span class="st0">'hd2kd9'</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
yearVic<span class="br0">&#40;</span><span class="st0">'20021'</span><span class="br0">&#41;</span><span class="sy0">;</span>  <span class="co1">// =&gt; false</span>
yearVic<span class="br0">&#40;</span><span class="st0">'96'</span><span class="br0">&#41;</span><span class="sy0">;</span>     <span class="co1">// =&gt; 1996</span>
yearVic<span class="br0">&#40;</span><span class="st0">'  4'</span><span class="br0">&#41;</span><span class="sy0">;</span>    <span class="co1">// =&gt; 2004</span>
yearVic<span class="br0">&#40;</span><span class="st0">'113'</span><span class="br0">&#41;</span><span class="sy0">;</span>    <span class="co1">// =&gt; 2113</span></pre></div></div>




<p>The regex used for the year example, <code>/^\s*(\d{1,4})\s*$</code>, is lenient in that it allows whitespace at the beginning and end, and doesn&#8217;t mind if the user enters one, two, three or four digits for the year. For years greater than 13 or less than 100 we assume the user is referring to the previous century, so we apply &#8217;1900&#8242; as padding, otherwise we assume we should pad with &#8217;2000&#8242;.</p>

<p>Vic offers a couple of helpers for basic tasks like padding, applying lower/upper case, etc. I&#8217;ll probably be adding to these as I think of more common use-cases for vic.</p>

<p>Vic allows more atomized per-group processing too. In this example we&#8217;ll validate a date in the form YYYY-MM-DD, but we&#8217;ll allow any one of <code>./,:-</code> (plus spaces) as separators, and we&#8217;ll validate the component numbers and pad them too:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> vicDate <span class="sy0">=</span> vic<span class="br0">&#40;</span><span class="co2">/^\s*(\d{1,4})[.\/,: -](\d{1,2})[.\/,: -](\d{1,2})\s*$/</span><span class="sy0">,</span> <span class="br0">&#123;</span>
    <span class="nu0">1</span><span class="sy0">:</span> <span class="kw2">function</span><span class="br0">&#40;</span>year<span class="br0">&#41;</span> <span class="br0">&#123;</span>
      <span class="co1">// Year between 50 and 99 assumed to be '19YY', otherwise presumed after 2000</span>
      <span class="kw1">return</span> vic.<span class="me1">pad</span><span class="br0">&#40;</span>year <span class="sy0">&gt;=</span> <span class="nu0">50</span> <span class="sy0">&amp;&amp;</span> year <span class="sy0">&lt;=</span> <span class="nu0">99</span> <span class="sy0">?</span> <span class="st0">'1900'</span> <span class="sy0">:</span> <span class="st0">'2000'</span> <span class="br0">&#41;</span><span class="br0">&#40;</span>year<span class="br0">&#41;</span><span class="sy0">;</span>
    <span class="br0">&#125;</span><span class="sy0">,</span>
    <span class="nu0">2</span><span class="sy0">:</span> <span class="kw2">function</span><span class="br0">&#40;</span>month<span class="br0">&#41;</span> <span class="br0">&#123;</span>
      <span class="kw1">return</span> month <span class="sy0">&gt;=</span> <span class="nu0">1</span> <span class="sy0">&amp;&amp;</span> month <span class="sy0">&lt;=</span> <span class="nu0">12</span> <span class="sy0">&amp;&amp;</span> vic.<span class="me1">pad</span><span class="br0">&#40;</span><span class="st0">'00'</span><span class="br0">&#41;</span><span class="br0">&#40;</span>month<span class="br0">&#41;</span><span class="sy0">;</span>
    <span class="br0">&#125;</span><span class="sy0">,</span>
    <span class="nu0">3</span><span class="sy0">:</span> <span class="kw2">function</span><span class="br0">&#40;</span>day<span class="sy0">,</span> i<span class="sy0">,</span> all<span class="br0">&#41;</span> <span class="br0">&#123;</span>
      <span class="co1">// Check that there are {day} amount of days in the entered month:</span>
      <span class="kw1">return</span> day <span class="sy0">&gt;</span> <span class="nu0">0</span> <span class="sy0">&amp;&amp;</span>
        day <span class="sy0">&lt;=</span> <span class="kw2">new</span> Date<span class="br0">&#40;</span>all<span class="br0">&#91;</span><span class="nu0">1</span><span class="br0">&#93;</span><span class="sy0">,</span> all<span class="br0">&#91;</span><span class="nu0">2</span><span class="br0">&#93;</span><span class="sy0">,</span> <span class="nu0">0</span><span class="br0">&#41;</span>.<span class="me1">getDate</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">&amp;&amp;</span>
        vic.<span class="me1">pad</span><span class="br0">&#40;</span><span class="st0">'00'</span><span class="br0">&#41;</span><span class="br0">&#40;</span>day<span class="br0">&#41;</span><span class="sy0">;</span>
    <span class="br0">&#125;</span>
<span class="br0">&#125;</span><span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span>v<span class="br0">&#41;</span> <span class="br0">&#123;</span>
  <span class="kw1">return</span> v.<span class="me1">join</span><span class="br0">&#40;</span><span class="st0">'-'</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
vicDate<span class="br0">&#40;</span><span class="st0">'111'</span><span class="br0">&#41;</span><span class="sy0">;</span>       <span class="co1">// =&gt; false</span>
vicDate<span class="br0">&#40;</span><span class="st0">'2/3/4/5'</span><span class="br0">&#41;</span><span class="sy0">;</span>   <span class="co1">// =&gt; false</span>
vicDate<span class="br0">&#40;</span><span class="st0">'16.332.2'</span><span class="br0">&#41;</span><span class="sy0">;</span>  <span class="co1">// =&gt; false</span>
vicDate<span class="br0">&#40;</span><span class="st0">'20  1  20'</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
vicDate<span class="br0">&#40;</span><span class="st0">' 1999.7.0'</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
vicDate<span class="br0">&#40;</span><span class="st0">'1999.0.1'</span><span class="br0">&#41;</span><span class="sy0">;</span>  <span class="co1">// =&gt; false</span>
&nbsp;
vicDate<span class="br0">&#40;</span><span class="st0">'1999.9.32'</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false (no 32 in Sept)</span>
vicDate<span class="br0">&#40;</span><span class="st0">'1999.2.28'</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; '1999-02-28'</span>
vicDate<span class="br0">&#40;</span><span class="st0">'1999.2.31'</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false (no 31 in Feb)</span>
&nbsp;
vicDate<span class="br0">&#40;</span><span class="st0">'1.1.1'</span><span class="br0">&#41;</span><span class="sy0">;</span>     <span class="co1">// =&gt; '2001-01-01'</span>
vicDate<span class="br0">&#40;</span><span class="st0">'1956.3.2'</span><span class="br0">&#41;</span><span class="sy0">;</span>  <span class="co1">// =&gt; '1956-03-02'</span>
vicDate<span class="br0">&#40;</span><span class="st0">'16.03-2'</span><span class="br0">&#41;</span><span class="sy0">;</span>   <span class="co1">// =&gt; '2016-03-02'</span>
vicDate<span class="br0">&#40;</span><span class="st0">' 20 1 20 '</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; '2020-01-20'</span>
vicDate<span class="br0">&#40;</span><span class="st0">'1999.7.31'</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; '1999-07-31'</span></pre></div></div>




<p>What we&#8217;ve done above is execute a rigid validation of the data that&#8217;s important to us (YYYY, MM and DD) while letting the user mess with the non-important stuff to their heart&#8217;s content (whitespace &#038; separators).</p>

<p>Vic is simple. It&#8217;s not a high level abstraction but it&#8217;s not complex. It&#8217;s a few lines of code.</p>

<p>The fact is: you could easily integrate this methodology into your own validation utilities. The basic principle is to extract the important data, validate it, but allow the user some flexibility in <em>how</em> they give you the important data.</p>

<p>Check out <strong><a href="http://github.com/padolsey/vic.js">vic.js</a></strong> on Github.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/permissive-user-input-validation/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Who maintains your JS?</title>
		<link>http://james.padolsey.com/javascript/who-maintains-your-js/</link>
		<comments>http://james.padolsey.com/javascript/who-maintains-your-js/#comments</comments>
		<pubDate>Sat, 05 Jan 2013 12:11:24 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Opinion]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=2186</guid>
		<description><![CDATA[<a href="http://james.padolsey.com/javascript/js-adolescence/">My last post</a> discussed techniques I once saw as the height of cleverness but now deem foolish. The truth is: I&#8217;m still battling with these coding dilemmas everyday&#8230; It seems to be a constant game of cleverness/terseness/speed vs. verbosity/readability.

We&#8217;re told to write code for the&#8230;]]></description>
			<content:encoded><![CDATA[<p><a href="http://james.padolsey.com/javascript/js-adolescence/">My last post</a> discussed techniques I once saw as the height of cleverness but now deem foolish. The truth is: I&#8217;m still battling with these coding dilemmas everyday&#8230; It seems to be a constant game of cleverness/terseness/speed vs. verbosity/readability.</p>

<p>We&#8217;re told to write code for the poor soul who has to maintain it in the future. What nobody tells you is how much knowledge this poor soul has, both about the language and the problem domain. People also say to expect this future maintainer to be an idiot &#8212; this will mean you write the most understandable code possible. But again: how much of an idiot is this person?</p>

<p>The fact is: we have a set of unspoken assumptions we tend to make about this mystery future maintainer.</p>

<p><em>The following are mostly assumptions related to JavaScript syntax. Unexplored assumptions are &#8216;Design patterns&#8217;, &#8216;OOP&#8217;, &#8216;The problem domain&#8217; etc.</em></p>

<h3 style="text-align:left;">Level 1 maintainer</h3>
<ul>
  <li>Sentient humanoid</li>
  <li>Speaks/Writes English well</li>
  <li>Knows what JavaScript is</li>
  <li>Has programmed before</li>
</ul>

<h3 style="text-align:left;">Level 2 maintainer</h3>
<ul>
  <li>Knows the correct syntax for if, else, for, while, do, throw, function, var &#8230;</li>
  <li>Knows about types</li>
  <li>Knows all the types available in JS</li>
  <li>Knows the difference between a statement and an expression</li>
</ul>

<h3 style="text-align:left;">Level 3 maintainer</h3>
<ul>
  <li>Knows about strict vs. non-strict equality operators</li>
  <li>Knows about short-circuiting in logical operators</li>
  <li>Knows the difference between Arrays and array-like Objects</li>
  <li>Knows several ways to cast a value, and ways to implicitly force coercion</li>
  <li>Knows regular expressions to an intermediate level (anchors, alternation, character classes)</li>
</ul>

<h3 style="text-align:left;">Level 4 maintainer</h3>
<ul>
  <li>Knows what a bitwise operator does</li>
  <li>Knows about primitives vs. objects, and wrapped primitives for method calling</li>
  <li>Knows what a closure is</li>
  <li>Knows how properties are resolved via the prototype chain</li>
  <li>Knows the differences between prefix and postfix increment operators</li>
  <li>Knows about variable/function-declaration hoisting</li>
  <li>Knows the exact difference between x==null and x===null</li>
  <li>Knows the difference between function declarations and function expressions</li>
</ul>

<h3 style="text-align:left;">Level 5 maintainer</h3>
<ul>
  <li>Knows how to check types without using typeof or instanceof</li>
  <li>Knows why <code>new Number(1) != new Number(1)</code></li>
  <li>Knows regular expressions well (lookarounds, capture vs. no-capture, greed)</li>
  <li>Knows what named function expressions are</li>
  <li>Knows the side effects of bitwise operations in JavaScript</li>
</ul>

<h3 style="text-align:left;">Level 6 maintainer (Eich level)</h3>
<ul>
  <li>Knows what values are returned by all JavaScript operators</li>
  <li>Knows all precedence and associativity of all operators</li>
  <li>Knows where ASI will put semi-colons</li>
  <li>Knows the subtle differences between ES 3.1, 5.1 and 6th Edition draft</li>
</ul>

<p>*** <small>The above is not exhaustive and is very subjective. I don&#8217;t wish to compartmentalize understanding into levels &#8212; it&#8217;s misleading. I just wanted to somehow portray these assumptions in a clearly understandable way.</small></p>

<p>I think most devs simply do not consider a future maintainer that is any less capable than themselves, and perhaps this is a problem. If you mark yourself as a maintainer 4.5 then is it fair for you to write in a way that presumes that all future readers of your code are <= 4.5? Is this reasonable?</p>

<p>I suppose it depends on what the code does (e.g. high level MVC sugar vs. low-level 3D rendering) and the people that you&#8217;re currently working with, for it is from them that you are likely to draw your estimation of an appropriate maintainer level.</p>

<p>I&#8217;m interested to hear other peoples&#8217; opinions on this.</p>

<p>What level do you assume in your future maintainers? How clever does your code get before you deem it reasonable to add a comment or opt for a more explicit and clearer technique?</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/who-maintains-your-js/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>JS adolescence</title>
		<link>http://james.padolsey.com/javascript/js-adolescence/</link>
		<comments>http://james.padolsey.com/javascript/js-adolescence/#comments</comments>
		<pubDate>Mon, 12 Nov 2012 23:31:50 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Opinion]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=2170</guid>
		<description><![CDATA[For me there was a time that can only be described as adolescence in the field of programming and more specifically JavaScript. This period was characterised by a certain laziness and hubris. I thought I was right. I thought others were wrong. I could see&#8230;]]></description>
			<content:encoded><![CDATA[<p>For me there was a time that can only be described as adolescence in the field of programming and more specifically JavaScript. This period was characterised by a certain laziness and hubris. I thought I was right. I thought others were wrong. I could see no path but the very strict one that I had boxed myself into through a process in which I longed for certainty and the expulsion of realistic doubt.</p>

<p>Today I present a short list of JavaScript practices that once seemed right but I now deem foolish (<em>in most situations</em>):</p>

<h3>Using logical operators as statements</h3>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">a<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">||</span> b.<span class="me1">foo</span>.<span class="me1">bar</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span> m <span class="sy0">&amp;&amp;</span> c<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">?</span> d<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">:</span> l <span class="sy0">||</span> m.<span class="me1">foo</span><span class="br0">&#91;</span>bee<span class="br0">&#93;</span><span class="br0">&#40;</span><span class="nu0">3</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>There is no real advantage in forgoing convention for the sake of cleverness.</p> 

<h3>Always declaring variables at the top of their scope</h3>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> calculate<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
  <span class="kw2">var</span> a<span class="sy0">,</span> m<span class="sy0">,</span> t<span class="sy0">,</span> y<span class="sy0">,</span> <span class="kw1">This</span><span class="sy0">,</span> <span class="kw1">is</span><span class="sy0">,</span> really<span class="sy0">,</span> understandable <span class="sy0">=</span> <span class="kw2">false</span><span class="sy0">;</span>
  <span class="co1">// Actual logic goes here</span>
<span class="br0">&#125;</span></pre></div></div>




<p>Instead I declare a variable where it makes sense. Much of the time this is at the top of the scope, but there are enough exceptions to make me shake my head in dissapproval at the thought of a style guide imposing religious top-of-scope declarations.</p> 

<h3>Repeatedly used inline object literals</h3>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> prepareRequest<span class="br0">&#40;</span>mode<span class="sy0">,</span> updateId<span class="sy0">,</span> value<span class="br0">&#41;</span> <span class="br0">&#123;</span>
  <span class="kw2">var</span> req <span class="sy0">=</span> <span class="br0">&#123;</span>
    mode<span class="sy0">:</span> mode<span class="sy0">,</span>
    updateId<span class="sy0">:</span> updateId<span class="sy0">,</span>
    value<span class="sy0">:</span> value<span class="sy0">,</span>
    uid<span class="sy0">:</span> genUID<span class="br0">&#40;</span><span class="br0">&#41;</span>
  <span class="br0">&#125;</span><span class="sy0">;</span>
  <span class="co1">// etc.</span>
<span class="br0">&#125;</span></pre></div></div>




<p>It&#8217;s better for clarity and performance (potentially) to define separate classes for cases where you repeatedly make object literals of the same structure. For example the above could be refactored into a Request class.</p> 

<h3>Complex inline regular expressions</h3>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">if</span> <span class="br0">&#40;</span><span class="co2">/r[ -~]?(?:m\d+|\d+[0-3]{2,})_m?$/</span>.<span class="me1">test</span><span class="br0">&#40;</span>thing<span class="br0">&#41;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
  <span class="co1">// ... wat</span>
<span class="br0">&#125;</span></pre></div></div>




<p>It makes sense to cache these things. Plus naming it means someone might have a chance of understanding WTF the code does.</p> 

<h3>Using single letter variable names</h3>

<p>They make no sense unless used in the various idiomatic loops. </p> 

<h3>Strict equality everywhere</h3>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">if</span> <span class="br0">&#40;</span><span class="kw1">typeof</span> x <span class="sy0">===</span> <span class="st0">'string'</span> <span class="sy0">&amp;&amp;</span> x <span class="sy0">===</span> <span class="st0">'mode:45'</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
  <span class="co1">// ... </span>
<span class="br0">&#125;</span></pre></div></div>




<p>Sometimes it&#8217;s overkill. Regular equality can be used in both of the above cases.</p> 

<h3>Assuming truthiness equals presence</h3>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">if</span> <span class="br0">&#40;</span><span class="sy0">!</span>cachedReturnValues<span class="br0">&#91;</span>key<span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
  cachedReturnValues<span class="br0">&#91;</span>key<span class="br0">&#93;</span> <span class="sy0">=</span> value<span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>It&#8217;s potentially dangerous. E.g. It&#8217;s better to use the &#8216;in&#8217; operator to discover presence, or even &#8216;hasOwnProperty&#8217;.</p> 

<h3>Commenting nothing or commenting every little thing</h3>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="co1">// This is a loop</span>
<span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span> i <span class="sy0">&lt;</span> arr.<span class="me1">length</span><span class="sy0">;</span> i<span class="sy0">++</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
  <span class="co1">// This is me adding one to the item in the array at the index</span>
  <span class="co1">// specified by the variable `i` declared slightly above this comment:</span>
  arr<span class="br0">&#91;</span>i<span class="br0">&#93;</span> <span class="sy0">+=</span> <span class="nu0">1</span><span class="sy0">;</span>
<span class="br0">&#125;</span> <span class="co1">// this is the end of the loop</span></pre></div></div>




<p>Commenting everything demonstrates either a lacking clarity in your code or a lacking clarity in your mind as to the intention of comments. Commenting nothing shows hubris and laziness.</p> 

<h3>Thinking I can write something reliable without unit tests</h3>

<p>Unit tests give me the confidence to be sure that my code does what I intend it to do.</p> 

<h3>Using long names and being overly specific</h3>

<p>A long name suggests bad API design. Re-think where you&#8217;re defining the variable/method. Think of a circumstance in which the variable name could be shorter &#8212; a context that makes sense for that variable. Then create that context. You&#8217;ll probably end up with a cleaner internal API. E.g.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="co1">// Version 1:</span>
<span class="kw2">var</span> responseCache <span class="sy0">=</span> <span class="br0">&#123;</span><span class="br0">&#125;</span><span class="sy0">;</span>
<span class="kw2">function</span> generateNextIDForANewResponseCacheItem<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>...<span class="br0">&#125;</span>
<span class="kw2">function</span> deleteResponseCacheItemsThatDoNotEqual<span class="br0">&#40;</span>value<span class="br0">&#41;</span> <span class="br0">&#123;</span>...<span class="br0">&#125;</span>
&nbsp;
<span class="co1">// Version 2:</span>
<span class="kw2">function</span> ResponseCache<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
  <span class="kw1">this</span>.<span class="me1">data</span> <span class="sy0">=</span> <span class="br0">&#123;</span><span class="br0">&#125;</span><span class="sy0">;</span>
<span class="br0">&#125;</span>
ResponseCache.<span class="me1">prototype</span> <span class="sy0">=</span> <span class="br0">&#123;</span>
  genNextID<span class="sy0">:</span> <span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>...<span class="br0">&#125;</span><span class="sy0">,</span>
  remove<span class="sy0">:</span> <span class="kw2">function</span><span class="br0">&#40;</span>optionalFnCheck<span class="br0">&#41;</span> <span class="br0">&#123;</span>...<span class="br0">&#125;</span>
<span class="br0">&#125;</span><span class="sy0">;</span></pre></div></div>




<h3>Strict coherence to a standard</h3>

<p>This never works and never solves what you think it will. It&#8217;s better to dynamically sway and constantly rethink your idea of what is right and wrong given each situation as it arises. This is why I try to steer clear of over-zealous coding style dogma, or all dogma for that matter.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/js-adolescence/feed/</wfw:commentRss>
		<slash:comments>50</slash:comments>
		</item>
		<item>
		<title>Character saving trickery and bitwise revelations</title>
		<link>http://james.padolsey.com/javascript/character-saving-trickery-and-bitwise-revelations/</link>
		<comments>http://james.padolsey.com/javascript/character-saving-trickery-and-bitwise-revelations/#comments</comments>
		<pubDate>Thu, 30 Aug 2012 18:20:48 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=2143</guid>
		<description><![CDATA[I want to share a tiny character-saving trick I use when flooring a number towards zero in JS. Hopefully you&#8217;re aware of the following idiom:


<pre class="javascript" style="font-family:monospace;">~~numberToBeFloored</pre>




<em>Don&#8217;t worry&#8230; this post isn&#8217;t all about ~~&#8230;</em>

In most cases this is used instead of <code>Math.floor</code> because it&#8217;s faster, terser and&#8230;]]></description>
			<content:encoded><![CDATA[<p>I want to share a tiny character-saving trick I use when flooring a number towards zero in JS. Hopefully you&#8217;re aware of the following idiom:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">~~numberToBeFloored</pre></div></div>




<p><em>Don&#8217;t worry&#8230; this post isn&#8217;t all about ~~&#8230;</em></p>

<p>In most cases this is used instead of <code>Math.floor</code> because it&#8217;s faster, terser and most important, much more confusing! Be careful though, it has different behaviour to <code>Math.floor</code>. For most cases, it has the effect of flooring the number towards zero. I wrote <a href="http://james.padolsey.com/javascript/double-bitwise-not/">a post covering it in some detail</a> a while ago. </p>

<p>It&#8217;s important to note, as <a href="http://james.padolsey.com/javascript/double-bitwise-not/#comment-29617">pointed out by Mathias Bynens</a>, that this and other similar bitwise operations only work reliably on numbers that can be expressed as 32-bit sequences. Any numbers above 2147483647 or below -2147483648 will not work as you expect. This is usually acceptable though.</p>

<p>The actual trick which I wanted to post about relates to operator precedence. I often find myself in a situation like this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="co1">// Generate random RGB red value:</span>
<span class="kw2">var</span> r <span class="sy0">=</span> ~~<span class="br0">&#40;</span>Math.<span class="me1">random</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">*</span> <span class="nu0">255</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>The bitwise-not operator (<code>`~`</code>) has a higher precedence than the multiplication operator (<code>`*`</code>) so the parentheses around <code>`Math.random() * 255`</code> are necessary to avoid the <code>`~~`</code> only applying to <code>`Math.random()`</code>. i.e.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="co1">// This doesn't work correctly</span>
<span class="kw2">var</span> r <span class="sy0">=</span> ~~Math.<span class="me1">random</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">*</span> <span class="nu0">255</span><span class="sy0">;</span></pre></div></div>




<p>Fortunately, there are other similarly effective bitwise operations that have the same flooring effect, but with lower operator precedence. One of them is <code>`0 | n`</code>. The pipe operator (bitwise OR) has a lower precedence than the multiplication operator so we can use it without the need for parentheses:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> r <span class="sy0">=</span> <span class="nu0">0</span> <span class="sy0">|</span> Math.<span class="me1">random</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">*</span> <span class="nu0">255</span><span class="sy0">;</span></pre></div></div>




<p>So we can save a couple of characters! Joy!</p>

<p>There&#8217;s also the bitwise shift operators with similarly low precedence, e.g.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> r <span class="sy0">=</span> Math.<span class="me1">random</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">*</span> <span class="nu0">255</span> <span class="sy0">&gt;&gt;</span> <span class="nu0">0</span><span class="sy0">;</span>
<span class="kw2">var</span> r <span class="sy0">=</span> Math.<span class="me1">random</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">*</span> <span class="nu0">255</span> <span class="sy0">&lt;&lt;</span> <span class="nu0">0</span><span class="sy0">;</span>
<span class="kw2">var</span> r <span class="sy0">=</span> Math.<span class="me1">random</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">*</span> <span class="nu0">255</span> <span class="sy0">&gt;&gt;&gt;</span> <span class="nu0">0</span><span class="sy0">;</span></pre></div></div>




<p>It&#8217;s definitely worth getting familiar with the various <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence">operator precedences in JavaScript</a>. It&#8217;ll help you know when you&#8217;re wasting time with parentheses.</p>

<p>Mathias also gave us a JSPerf test case benchmarking all the various flooring solutions in JavaScript. <a href="http://jsperf.com/rounding-numbers-down">Check it out</a>!</p>

<p><em>Just to be clear</em>, with all these strange bitwise flooring operations, we&#8217;re not interested in manipulating the bits of the 32-bit sequence at all. All we&#8217;re interested in is getting the integer produced by <a href="http://es5.github.com/#x9.5">the internal <code>`ToInt32`</code> operation</a>, hence why all bitwise flooring techniques are no-op bitwise operations: e.g. we <em>bitwise-not</em> and then <em>bitwise-not</em> again, causing a reversal of its effects (comparable to <code>`!!true`</code>). We <em>bitwise-or</em> with zero as an operand, meaning that for every bit-pair, the non-zero operand will win and thus <em>nothing</em> will change&#8230; and it&#8217;s the same deal with <code>`n << 0`</code> and <code>`n &#038; n`</code>...</p>

<p>What's important is that accessing the internal ToInt32 via bitwise operations is much faster than via the <code>`parseInt`</code> function, as is clearly evident in Mathias' test case.</p>

<p>... and now for the "revelation":</p>

<p>Regarding the usage of these tricks: over time I've come to the opinion <strong>that they're almost entirely pointless</strong>. The performance differences, even though they may seem staggering, are entirely negligible in most cases. You should only sacrifice readability for performance if you really need to squeeze out those precious microseconds. The only other reason for using these bitwise tricks is to make your code look more complicated than it really is, which is probably a stupid reason. As mentioned, there are also edge cases to watch out for. You can't just replace all your current <code>`Math.floor()`</code> calls with <code>`~~`</code>. Things will likely fail. What's worse is that your test coverage probably isn't exhaustive enough to catch these edge cases!</p>

<p>Even though I shouldn't, I still use them though. They're <em>"cool"</em>...</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/character-saving-trickery-and-bitwise-revelations/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>What JS devs seem to care about</title>
		<link>http://james.padolsey.com/javascript/what-js-devs-seem-to-care-about/</link>
		<comments>http://james.padolsey.com/javascript/what-js-devs-seem-to-care-about/#comments</comments>
		<pubDate>Mon, 27 Aug 2012 09:14:44 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Opinion]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=2137</guid>
		<description><![CDATA[After observing the JS &#8220;community&#8221; for a while and its various skirmishes I have come to the conclusion that, due to their capacity in attracting loud voices, these are the areas that JavaScript developers seem to care most about:


 Automatic Semi-colon Insertion
 eval is evil&#8230;]]></description>
			<content:encoded><![CDATA[<p>After observing the JS &#8220;community&#8221; for a while and its various skirmishes I have come to the conclusion that, due to their capacity in attracting loud voices, these are the areas that JavaScript developers seem to care most about:</p>

<ul>
 <li>Automatic Semi-colon Insertion</li>
 <li>eval is evil</li>
 <li>ES5 shimming (e.g. partial/incomplete shims)</li>
 <li>Browser support</li>
 <li>JSLint, JSHint, i.e. anything that judges your JS</li>
 <li>JavaScript vs. CoffeeScript</li>
 <li>JavaScript vs. Dart</li>
 <li>ES5/6 features (e.g. the fat arrow)</li>
 <li>Coding conventions (white-space, curly-braces)</li>
 <li>MV* frameworks (Backbone, AngularJS, Knockout, Ember, etc.*1000)</li>
 <li>Node.js</li>
 <li>Millisecond performance differences</li>
 <li>OLD: jQuery vs. Dojo vs. YUI vs. Prototype vs. Mootools vs. ExtJS</li>
 <li>OLD: Native prototype augmentation</li>
</ul>

<p>To clarify, there are a lot of really valuable discussions that occur surrounding the above topics, but there is also a lot of passionate rhetoric defending various sides with little basis in fact or pragmatism.</p>

<p>On the other side of the coin we have areas that are still cared about but are rarely fought over with such passion and rhetoric:</p>

<ul>
 <li>Minification tools</li>
 <li>JavaScript engines</li>
 <li>Build tools</li>
 <li>Web inspectors / profilers</li>
 <li>API naming conventions</li>
 <li>&#8230;</li>
</ul>

<p>Somewhere in between these two extremities lies AMD.</p>

<p>This is just an obvervation&#8230; and I thought it worth posting. Did I miss anything?</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/what-js-devs-seem-to-care-about/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>IIFE argument madness</title>
		<link>http://james.padolsey.com/javascript/iife-argument-madness/</link>
		<comments>http://james.padolsey.com/javascript/iife-argument-madness/#comments</comments>
		<pubDate>Fri, 06 Jul 2012 16:32:30 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=2124</guid>
		<description><![CDATA[Lots of people are doing this nowadays:


<pre class="javascript" style="font-family:monospace;"><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span>window<span class="sy0">,</span> $<span class="sy0">,</span> undefined<span class="br0">&#41;</span><span class="br0">&#123;</span>
  <span class="co1">// my special module</span>
<span class="br0">&#125;</span><span class="br0">&#40;</span>window<span class="sy0">,</span> jQuery<span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre>




If you&#8217;re using this, it&#8217;s probably not needed. It&#8217;s usually just redundant cruft. The <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/">IIFE</a> itself is okay (i.e. <code>(function(){...}())</code>). It&#8217;s the arguments that are the problem.

This strange concoction is used to protect a module&#8217;s&#8230;]]></description>
			<content:encoded><![CDATA[<p>Lots of people are doing this nowadays:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span>window<span class="sy0">,</span> $<span class="sy0">,</span> undefined<span class="br0">&#41;</span><span class="br0">&#123;</span>
  <span class="co1">// my special module</span>
<span class="br0">&#125;</span><span class="br0">&#40;</span>window<span class="sy0">,</span> jQuery<span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>If you&#8217;re using this, it&#8217;s probably not needed. It&#8217;s usually just redundant cruft. The <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/">IIFE</a> itself is okay (i.e. <code>(function(){...}())</code>). It&#8217;s the arguments that are the problem.</p>

<p>This strange concoction is used to protect a module&#8217;s scope from the environment in which its placed.</p>

<p>I have some bones to pick though&#8230;</p>

<p>If you can&#8217;t trust the <code>window</code> variable, then what can you trust? And you&#8217;re not even guaranteeing anything by passing it in. Some script could still overwrite it before you arrive. And the <code>window</code> object is still available for other scripts to mutate as they please, even after your have passed it in.</p>

<p>And you can&#8217;t trust jQuery either? You think some prototype.js imp is going to somehow travel into your code and re-assign the global dollar symbol? Ok ok, this may be permissible if you&#8217;re creating a third-party jQuery script, but certainly not if you have full control of your app.</p>

<p>Most importantly, who the hell overwrites <code>undefined</code>? Again, if you&#8217;re having to protect against this then you should deal with that issue directly. Go and knock on Bob&#8217;s door and tell him to stop overwriting <code>undefined</code>!</p>

<p>I know, I know. You&#8217;re writing a third-party script which may be placed in <em>hostile</em> environments. But here&#8217;s the thing: for every potential breach that you&#8217;re &#8220;<em>protecting</em>&#8221; yourself from there are a near-infinite amount of other things that someone could do to mess up your script, and you can&#8217;t protect yourself against all of them!</p>

<p>In my opinion, it&#8217;s acceptable for your code to be sensitive to the assumptions it makes about its environment. Yes, Bob, my module/plugin/library is going to mess up if you decide to overwrite <code>undefined</code>, and you should expect it to. Why should we protect ourselves from this imaginary (and probably non-existent) behaviour? I would love to know who overwrites <code>undefined</code>. Do you? If you do, then stop it.</p>

<p>I&#8217;m definitely not having a go at the general pattern of (i.e. the humble IIFE):</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span>   <span class="br0">&#125;</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span></pre></div></div>




<p>Actually, it&#8217;s incredibly useful in places. It allows me to create and run in a fresh scope which means I don&#8217;t have to risk polluting the global namespace.</p>

<p>Passing <code>undefined</code> though&#8230; The only possible benefits it gives are: a potential minuscule performance improvement due to a slightly lesser scope lookup (so miniscule that you&#8217;d be crazy to care). Also, it provides you with the possibility to use an alias like <code>undef</code>, but I&#8217;m not sure how helpful that really is anyway. And what&#8217;s wrong with <code>var undef;</code>?</p>

<p>Also, for readability&#8217;s sake, don&#8217;t pass so many things into your module&#8217;s main IIFE. It means the reader has to scroll all the way to the bottom just to see what each value is.</p>

<p>So, to sum up, this pattern:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span>window<span class="sy0">,</span> $<span class="sy0">,</span> undefined<span class="br0">&#41;</span><span class="br0">&#123;</span>
  <span class="co1">// all ma code</span>
<span class="br0">&#125;</span><span class="br0">&#40;</span>window<span class="sy0">,</span> jQuery<span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>&#8230; is not the cure people claim it to be.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/iife-argument-madness/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
	</channel>
</rss><!-- Dynamic Page Served (once) in 0.504 seconds --><!-- Cached page generated by WP-Super-Cache on 2013-05-21 23:16:50 -->
