<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	>

<channel>
	<title>The Accidental Developer &#187; Javascript</title>
	<atom:link href="http://osric.com/chris/accidental-developer/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://osric.com/chris/accidental-developer</link>
	<description>What if Gregor Samsa awoke a computer programmer?</description>
	<lastBuildDate>Sat, 28 Jan 2012 23:13:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Douglas Crockford: &#8220;Programming Style and Your Brain&#8221;</title>
		<link>http://osric.com/chris/accidental-developer/2012/01/douglas-crockford-programming-style-and-your-brain/</link>
		<comments>http://osric.com/chris/accidental-developer/2012/01/douglas-crockford-programming-style-and-your-brain/#comments</comments>
		<pubDate>Sat, 28 Jan 2012 23:13:31 +0000</pubDate>
		<dc:creator>Chris Herdt</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Douglas Crockford]]></category>

		<guid isPermaLink="false">http://osric.com/chris/accidental-developer/?p=632</guid>
		<description><![CDATA[Douglas Crockford provided many examples of error-resistant Javascript in his 13 January 2012 talk, "Programming Style and Your Brain." Here's a summary of the talk and 3 of the specific Javascript examples Crockford provided.]]></description>
			<content:encoded><![CDATA[<p>On 13 January, 2012, I saw Javascript expert <a href="http://www.crockford.com/">Douglas Crockford</a> deliver a talk titled &#8220;Programming Style and Your Brain&#8221; on the campus of the University of Pennsylvania. The brain portion of the talk (which Mr Crockford said borrowed heavily from Daniel Kahneman&#8217;s book <em><a href="http://www.amazon.com/gp/product/0374275637/ref=as_li_ss_tl?ie=UTF8&#038;tag=osriccom-20&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=0374275637">Thinking, Fast and Slow</a><img src="http://www.assoc-amazon.com/e/ir?t=osriccom-20&#038;l=as2&#038;o=1&#038;a=0374275637" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></em>) was really just to emphasize that human beings have 2 distinct ways of thinking: Head (slow) and Gut (fast). Computer programming requires some of both, but the same Gut-thinking that can provide useful insights can sometimes also lead us astray.</p>
<p>For example, programmers have been arguing since the 1970s about the placement of curly braces. Some people prefer:</p>
<p><code>if ( true ) {<br />
    doSomething();<br />
}</code></pre>
<p>Others prefer:</p>
<p><code>if ( true )<br />
{<br />
    doSomething();<br />
}</code></p>
<p>Crockford says that if the compiler treats these 2 forms as equivalent, then there is really no difference (so long as you are consistent). These are Gut decisions. However, people will use their Head to try to rationalize their Gut decisions and come up with some ridiculous rationalizations.</p>
<p>OK, fine. What does that mean in practical terms, i.e. writing code?<br />
<span id="more-632"></span><br />
Crockford's advice is:</p>
<blockquote><p><strong><em>Prefer forms that are error-resistant.</em></strong></p></blockquote>
<p>This is aligned closely with my own advice:</p>
<blockquote><p><strong><em>Prefer explicit forms to implicit forms.</em></strong></p></blockquote>
<p>One of Crockford's illustrations (which I have not verified but sounds plausible enough) is that the space character was introduced into Latin writing after the prior practice of running all the words together led to ambiguity and transcription errors. The space characters made the text more explicit, and therefore less prone to transcription error.</p>
<p>Here are 3 of the Javascript examples Crockford provided during his talk:</p>
<p><strong>Curly Braces &#038; Conditional Statements and Loops</strong><br />
In Javascript, a conditional statement or a loop containing only one statement can be written without curly braces:<br />
<code>if ( condition ) doSomething();</code></p>
<p>This form is error-prone. Include the curly braces:<br />
<code>if ( condition ) {<br />
    doSomething();<br />
}</code></p>
<p>Some people might complain and say that this is less concise and requires extra typing. Crockford's response was: less concise is better, and the majority of the time it takes to write a program is in thinking, not typing. If adding a few characters is slowing you down, you either need to take a typing class or spend more time thinking!</p>
<p><strong>Double-Equals versus Triple-Equals</strong><br />
Crockford said that using double-equals (==) to compare objects is <em>always</em> a bad idea because it does implicit type conversion. For example:<br />
<code>var n = 5;<br />
n == 5; //true<br />
n == "5"; // true<br />
n === "5"; // false<br />
n === 5; // true</code></p>
<p>The triple-equals also helps developers know that a number is expected, not a character or other data type.</p>
<p>As Crockford emphasized:</p>
<blockquote><p><strong><em>If a feature is sometimes problematic, and a more reliable feature exists, use it!</em></strong></p></blockquote>
<p>Some people might try to justify the use of implicit type conversion: "But I'm doing it intentionally!" Crockford said that relying on implicit type conversion means you don't know what you're doing.</p>
<p><strong>Incrementing Values</strong><br />
Crockford said he never uses the prefix or postfix ++ operator, because many people don't understand the difference and it can lead to confusion. For example:<br />
<code>var x = 5;<br />
var y = x++; // y is now 5 and x is 6<br />
var z = ++x; // z is now 7 and x is 7<br />
x += 1; // x is now 8. This is Crockford's preferred method to increment a variable</code></p>
<p>Crockford provides several resources to help people write better, more error-resistant Javascript:</p>
<ul>
<li><a href="http://javascript.crockford.com/code.html">Code Conventions for the JavaScript programming language</a></li>
<li><a href="http://www.jslint.com/">JSLint</a>, which alerts you to errors in your code or error-prone code ("JSLint <em>will</em> hurt your feelings")</li>
<li><a href="http://javascript.crockford.com/jsmin.html">JSMin</a>, which "minifies" (removes unnecessary characters) from Javascript files. This should be largely unnecessary if your web server uses <a href="http://developer.yahoo.com/performance/rules.html#gzip">Gzip compression</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://osric.com/chris/accidental-developer/2012/01/douglas-crockford-programming-style-and-your-brain/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Opening links in a new window without the target attribute</title>
		<link>http://osric.com/chris/accidental-developer/2011/02/opening-links-in-a-new-window-without-the-target-attribute/</link>
		<comments>http://osric.com/chris/accidental-developer/2011/02/opening-links-in-a-new-window-without-the-target-attribute/#comments</comments>
		<pubDate>Sun, 20 Feb 2011 21:00:26 +0000</pubDate>
		<dc:creator>Chris Herdt</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[anchor]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[target]]></category>
		<category><![CDATA[validation]]></category>
		<category><![CDATA[window]]></category>
		<category><![CDATA[xhtml]]></category>

		<guid isPermaLink="false">http://osric.com/chris/accidental-developer/?p=354</guid>
		<description><![CDATA[Web developers often use the attribute target="_blank" to force a link to open in a new window. However, if you use an HTML validation service to check your web pages, you know that the target attribute is not valid in strict versions of HTML and XHTML. There is a simple way to have a link [...]]]></description>
			<content:encoded><![CDATA[<p>Web developers often use the attribute <code>target="_blank"</code> to force a link to open in a new window. However, if you use an <a href="http://validator.w3.org/">HTML validation service</a> to check your web pages, you know that the target attribute is not valid in strict versions of HTML and XHTML.</p>
<p>There is a simple way to have a link open in a new window using Javascript. You may have seen code like this:<br />
<code>&lt;<!-- -->a href="#" onclick="window.open('http://osric.net')"&gt;osric.net web hosting&lt;<!-- -->/a&gt;</code></p>
<p>That method has some serious drawbacks, though:</p>
<ul>
<li>The user now sees <em>#</em> in the browser&#8217;s status bar instead of the actual destination URL</li>
<li>The link fails if the Javascript fails (or if the browser has Javascript disabled</li>
<li>Search engines may not follow the link</li>
</ul>
<p>I&#8217;ve written a summary of the issue and the methods I&#8217;ve found so far that best address it. I moved it to a page outside this blog because of the Javascript examples, which were easier to include on a separate page:<br />
<a href="http://osric.com/chris/javascript/javascript-anchor-target-blank.html"><br />
<img src="http://osric.com/chris/accidental-developer/wp-content/uploads/2011/02/javascript-new-window-screenshot-300x199.png" alt="" title="How to best use Javascript to open links in a new window" width="300" height="199" class="alignnone size-medium wp-image-357" /></a></p>
<p><a href="http://osric.com/chris/javascript/javascript-anchor-target-blank.html">How to best use Javascript to open links in a new window</a></p>
]]></content:encoded>
			<wfw:commentRss>http://osric.com/chris/accidental-developer/2011/02/opening-links-in-a-new-window-without-the-target-attribute/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>More People Alive Today Than Have Ever Died</title>
		<link>http://osric.com/chris/accidental-developer/2011/02/more-people-alive-today-than-have-ever-died/</link>
		<comments>http://osric.com/chris/accidental-developer/2011/02/more-people-alive-today-than-have-ever-died/#comments</comments>
		<pubDate>Wed, 16 Feb 2011 04:19:22 +0000</pubDate>
		<dc:creator>Chris Herdt</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[mathematics]]></category>
		<category><![CDATA[population]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[trees]]></category>

		<guid isPermaLink="false">http://osric.com/chris/accidental-developer/?p=314</guid>
		<description><![CDATA[A few years ago, I ran across this quote: &#8220;There are more people alive today than have ever died.&#8221; As we contemplate overpopulation, a quote like that is quite thought-provoking and shocking. Could it be that the living today outnumber all of our ancestors? It&#8217;s astounding. However, I didn&#8217;t believe it. I still don&#8217;t believe [...]]]></description>
			<content:encoded><![CDATA[<p>A few years ago, I ran across this quote:<br />
<em>&#8220;There are more people alive today than have ever died.&#8221;</em></p>
<p>As we contemplate overpopulation, a quote like that is quite thought-provoking and shocking. Could it be that the living today outnumber all of our ancestors? It&#8217;s astounding. However, I didn&#8217;t believe it. I still don&#8217;t believe it, and for good reason.<br />
<span id="more-314"></span><br />
For one thing, relatively trusted sources say otherwise:</p>
<ul>
<li><a href="http://www.snopes.com/science/stats/dead.asp">Recount Your Dead</a> (Snopes.com)</li>
<li><a href="http://www.null-hypothesis.co.uk/science/strange-but-true/item/top_scientifically_inaccurate_urban_legends">Worst 10 Urban Myths</a> (Myth #3 on <em>Null Hypothesis</em>)</li>
<li><a href="http://www.scientificamerican.com/article.cfm?id=fact-or-fiction-living-outnumber-dead">Fact or Fiction: Living People Outnumber the Dead</a> (<em>Scientific American</em>)</li>
</ul>
<p><strong>Where did the myth come from?</strong><br />
Good question. I&#8217;m guessing it came from a college sophomore studying computer science. If you look at doubling, you&#8217;ll notice that each successive result is larger, by 1, than the sum of all previous results:<br />
<code>1, 2, 4, 8, 16, 32, 64 ... n^2</code></p>
<p>If you look at a perfect binary tree, the relationship to population becomes more apparent:<br />
<div id="attachment_341" class="wp-caption alignnone" style="width: 310px"><a href="http://osric.com/chris/accidental-developer/wp-content/uploads/2011/02/binarytree.png"><img src="http://osric.com/chris/accidental-developer/wp-content/uploads/2011/02/binarytree-300x225.png" alt="A perfect binary tree" title="Perfect Binary Tree" width="300" height="225" class="size-medium wp-image-341" /></a><p class="wp-caption-text">A perfect binary tree</p></div></p>
<p><strong>&#8220;Assume a Spherical Sheep&#8221;</strong><br />
There&#8217;s a joke I&#8217;m fond of that involves a physicist describing to a farmer how he can get more wool from his sheep. &#8220;First,&#8221; he says, &#8220;assume a spherical sheep.&#8221; We often turn to simplified models to help explain complex phenomena, but in the case of the sheep and in the case of human population growth, the model makes quite a few assumptions that just don&#8217;t reflect reality. The main assumption made when using a perfect binary tree as a model is that population doubles with each successive generation. But what if that isn&#8217;t the case?</p>
<div id="attachment_344" class="wp-caption alignnone" style="width: 310px"><a href="http://osric.com/chris/accidental-developer/wp-content/uploads/2011/02/incomplete-binarytree1.png"><img src="http://osric.com/chris/accidental-developer/wp-content/uploads/2011/02/incomplete-binarytree1-300x225.png" alt="Binary tree (not complete)" title="Binary tree (not complete)" width="300" height="225" class="size-medium wp-image-344" /></a><p class="wp-caption-text">A binary tree (not complete)</p></div>
<p>Now the last generation is outnumbered by its predecessors! This could be due to disease, war, infant mortality, hungry tigers, or any number of things. World population actually <em>decreased</em> during the Black Death of the 14th century, so the population growth rate was, for a time, negative.</p>
<p>You might say, and quite rightly, that more than just one generation is alive at a given time. Your parents are probably alive. Your grandparents may be alive. You may have children. That&#8217;s why I decided to build a <a href="http://osric.com/chris/population/">population simulator</a>!</p>
<div id="attachment_346" class="wp-caption alignnone" style="width: 310px"><a href="http://osric.com/chris/population/"><img src="http://osric.com/chris/accidental-developer/wp-content/uploads/2011/02/screenshot-300x225.png" alt="Population Simulator" title="Population Simulator" width="300" height="225" class="size-medium wp-image-346" /></a><p class="wp-caption-text">Javascript-based population simulator</p></div>
<p>Use the sliders (thanks, jQuery!) to adjust some of the variables, such as the age of humankind, the number of years between generations, and the growth rate. If you hope to produce a result in line with the Earth&#8217;s current human population (about 7 billion), you will find that population growth has been, on average, extremely slow over the course of human history. It&#8217;s a rough world out there: not everyone lives (or, at very least, not long enough to reproduce).</p>
<p>You might also object that, even if population growth has been slow historically, we haven&#8217;t had a devastating plague lately&#8211;couldn&#8217;t a few recent successive generations of dramatic growth easily surpass prior generations?</p>
<div id="attachment_345" class="wp-caption alignnone" style="width: 310px"><a href="http://osric.com/chris/accidental-developer/wp-content/uploads/2011/02/population-horn.png"><img src="http://osric.com/chris/accidental-developer/wp-content/uploads/2011/02/population-horn-300x225.png" alt="Population - Slow Growth, Fast Growth" title="Population - Slow Growth, Fast Growth" width="300" height="225" class="size-medium wp-image-345" /></a><p class="wp-caption-text">The population starts doubling in the last 3 generations</p></div>
<p>Not really. The above representation only shows 27 generations&#8211;maybe 600-700 years. In reality, the long thin line of ancestors on the left vastly outnumbers the dramatic growth on the right.</p>
]]></content:encoded>
			<wfw:commentRss>http://osric.com/chris/accidental-developer/2011/02/more-people-alive-today-than-have-ever-died/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JSONP and Sencha Touch</title>
		<link>http://osric.com/chris/accidental-developer/2011/02/jsonp-and-sencha-touch/</link>
		<comments>http://osric.com/chris/accidental-developer/2011/02/jsonp-and-sencha-touch/#comments</comments>
		<pubDate>Thu, 10 Feb 2011 01:21:09 +0000</pubDate>
		<dc:creator>Chris Herdt</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[callback]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[jsonp]]></category>
		<category><![CDATA[sencha touch]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://osric.com/chris/accidental-developer/?p=330</guid>
		<description><![CDATA[I was recently trying to get a Sencha Touch demo up-and-running, but my callback functions after requests for JSON data never ran, and Firefox would throw errors along the lines of &#8220;invalid label.&#8221; I didn&#8217;t understand why&#8211;until I read more about JSONP. JSONP prefixes your JSON response with a function name, which runs when the [...]]]></description>
			<content:encoded><![CDATA[<p>I was recently trying to get a <a href="http://www.sencha.com/products/touch/">Sencha Touch</a> demo up-and-running, but my callback functions after requests for JSON data never ran, and Firefox would throw errors along the lines of &#8220;invalid label.&#8221; I didn&#8217;t understand why&#8211;until I read more about <a href="http://en.wikipedia.org/wiki/JSON#JSONP">JSONP</a>.</p>
<p>JSONP prefixes your JSON response with a function name, which runs when the response is retrieved. It&#8217;s a way of handling the data without a listener.</p>
<p>This means that your JSONP provider needs to detect a JSONP parameter, and then wrap or &#8220;pad&#8221; the response within the specified parameter value.</p>
<p>For Sencha Touch, the JSON returned should be wrapped in <em>Ext.util.JSONP.callback();</em>. If your JSON looks like this:</p>
<p><code>{"results":[{"name":"Chris"},{"name","Harry"}]}</code></p>
<p>then your JSONP should look like this:</p>
<p><code>Ext.util.JSONP.callback({"results":[{"name":"Chris"},{"name","Harry"}]});</code></p>
<p>Not that you should hard-code that function name anywhere in your JSON output&#8211;web-based APIs and services should pick up the function from your request and wrap the JSON for you. For example, the <a href="http://apiwiki.twitter.com/w/page/22554756/Twitter-Search-API-Method:-search">twitter search API</a> accepts a <em>callback</em> querystring parameter.</p>
<p><code>http://search.twitter.com/search.json?q=fakecriterions&amp;callback=myCallbackFunction</code></p>
<p>would wrap the JSON response inside</p>
<p><code>myCallbackFunction();</code></p>
<p>I ignored the extra letter in the acronym at my own peril&#8211;I figured it was just a trivial variation on JSON (which it is) that wouldn&#8217;t make any difference in how it was handled (but it does).</p>
]]></content:encoded>
			<wfw:commentRss>http://osric.com/chris/accidental-developer/2011/02/jsonp-and-sencha-touch/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Parsing a URL Querystring with Javascript</title>
		<link>http://osric.com/chris/accidental-developer/2011/02/parsing-a-url-querystring-with-javascript/</link>
		<comments>http://osric.com/chris/accidental-developer/2011/02/parsing-a-url-querystring-with-javascript/#comments</comments>
		<pubDate>Tue, 08 Feb 2011 00:42:24 +0000</pubDate>
		<dc:creator>Chris Herdt</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[parameters]]></category>
		<category><![CDATA[parse]]></category>
		<category><![CDATA[querystring]]></category>

		<guid isPermaLink="false">http://osric.com/chris/accidental-developer/?p=332</guid>
		<description><![CDATA[Can you access a URL querystring with Javascript? Yes. Just refer to location.search. Why would you want to reference the URL querystring with Javascript? A couple reasons come to mind. Highlighting a specified term wherever it appears within a page Linking to a dynamic page in a specific state The latter, which I have also [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Can you access a URL querystring with Javascript?</strong><br />
Yes. Just refer to <em>location.search</em>.</p>
<p><strong>Why would you <em>want </em>to reference the URL querystring with Javascript?</strong><br />
A couple reasons come to mind.<span id="more-332"></span></p>
<ul>
<li>Highlighting a specified term wherever it appears within a page</li>
<li>Linking to a dynamic page in a specific state</li>
</ul>
<p>The latter, which I have also seen called <em>deep linking</em>, seems particularly useful to me. You want to send someone a link to a video, but it&#8217;s one of several videos in a playlist on a page. You can send the URL and tell them, &#8220;It&#8217;s the 4th video from the top.&#8221;</p>
<p>Or you want to send someone the link to a page featuring one of the nearly-ubiquitous carousels, like the <a href="http://dsc.discovery.com/">Discovery Channel&#8217;s main page</a>. You want to send a link to the <a href="http://news.discovery.com/videos/space-nasa-plans-next-journey-to-moon.html">lunar rover feature</a>, but by default the page features a ridiculous-looking reality show called <a href="http://dsc.discovery.com/tv/american-chopper/">American Choppers</a>.</p>
<p>One way would be to supply the user with a link, something like:<br />
<code>http://dsc.discovery.com/?feature=4</code></p>
<p>(Sure, you could link to the feature&#8217;s destination page, but humor me here.)</p>
<p>Here&#8217;s some code to help turn <em>location.search</em> into something a little easier to use:<br />
<code>function parseQS() {<br />
	// Remove leading question mark ("?") and split into array of key/value pairs<br />
	var qsArray = location.search.slice(1).split("&amp;");<br />
	// Initialize object to store key/value pairs<br />
	var json = {};<br />
	// Loop through key/value pairs and separate into keys and values<br />
	for ( var i = 0; i &lt; qsArray.length; i++ ) {<br />
		var kv = qsArray[i].split("=");<br />
		var key = kv[0];<br />
		var val;<br />
		if ( kv.length == 1 ) val = key;<br />
		// A key may be present without a value, so set a placeholder value<br />
		else val = kv[1];<br />
		json[key] = val;<br />
	}<br />
	return json;<br />
}</code></p>
<p>Now you can check to see if <em>parseQS().feature</em> is defined, and if so, show the user the specified feature.</p>
<p>I&#8217;m sure someone has created a more elegant Javascript querystring parser. If you&#8217;ve found one&#8211;or if you wrote one&#8211;let me know in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://osric.com/chris/accidental-developer/2011/02/parsing-a-url-querystring-with-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Javascript Game (LetterLock)</title>
		<link>http://osric.com/chris/accidental-developer/2010/05/creating-a-javascript-game-wordlock/</link>
		<comments>http://osric.com/chris/accidental-developer/2010/05/creating-a-javascript-game-wordlock/#comments</comments>
		<pubDate>Tue, 25 May 2010 20:17:32 +0000</pubDate>
		<dc:creator>Chris Herdt</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[games]]></category>

		<guid isPermaLink="false">http://osric.com/chris/accidental-developer/?p=273</guid>
		<description><![CDATA[I recently created a simple word game (<a href="http://osric.com/letterlock/">LetterLock</a>) using Javascript, which presented certain challenges. The game displays 3 random letters to the player, who must then attempt to create a dictionary word in as few moves as possible by shifting the letters up or down in the alphabet.

There were several programming decisions or challenges that came up during the game's creation, which I discuss in the full post.]]></description>
			<content:encoded><![CDATA[<p><img src="http://osric.com/games/images/letterlock200x150.png" alt="LetterLock - A Word Game" style="border:solid 1px #999" /><br />
<a href="http://osric.com/letterlock/">osric.com/letterlock</a></p>
<p>I recently created a simple word game using Javascript, which presented certain challenges. The game displays 3 random letters to the player, who must then attempt to create a dictionary word in as few moves as possible by shifting the letters up or down in the alphabet.</p>
<p>There were several programming decisions or challenges that came up during the game&#8217;s creation, for which I was able to apply some of the things I learned in my recent computer science classes.</p>
<p><span id="more-273"></span></p>
<p>The first challenge was how to include the dictionary. The source list I used for 3-letter words (from a Scrabble dictionary) includes 1012 entries. Although I could have developed a server-side solution to check words via AJAX, I wanted the game to be as quick and responsive as possible, and 1012 3-letter words is not all that prohibitive. First, I created an array of all the words; however, that took a lot of extra bytes for all the quotes and commas. In fact, it doubled the space required. I looked at using a prefix scheme (&#8220;A&#8221; followed by all the two-letter sequences that begin with &#8220;A&#8221;) to save a few bytes, but the savings was not as great as I had initially anticipated. In the end, I just included the dictionary as a long, unbroken string: since we know that each word is 3 characters, it is easy to access any given word. </p>
<p>The next challenge was how to look up the user&#8217;s 3-letter sequence to see if the sequence is in our dictionary. The brute-force approach is to compare it to every word in the dictionary, which would take 1012 comparisons for a sequence that isn&#8217;t present. 1012 comparisons isn&#8217;t all that bad, but there are certainly more efficient ways, and I was thinking about the implications of expanding to a 4-letter or 5-letter game. Here are some of the look-up options I considered:</p>
<ul>
<li><strong>Binary search.</strong> Because we are dealing with an alphabetized dictionary, we can start in the middle of the dictionary and immediately eliminate half as possible matches, and then perform the same binary search recursively. Now we need only 10 comparisons for a sequence that isn&#8217;t present.</li>
<li><strong>Hash table.</strong> Although we would have to create the hash table at the beginning of the game, this only took 3 comparisons for a sequence that wasn&#8217;t present (based on empirical observation).</li>
<li><strong>Bucket array.</strong> I&#8217;m not sure what else to call it, but I created a large array (17,576) that could accommodate every conceivable combination of letters. A sequence not in the dictionary remains null, and a sequence in the dictionary gets assigned a 1. This method has larger memory requirements&#8211;not extraordinary for 3-letter sequences, but would grow quickly for longer sequences. Now we only need one comparison to determine is a sequence is a dictionary word.</li>
</ul>
<p>I picked the binary search for its simplicity.</p>
<p>The last major challenge was creating the &#8220;fewest moves&#8221; algorithm. The game currently tells the user the fewest number of moves it takes to convert the random sequence to a dictionary word. I struggled with this at first, until I realized that the problem is basically just a <a href="http://en.wikipedia.org/wiki/Breadth-first_search">Breadth-First Search</a> or shortest-path algorithm. I enqueue the initial sequence. For each possible one-move combination, I check it against the dictionary, and enqueue that sequence. (I enqueue an impossible dummy sequence&#8211;&#8221;###&#8221;&#8211;to indicate that we need to increment the fewest moves.)</p>
<p>One problem with this is that if it enqueues every one-move combination, it will enqueue many duplicates. Before I checked for duplicates, I found that the fewest moves algorithm often checked more than the 17,576 unique 3-letter sequences. For letter combinations where the nearest dictionary word was 8 or more moves away, Javascript would become unresponsive (or the browser would crash). Since the already-checked sequences were in no particular order, I used the hash table (instead of the binary search) to perform look-ups (although a brute force approach would probably have been sufficient).</p>
<p>Another problem with the fewest-moves algorithm is that my first approach was to use a recursive function. However, Javascript apparently does not always perform well with recursion; Firefox would throw &#8220;too much recursion&#8221; errors. I changed the function to use a while loop (continue processing while the queue is not empty), which solved that issue.</p>
<p>Although many of these optimizations were not strictly necessary and the brute-force approach would have worked suitably in many cases, I think the optimizations will help the game scale to handle 4-and-5-letter words (although the dictionaries may become too heavy for 5-letter words).</p>
]]></content:encoded>
			<wfw:commentRss>http://osric.com/chris/accidental-developer/2010/05/creating-a-javascript-game-wordlock/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hunt the Wumpus</title>
		<link>http://osric.com/chris/accidental-developer/2010/01/javascript-hunt-the-wumpus/</link>
		<comments>http://osric.com/chris/accidental-developer/2010/01/javascript-hunt-the-wumpus/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 00:09:10 +0000</pubDate>
		<dc:creator>Chris Herdt</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[games]]></category>
		<category><![CDATA[wumpus]]></category>

		<guid isPermaLink="false">http://osric.com/chris/accidental-developer/?p=263</guid>
		<description><![CDATA[I am taking a course in discrete mathematics this semester, and the professor suggested we take a look at a game called Hunt the Wumpus. Hunt the Wumpus was originally created in the 1970s, and unfortunately, most of the versions you can find on the web today are easier and less interesting that the original. [...]]]></description>
			<content:encoded><![CDATA[<p>I am taking a course in discrete mathematics this semester, and the professor suggested we take a look at a game called Hunt the Wumpus.</p>
<p>Hunt the Wumpus was originally created in the 1970s, and unfortunately, most of the versions you can find on the web today are easier and less interesting that the original. The original eschewed a square grid for the game board and instead used a &#8220;squashed&#8221; dodecahedron, where each game space was one of the vertices.</p>
<p>It is also noteworthy for introducing the <em>superbat</em>, a feature of other games (including Zork) that followed Hunt the Wumpus, and for the humorous feedback (e.g. &#8220;ZAP&#8211;Superbat Snatch! Elsewhereville for you!&#8221;) that many of my favorite games adopted.</p>
<p>At any rate, I decided to recreate a version of the easier and less interesting grid-based game in Javascript:<br />
<a href="http://osric.com/wumpus/">Hunt the Wumpus</a></p>
]]></content:encoded>
			<wfw:commentRss>http://osric.com/chris/accidental-developer/2010/01/javascript-hunt-the-wumpus/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Javascript insertAfter()</title>
		<link>http://osric.com/chris/accidental-developer/2009/08/javascript-insertafter/</link>
		<comments>http://osric.com/chris/accidental-developer/2009/08/javascript-insertafter/#comments</comments>
		<pubDate>Fri, 28 Aug 2009 23:12:47 +0000</pubDate>
		<dc:creator>Chris Herdt</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[insertAfter]]></category>
		<category><![CDATA[insertBefore]]></category>

		<guid isPermaLink="false">http://osric.com/chris/accidental-developer/?p=217</guid>
		<description><![CDATA[Although Javascript doesn't contain a DOM function for Node.insertAfter(), you can easily emulate it using Node.insertBefore -- and even call it via Node.insertAfter()]]></description>
			<content:encoded><![CDATA[<p>There is no <em>Node.insertAfter()</em> DOM function in Javascript, but it is clearly something that developers would like.</p>
<p>As the <a href="https://developer.mozilla.org/en/Gecko_DOM_Reference">Gecko DOM Reference</a> for <a href="https://developer.mozilla.org/En/DOM/Node.insertBefore">Node.insertBefore()</a> points out, this can easily be achieved with<br />
<code>parentDiv.insertBefore(nodeToInsert, nodeToInsertAfter.nextSibling);</code></p>
<p>If <em>nodeToInsertAfter</em> doesn&#8217;t have a next sibling, a NULL value will be returned and <em>nodeToInsert</em> will be inserted as the last child of <em>parentDiv</em>.</p>
<p>If you find it frustrating to type <em>insertBefore</em> when you want to <em>insertAfter</em>, that&#8217;s OK: you can add that function to the Object object:<br />
<code>Object.prototype.insertAfter = function (newNode) { this.parentNode.insertBefore(newNode, this.nextSibling); }</code></p>
<p>Now you can type:<br />
<code>nodeToInsertAfter.insertAfter(nodeToInsert)</code></p>
]]></content:encoded>
			<wfw:commentRss>http://osric.com/chris/accidental-developer/2009/08/javascript-insertafter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery is AWESOME</title>
		<link>http://osric.com/chris/accidental-developer/2009/01/jquery-is-awsome/</link>
		<comments>http://osric.com/chris/accidental-developer/2009/01/jquery-is-awsome/#comments</comments>
		<pubDate>Tue, 13 Jan 2009 22:53:12 +0000</pubDate>
		<dc:creator>giblfiz</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://osric.com/chris/accidental-developer/?p=135</guid>
		<description><![CDATA[I just took (and finished) a small project to add some ajax and javascript whiz-bang to a website. (actually it was the home page for a web development company you would think that they would keep that in house) and I decided to try out jQuery. It blew my socks off. I&#8217;m really really impressed [...]]]></description>
			<content:encoded><![CDATA[<p>I just took (and finished) a small project to add some ajax and javascript whiz-bang to a website. (actually it was the home page for a web development company you would think that they would keep that in house) and I decided to try out jQuery.</p>
<p>It blew my socks off. I&#8217;m really really impressed with jQuery, and I&#8217;m looking forward to using it a lot more. It took me an hour or two to really get a handle on how a few parts of it work, but man is it a powerhouse. If your website needs to sing and dance&#8230;. jQuery is the way!</p>
]]></content:encoded>
			<wfw:commentRss>http://osric.com/chris/accidental-developer/2009/01/jquery-is-awsome/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Javascript textarea counter</title>
		<link>http://osric.com/chris/accidental-developer/2008/11/javascript-textarea-counter/</link>
		<comments>http://osric.com/chris/accidental-developer/2008/11/javascript-textarea-counter/#comments</comments>
		<pubDate>Sat, 15 Nov 2008 19:33:26 +0000</pubDate>
		<dc:creator>Chris Herdt</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[User Interface]]></category>
		<category><![CDATA[delicious]]></category>
		<category><![CDATA[forms]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[textarea]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://osric.com/chris/accidental-developer/?p=109</guid>
		<description><![CDATA[I&#8217;ve been thinking more about the textarea counter issue that I mentioned in my previous post (&#8220;Users Paste Differently&#8220;). First of all, I noticed that some of the textarea counter scripts date back to at least 2000, so this has been a problem that developers have been looking to solve for 8 years. I checked [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been thinking more about the textarea counter issue that I mentioned in my previous post (&#8220;<a href="http://osric.com/chris/accidental-developer/?p=103">Users Paste Differently</a>&#8220;).</p>
<p>First of all, I noticed that some of the textarea counter scripts date back to at least 2000, so this has been a problem that developers have been looking to solve for 8 years. I checked the <a href="http://www.w3.org/html/wg/html5/">HTML 5 specification</a> and found that in HTML 5, the <a href="http://www.w3.org/html/wg/html5/#the-textarea-element">textarea element has a maxlength attribute</a>. Presumably user agents will build in the most elegant solution.</p>
<p>But what is the current most elegant solution?<span id="more-109"></span><br />
I checked a couple sites that I know use textarea counters well: <a href="http://delicious.com/">Delicious</a> and <a href="http://twitter.com/">Twitter</a>.</p>
<p><strong>Delicious</strong><br />
<div id="attachment_118" class="wp-caption alignnone" style="width: 420px"><a href="http://osric.com/chris/accidental-developer/wp-content/uploads/2008/11/delicious-textarea-counters.png"><img src="http://osric.com/chris/accidental-developer/wp-content/uploads/2008/11/delicious-textarea-counters.png" alt="Textarea counters on Delicious.com" title="delicious-textarea-counters" width="410" height="66" class="size-full wp-image-118" /></a><p class="wp-caption-text">Textarea counters on Delicious.com</p></div></p>
<p><strong>Twitter</strong><br />
<div id="attachment_120" class="wp-caption alignnone" style="width: 394px"><a href="http://osric.com/chris/accidental-developer/wp-content/uploads/2008/11/twitter-textarea-counters.png"><img src="http://osric.com/chris/accidental-developer/wp-content/uploads/2008/11/twitter-textarea-counters.png" alt="Textarea counters on Twitter.com" title="twitter-textarea-counters" width="384" height="80" class="size-full wp-image-120" /></a><p class="wp-caption-text">Textarea counters on Twitter.com</p></div></p>
<p>I like how prominent the character count is in Twitter, although perhaps too terse, but if Javascript is disabled it displays nothing at all. On the other hand, in Delicious displays &#8220;1000 characters max&#8221; if Javascript is off (instead of &#8220;1000 characters left&#8221;), which is still useful information. (I would avoid using the abbreviation <em>max</em>, though, and use <em>maximum</em> or <em>limit</em> instead, which might be better understood by those for whom English is a second language.)</p>
<p>I like Twitter&#8217;s &#8220;warning track&#8221; that lets the user know they need to keep it concise and wrap it up, although I find it confusing that they used bright red to denote both the &#8220;dangerously close to&#8221; as well as &#8220;over&#8221; the limit. The positive bright red numbers could easily be misconstrued as over the limit, since red is a color we frequently use to denote errors.</p>
<p>Twitter&#8217;s counter responds to onBlur and onChange, whereas the counter in Delicious is triggered by neither.</p>
<p>Both get one thing right that I think most other textarea counters get wrong: they don&#8217;t truncate the user&#8217;s text. Deleting something that the user has typed (or pasted) is definitely a bad idea for at least two reasons: the user may not realize the input was truncated and may submit incomplete info, and that the user, upon discovering that the input requires editing, may choose to cut text from someplace other than the end. Instead, both versions alert the user that they are over the limit and provide information on how many characters need to be cut to stay within the limit.</p>
<p>(As an aside, one thing I find curious is that both count an <em>Enter</em> keystroke as one character. I&#8217;ve run into issues with this before because a line break on a Windows-based system should insert 2 ASCII characters: a Carriage Return (CR) and a Line Feed (LF). *nix systems, including OS X, will insert a Line Feed (LF). However, I haven&#8217;t been able to reproduce this issue with recent testing. If it is still an issue, I imagine they handle this on the back-end by converting the CRLF to LF before inserting it into the database?)</p>
<p>In short, my recommendations are:</p>
<ul>
<li>Don&#8217;t truncate the user&#8217;s input; let the user correct it</li>
<li>Let the user know how far over the limit he or she is</li>
<li>Provide guidelines even if Javascript is disabled</li>
<li>onBlur and onChange should also trigger the counter, in case the user is pasting text</li>
<li>Keep the counter message simple and clear</li>
</ul>
<p>Another idea I had for a visual counter:<br />
<div id="attachment_116" class="wp-caption alignnone" style="width: 260px"><a href="http://osric.com/chris/accidental-developer/wp-content/uploads/2008/11/counter-bar.png"><img src="http://osric.com/chris/accidental-developer/wp-content/uploads/2008/11/counter-bar.png" alt="Counter - characters remaining" title="counter-bar" width="250" height="20" class="size-full wp-image-116" /></a><p class="wp-caption-text">Counter - characters remaining</p></div><br />
Aside from turning red once past the limit, though I&#8217;m not sure how it would visually convey to the user by how much the text exceeds the limits.</p>
<p><strong>How can a counter be implemented programatically?</strong><br />
I would like to set something up so that the appropriate event handlers are attached to textarea elements automatically. I found a <a href="http://jquery.com/">jQuery</a> plugin, <a href="http://plugins.jquery.com/project/CharLimit">Char Limit</a>, but in addition to not meeting the recommendations I made above, I don&#8217;t like how the developer has to specify the character limit in the Javascript (and apply the same limit for all textarea elements).</p>
<p>I think a clever, although imperfect, solution would be to have jQuery (or any Javascript of your choice) turn any static character limit messages (like the one that Delicious provides if Javascript is disabled) into dynamic character counters. For example, with the following code, the Javascript could find any elements with id attributes matching *_counter, take the numeric part as the limit, and build a character counter:<br />
<code>&lt;textarea name="example" id="example"&gt;&lt;/textarea&gt;<br />
&lt;div id="example_counter"&gt;300 characters maximum&lt;/div&gt;</code></p>
<p>It&#8217;s problematic for several reasons: another element on the page could have an id that matches *_counter, the non-Javascript message could  contain more than one numeric part, and the developers would have be consistent in naming the textareas and accompanying divs. But I think it is in many ways an improvement over the inline Javascript I&#8217;ve seen in some oft-used solutions.</p>
]]></content:encoded>
			<wfw:commentRss>http://osric.com/chris/accidental-developer/2008/11/javascript-textarea-counter/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>

