January 2011
1 post
2 tags
Syntactic sugar: RexExp.exec with callbacks
The RegExp.exec method returns an array of results when there’s a match or null when there’s none. I often find myself coding the same check over and over again: var result = /(.+)=(.+)/.exec("name=value"); if (result) { console.log(result[1] + " = " + result[2]); } It would make life easier if exec accepted a callback method as the second argument (and then a scope as the...
Jan 13th
2 notes
December 2010
1 post
3 tags
Ruby on Rails on Windows with Pain
I decided to give RoR another try (my first attempt ended with my attention deficit overcoming my desire to learn). Things didn’t work “out of the box” as I hoped. First, I downloaded and installed Ruby 1.8.7. I was surprised to see that the installer didn’t add the Ruby bin directory to the PATH environment variable, so I had to do it myself. Next, I downloaded and...
Dec 13th
April 2010
3 posts
1 tag
Parsing ISO 8601 UTC dates
Here’s a concise implementation for parsing UTC date strings in ISO 8601 format into Date objects in the local time zone. function parseIsoDate(s) { var tokens = /(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)\.(\d+)/ .exec(s).slice(1); tokens[1] -= 1; return new Date(Date.UTC.apply(null, tokens)); } The new Date(Date.UTC.apply(null, tokens)) trick allows the direct usage...
Apr 26th
1 note
1 tag
Catch those anchors with hash && (hash = hash)
The following cryptic bit of JavaScript is actual code that I’ve used as a workaround to a very specific issue. The issue I was having was with anchor links not pointing to the right place on the page. It was a single page with the top navigation pointing to sections within the page, but the issue was that the position of the section anchors were shifting due to progressive enhancement...
Apr 26th
8 notes
4 tags
Enabling Disqus comments on a custom Tumblr theme...
The official “Universal Code” that is suggested by Disqus for embedding the comment widget injects a new <script> element into the page and looks a bit messy. The embedding can be achieved with cleaner code using jQuery’s JSONP support. Here’s the code suggested by Disqus: (function() { var dsq = document.createElement('script'); dsq.type =...
Apr 8th
28 notes
July 2009
2 posts
1 tag
When semicolons are NOT optional in JavaScript
An inadvertently skipped semicolon recently left me scratching my head over a runtime error. The code looked something like this: // Add a new function to an existing namespace some.namespace.doSomething = function () { // ... } // Define more functions inside a closure to hide some helpers (function () { // ... })(); This was giving me a “yada yada yada… is not a...
Jul 23rd
1 tag
Parsing query string parameters into a collection
Here’s a utility function for parsing query parameters: function getQueryParams(qs) { qs = qs.split("+").join(" "); var params = {}; var tokens, re = /[?&]?([^=]+)=([^&]*)/g; while (tokens = re.exec(qs)) { params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]); } return params; } //var query =...
Jul 8th
June 2009
3 posts
2 tags
Turkish letter escape bookmarklet for dotSUB
I’ve created a bookmarklet to temporarily solve a very specific problem at hand: I’m translating a TED video into Turkish, but I don’t currently have a Turkish keyboard hooked up to my computer (it’s in a box somewhere in the basement). TED uses dotSUB for video translation. Peeking at the HTML source of dotSUB’s translation interface, I saw that they were using script.aculo.us (therefore...
Jun 25th
3 tags
Creating Todoist items with voice using reQall
Todoist is an awesome, minimalistic task management service. The voice-to-web service reQall, which is a free alternative to Jott, also does a fairly good job at task management. However, I wanted to stick to Todoist and bring voice input capabilities to it. I used reQall’s e-mail forwarding along with Todoist’s HTTP API and my awesome hosting provider’s powerful features to...
Jun 3rd
3 tags
A quick and dirty markup generator in JavaScript
Here’s a quick and dirty XML/HTML generator. Without even bothering to write a new class, I simply extend an Array instance with a few helpers that can be chained. The generator: function xmlEscape(s) { return s.replace(/[<>&"]/g, function (c) { return "&" + { "<": "lt", ">": "gt", "&": "amp", "\"": "quot" }[c] + ";"; ...
Jun 3rd
36 notes
February 2009
2 posts
1 tag
JavaScript function definition inside a with()...
I came across yet another browser discrepancy with a rather obscure scenario: Accessing an object property from a function declaration within a with block for that object. var obj = { a: 1 }; with (obj) { function foo() { return typeof a; } } alert(foo()); // alerts "number" on Firefox, "undefined" on others This exposes the object properties to the function scope only on...
Feb 14th
1 tag
Browser discrepancies when calling toString() on a...
I had been working on parsing the source of JavaScript function instances when I realized that Function.prototype.toString() may return parts of the original comments in the source code, depending on the browser. I’ve done a quick test to capture the different behaviours of popular browsers. Here’s my test script: function/*post-keyword*/fn/*post-name*/()/*post-parens*/{ ...
Feb 6th
16 notes
December 2008
1 post
2 tags
browsersize.com updates
Last night I touched some code that hadn’t been touched for years. I refactored the plug-in detection code at whatsmy.browsersize.com and added detection for the Microsoft Silverlight plug-in. I also added bookmarklet support for setmy.browsersize.com and brought back to life a feature that had been broken long ago: specifying arbitrary URLs in the form http://setmy.browsersize.com/1024x768 to set...
Dec 22nd
October 2008
4 posts
1 tag
Automatic Table of Contents Generation
Here’s a JavaScript snippet for automatically generating a table of contents based on headings in a document. It will traverse all <h1>, <h2>, <h3>, etc. elements, add anchors (<a>) to them and generate nested unordered lists (<ul>, <li>) with links to the now anchored headings. The nesting honors the hierarchy of the headings. For example, for a document...
Oct 20th
2 tags
Timing Code Accurately
The most common approach to time a function or a segment of code is to repeat it many times in a loop, measure the time the entire loop takes and then divide that number with the number of iterations. However, this approach disregards the overhead of the loop. This can be remedied with a slight modification to the loop. Illustrating the problem with JavaScript (although this method applies to all...
Oct 20th
1 tag
Rounding to a Certain Significant Figures in...
A function for rounding a decimal number to a given number of significant figures (or digits): function sigFigs(n, sig) { var mult = Math.pow(10, sig - Math.floor(Math.log(n) / Math.LN10) - 1); return Math.round(n * mult) / mult; } alert(sigFigs(1234567, 3)); // Gives 1230000 alert(sigFigs(0.06805, 3)); // Gives 0.0681 alert(sigFigs(5, 3)); // Gives 5
Oct 15th
1 note
1 tag
Repeating or Padding Strings in JavaScript
Here’s a nice trick for repeating a string a given number of times. Let’s say you want to create a string with the characters “ABC” repeated 5 times. The most straightforward approach that you could take is to set up a for loop to append “ABC” to a string 5 times: var s = ""; for (var i = 0; i < 5; i++) { s += "ABC"; } alert(s); // Gives you "ABCABCABCABCABC" You can avoid repeated...
Oct 13th
25 notes
September 2008
1 post
1 tag
JavaScript Date Formatting - An Unorthodox Way
Most date formatting implementations use format strings where format specifiers like “mm”, “mmm”, “HH”, etc. are used for selecting different components of a date. Here’s a different approach that allows you to use more human-readable format specifiers (while being rather verbose). Date.prototype.format = function (fmt) { var date = this; return...
Sep 2nd
1 note
August 2008
1 post
3 tags
Subpixel Scrolltext in JavaScript
After having it in my to-do list (the “what if?” section) for a long time, I’ve finally managed to spend some time on a JavaScript implementation of a very tiny scrolltext: using a 5x5 font with subpixel rendering (aka ClearType). Knowing what subpixel-rendered static letters look like on an LCD, I wanted to see the effect of scrolling them, 1/3 pixel at a time. Note: you need an...
Aug 6th
26 notes
June 2008
2 posts
2 tags
Adobe (Photoshop) Color Book Specification in HTML...
I finally sat down and created a friendlier, HTML version of the Unofficial Adobe Color Book Specification by updating the original post. This obsoletes the 80-column plain-text version that I wrote up in 2003.
Jun 18th
21 notes
1 tag
A Boulder Dash Clone in Only 20 Lines of...
This was my very first entry for the quasi-regular, friendly 20-line JavaScript competition over at OZONE Asylum, for the month of January 2008. My entry titled “Rockford the Invincible” got the second place among some very impressive entries (I was actually a bit shocked that I got the second place). In-game screenshot. Click to play! The winning entries were: Candle Flame by...
Jun 18th
1 note
September 2007
1 post
1 tag
Generating "Unified Diff" Files with ClearCase
In my company, we recently migrated from CVS to ClearCase. We were a bit thrown off by the fact that ClearCase doesn’t readily provide diff files that span multiple files. We have all been used to reviewing CVS diff files which do so. People here had to come up with their own scripts to remedy this issue. Here’s what I’ve been using so far: cleartool lsco -cvi -r -s | xargs -n1...
Sep 7th
February 2007
1 post
1 tag
Verifying the Integrity of an Easynews Download...
Suppose you had to download a huge file from Easynews as a single piece because a multiple archive version wasn’t available. If the poster didn’t supply a checksum file (MD5, SFV) or Parchive files, you can’t readily tell if the file you’ve downloaded is intact. Here’s a method I came up with for verifying the integrity of an ISO image file that didn’t come with...
Feb 7th
December 2006
1 post
1 tag
Default Constructor vs. Empty Constructor
While coding away new classes for your C++ project, do you have the habit of just dropping in a constructor definition, just in case you may in the future need to do some initialization at construction? A while ago, I had wondered if there would be any difference at compile time between having an empty constructor and having no constructor at all (and thus using the default constructor). I did a...
Dec 17th
3 notes
November 2006
2 posts
1 tag
Rendering N-sided Polygons with DHTML
With this technique, convex polygons with any number of sides can be rendered, with a solid color or a background image as the fill. Click here or the image below to launch the demo. You can probably figure it out on your own by playing with the checkboxes at the lower left corner of the pop-up, but read on to find out how it all works. The demo renders only regular polygons, but any convex,...
Nov 28th
1 tag
browsersize.com
A simple website that I had put together a while ago, that harbors two simple tools that web designers may find useful. The main site shows you decently current statistics on different screen resolutions that web surfers have nowadays. You could use that as a starting point for deciding on the dimensions for a non-fluid website layout. setmy.browsersize.com allows you to set your browser size...
Nov 19th
August 2006
2 posts
1 tag
CSS Sprites (using fewer images)
(This post was originally published in 2006. I’ve just moved it from my old Wordpress blog to Tumblr.) Image rollovers are usually composed of two individual images; one for the default state and one for when the mouse is hovered over the image or link. However, it bears some advantages to use a single image by taking advantage of CSS background image offsets. I’ll start by describing...
Aug 27th
1 note
1 tag
Opt for Pre-incrementing Iterators
There’s a slight performance advantage in using pre-increment operators versus post-increment operators. In setting up loops that use iterators, you should opt to use pre-increments: for (list<string>::const_iterator it = tokens.begin(); it != tokens.end(); ++it) { // Don't use it++ ... } The reason comes to light when you think about how both operators would typically...
Aug 26th
July 2006
4 posts
2 tags
PHP-style Serialization of JavaScript Objects
Heavily-scripted data entry forms that expand on-the-fly as the user enters new data make life easier for the user. However, it can be hell for a developer to devise a method for the representation and submission of data with arbitrary length and depth. A logical thing to do seems to be to take an object-oriented approach to represent all client-side data as one or multiple JavaScript objects....
Jul 31st
2 notes
1 tag
Don't Hand-count Characters
A common mistake that most programmers do is to hard-code hand-counted lengths of string literals. For example: if (!strncmp(str, "MAGIC_PREFIX_", 13)) { ... } Even if the string literal "MAGIC_PREFIX_" is not due to change in a life time, it makes the code more prone to human error and harder to read when the length of the string is hand-counted and hard-coded as a separate entity (13 in...
Jul 15th
28 notes
Spelling "Quake" With The Quake Logo
I created this GIF animation back in 1997, when I used to play Quake 25 hours a day. I recall the tedious process of manual tweening to create the individual frames (by calculating the angle and position differences and dividing them by the number of frames) using Freehand. I would probably use Flash if I were to do it today…
Jul 11th
1 tag
Finding Out Class Names of JavaScript Objects
JavaScript lacks a built-in function for getting the exact class names of object instances. The typeof operator just returns “object” for instances of both Object and Array, as well as user-defined classes. The following example illustrates this: function MyClassA() { } var obj = new Object(); var arr = new Array(); var myobj = new MyClassA(); document.write(typeof(obj) +...
Jul 11th
25 notes