I just read an article by Sergi Mansilla, Extending JavaScript with inline unit tests, where he implements a pretty neat inline testing syntax using sweet.js, which allows writing code like this:

function square(n) {
    return n * n;
} where {
    square(2) is 4
    square(3) is 5
}

Obviously this isn’t really valid javascript – sweet.js is a javascript preprocessor which allows you to write macros in your code which are then rewritten as valid javascript. I liked the idea of being able to write inline tests, but wanted to be able to achieve it in pure js only, so I wrote inline, a little snippet of javascript (~20 lines) which implements this functionality. The syntax is a bit different, but I think it’s still pretty readable:

var square = function(n) {
    return n * n;
}.where(2).shouldEqual(4)
 .where(3) shouldEqual(5);

The way it works is simple. Inline adds a ‘where’ function to the prototype of Function, which returns an Inline object which records the function and the arguments and also has assertion functions (currently only shouldEqual() but it’s pretty obvious how more could be added).

Notes:

– To use it with functions written like function fn() { ... } you must wrap the function declaration in brackets to avoid a syntax error: (function fn() { ... }).where(...).shouldEqual(...);
– Make sure not to call where() without following it with an assertion function as it’ll replace the original function! (ie. for the code: var fn = function() { ... }.where(...); fn will be an Inline object and not the specified function
– You can chain multiple where().shouldEqual()s on a function to run multiple tests

Inline.js is only a quick experiment, and I wouldn’t really recommend mixing tests and code, but I do think there’s something interesting about inline testing, and could see it being used for teaching or demonstration purposes. Sergi’s code definitely offers an advantage that as it’s written as a macro you can write the tests inline but strip them out for production.

Occasionally when using javascript you’ll find that you want to intercept a function call, usually to run some code before invoking functions belonging to a third-party codebase. Essentially, this is achieved by saving a reference to the original function and then replacing it with a new function which, at the end, calls the original. Something like:

(function () {
    var originalFunction = Object.getPrototypeOf(someObject).someFunction;
    Object.getPrototypeOf(someObject).someFunction = function () {
        // intercept code here
        originalFunction.call(this);
    }
})();

Likewise, interception is possible if a property has a getter or a setter:

(function() {
    var propDesc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(someObject), "someProperty"),
        originalGetter = propDesc.get,
        originalSetter = propDesc.set;

    propDesc.set = function(val) {
        // getter intercept code here
        return originalSetter.call(this, val);
    };

    propDesc.get = function() {
        // setter intercept code here
        return originalGetter.call(this);
    };

    Object.defineProperty(Object.getPrototypeOf(someObject), "someProperty", propDesc);
})();

As you can see this is basically the same; the only real difference is that you need to use Object.getOwnPropertyDescriptor / Object.defineProperty rather than being able to set it directly using regular assignment. This is because var getter = someObject.someProperty will return the result of the getter function, and someObject.someProperty = "something" will invoke the setter function.

In my last post, looking at “typed” function overloading, I mentioned that I was working on a new project aiming to simplify animations in paper.js, and I’m pleased to say that today I was able to get the project to what I would consider a useable form. I’m also pleased to mention that I completely changed the approach that I was taking with the api, with the effect that it is simpler to use, and has also allowed me to do away with all the function overloading stuff! (Don’t worry, I’m not a hypocrite; I said at the beginning of the post that it was something I disagreed with in Javascript!).

Anyway, check it out over on GitHub, I’d love to hear any opinions or feedback.

 

Usage

paper.animate.js has been designed to integrate easily with existing paper.js code. Simply prefix a transform command withanimate(duration, updater, chain) / animate(duration, chain). This returns a proxy object, PaperAnimate.AnimationProxy, with overloads for all the transform methods found on paper.Item. To run the animations, call the update() method of the proxy from the paper.js view onFrame event handler. It’s easiest to use the PaperAnimate.Updater to make this easier and to automatically clear up any finished animations (more info below).

var shape = ...
var updater = new PaperAnimate.Updater();

function onFrame(e) { // paper.js onFrame event
    updater.update(e);
}

// Translate
shape.translate(new Point(100, 50); // paper.js
shape.animate(1, updater).translate(new Point(100, 50)); // paper.animate.js

// Rotate
shape.rotate(90); // paper.js
shape.animate(4, updater).rotate(90); // paper.animate.js

// Chaining
shape.animate(2, updater, true) // 2 secs, chained = true
     .scale(2)
     .shear(0.1, 0.3);

// Animate Shape (paper.animate.js only)
shape.animate(2, updater).replaceShape(differentShape);

// Not using PaperAnimate.Updater
var anim = shape.animate(1).rotate(45);
function onFrame(e) {
    anim.update(e);
}

Params

animate(duration[, updater, chain]) or animate(duration[, chain])

  • duration (Number): Specifies, in seconds, the duration of the animation. If unspecified then defaults to 1 second
  • updater (PaperAnimate.Updater): Makes it simple to work with and update many animations
  • chain (Boolean): Allows chaining commands by returning PaperAnimate.AnimationProxy object rather than originalpaper.Item. Defaults false, in keeping with paper.js api (returning item)

Supported Transformations

paper.animate.js supports all the transformations currently implemented by paper.js:

  • scale(scale[, center])
  • scale(hor, ver[, center])
  • translate(delta)
  • rotate(angle[, center])
  • shear(point[, center])
  • shear(hor, ver[, center])
  • transform(matrix, flags)
  • fitBounds(rectangle[, fill])

PaperAnimate.Updater

The updater is simply an easy way to manage animations. Rather than having to maintain a list of all the animation proxies returned every time animate() is called, simply pass in the reference to the updater and then call update() only on that. Additionally, the updater will remove animations when they have completed

Before I start, I want to go on the record to say that I do not agree with using function overloads in javascript. Javascript doesn’t really support function overloading, and overloaded functions (at least in my experience) seem to lead to unclear code; the better solution is to pass in an object and determine behaviour from that.

That said, the other day I did have to implement function overloading, for a new project I started which aims to simplify basic animations when using paper.js. I wanted my solution to integrate nicely with existing code written for paper, so I decided to use a proxy object which intercepts the tranform function calls on an item and animates it, and for this reason my proxy object needed to implement matching method signatures.

Typically when people use function overloading in javascript, they are dealing with different numbers of arguments, but paper.js complicates things slightly as there can be ambiguities in function calls which can be resolved not by counting the number of arguments but by looking at the “types” of the arguments.

  • scale(Number:scale [, Point:center])
  • scale(Number:hor, Number:ver[, Point:center])

When calling something.scale(a,b), we cannot know which function to use without further inspecting b. I briefly googled function overloading in javascript and came up with a few solutions that dealt with overloads which had different numbers of overloads, but nothing that dealt with ambiguities such as the one above, and so I came up with this method:

function selectOverload(that, args, overloads) {
	var types = {
		Number: function(val) { return !isNaN(parseFloat(val)) && isFinite(val); },
		Point: function(val) { return val.x !== undefined && val.y !== undefined; }
	};
	for (var o = 0; o < overloads.length; o++) {
		var overload = overloads[o],
			matches = true;
		if (args.length > overloads[o].params.length) continue;
		for (var a = 0; a < args.length; a++) {
			if (!types[overload.params[a]](args[a])) {
				matches = false;
				break;
			};
		}
		if (matches) { return overload.fn.apply(that, args); }
	}
}

And it gets used like this:

AnimationProxy.prototype.scale = function() {
	selectOverload(
		this, arguments,
		[{
			params: ["Number","Point"],
			fn: function(scale, center) {
				// code for this overload here
			}
		},
		{
			params: ["Number","Number","Point"],
			fn: function(hor, ver, center) {
				// code for this overload here
			}
		}]
	);
	return this;
}

Although not perfect, I’m pretty pleased with this code. I think the intention is pretty clear, and like that the arguments are correctly named. It doesn’t actually check the type of the argument; the “type definitions” are actually just boolean functions which return true or false if an argument meets their “type criteria”, and so this can easily be used on a whole variety of scenarios.

Also, I made the decision to pass a string value in for the type and have the type defs in the selectOverload function, but that’s just because it suited the situation I was working with, but there’s no reason you can’t adapt the code to use the criteria function itself. In my situation I didn’t feel it would be as readable, but if you have a lot of different types then it may work out more efficient.

I’ve just read a post by Alex Maccaw, 5 APIs that will transform the Web in 2013, and think that while the APIs described are all pretty cool, my personal favourite has not been mentioned: web intents. The specification is currently in the ‘working draft’ stage and so chances are it still won’t be finalised next year, which probably means browser coverage will be lacking (particularly in the IE camp), but Firefox and Chrome are already picking it up and so at least that’s something!

Web intents is inspired by Android’s Intents framework, and is a framework that allows for web-based inter-app communication and service discovery. The example that is typically bounded about when talking about web intents is photo editing. Say, for example, I build a web application that allows users to upload photos, and I want to enable them to manipulate the photo on my site. I could spend a lot of time trying to develop my own editing system, but the likelihood is that it will be buggy, or lacking in features, because this is simply not my area of expertise. Using the web intents framework, however, I could simply integrate with a third-party photo editing application which is hopefully less buggy and more feature packed than anything I could code myself. Furthermore, since all my application is doing is declaring that it needs a certain type of service, rather than specifying one service specifically, the user is able to select whichever photo editing application suits him best.

This example works well, given the difficulties that can arise for the average developer dealing with advanced image manipulation techniques, but the web intents system specification is open enough that anyone can register a service for any intent that they wish. Take a look at the demos on the webintents.org for some different sample applications, as well as to get an idea of how this system will work. I think it’s really exciting, and will make it easier for us all to develop richer web applications going forward.

I­­­ read an article the other day by Nicholas C. Zakas titled ‘The Problem with Native Javascript APIs’, and found it thoroughly depressing.

“Browsers are written by humans just like web pages are written by humans. All humans have one thing in common: They make mistakes. Browsers have bugs just like web pages have bugs just like any other software has bugs. The native APIs you are relying on likely have bugs”

I’m not totally naïve, of course I understand that it is rare that a code base will be bug-free, but I find it a real shame that someone like Nicholas, a respected authority for javascript who strongly advocates best-practise methodologies, would be so dismissive of native code within the browser. These APIs are in there to help us, as developers, and as a result of being coded natively are typically considerably faster than equivalent javascript would be.

So why does he have this attitude? It’s not totally unfounded, and he does present one example of a native API which had different bugs in the implementation Firefox and WebKit, which we know from history is just one of many browser bugs.

His solution to avoiding native APIs, then? Write it yourself, of course!

There are two ways that you can rewrite a native API: either by using a façade, such as jQuery, which provides an alternate interface to existing code; or a polyfill, such as Modernizer, which attempts to implement native API functionality which may be missing. Nicholas advocates facades, as polyfills “represent yet another implementation of the same functionality”. I don’t totally understand this, as it seems that facades do the exact same thing, just with a different interface, but that’s neither here nor there, as it seems to me that both have their place within a code base.

The final solution presented recreates the functionality of the native API, but without using it directly. This to me stinks of reinventing the wheel. Furthermore, I think it’s downright arrogant to assume that your code is somehow impervious to bugs. Imagine if we all had this viewpoint, and used no third party code at all. The reason we use third party libraries and frameworks is because they allow us to concentrate on the code that is relevant to us. If you know there is a bug in some code, don’t waste your time by duplicating the functionality and adding to your own codebase, let the developers know: file bug reports, email them, tweet. Get it fixed and help everybody.*

*Interestingly enough, the author has even noted that the bugs mentioned in the case study have both been sorted! Think about how many of us developers are using browsers: it’s far more likely that a bug in Chrome will be noticed, for example, than a bug in your code.

I recently needed to implement a facility on a web page to download a file that was defined by a reasonably number parameters, stored on the page as JSON. The first thing I tried was to ajax the request, but that failed as the file never downloaded – I retrieved the data, but it essentially just got ‘swallowed’.

Next I tried using JSON.stringify to populate a hidden field with the JSON value and then submit that. The action that I was posting to was defined with the parameters separately, rather than just string, and I wasn’t able to edit it: I had hoped that ASP.NET MVC 3 might have been able to decode the string but it couldn’t, so that approach failed too. (If I’d been able to amend the action then I could have obviously deserialized the string, but I wasn’t allowed [boo!]).

So in the end I wrote a quick method that would populate my form with hidden fields representing the properties of my JSON model, and that ended up working nicely. Really simple, and would obviously have to be tweaked to handle nested JSON, but it got the job done:

function downloadCurrentReport() {
    var newHiddenInputs = "", i;
    for (i = 0; i < model.length; i++) {
        var nameBase = "model[" + i + "].";
        for (var prop in model[i]) {
            newHiddenInputs +=
                    hiddenField(nameBase + prop, model[i][prop]);
        }
    }
    $("#downloadForm").html(newHiddenInputs);
    $("#downloadForm").submit();
}
    
function hiddenField(name, value) {
    return "<input type='hidden' name='" + name + "' value='" + value + "'/>";
}

I’ve been reading recently about the new HTML5 specs, and one thing that really interested me was the Web SQL Database spec that would allow javascript developers to access a client-side database from within the browser, in order to save and manipulate data locally on the users machine. This would enable interactive javascript web applications to run offline, in a similar manner to how Google Gears works (think storing emails for access at a time when no internet connection is available). The WebDB API defined a relational database that could be queried using SQL. Unfortunately, as of 18th November 2010, this spec was canned, because it suffered from one fatal flaw: it used SQL. The problem was that in order to define a cross-browser compatible API, all vendors would need to implement the same database (or more specifically, the same form of SQL). The spec pushed SQLLite as the database implementation, which both Chrome and Safari agreed with, but since Microsoft wanted to use a version of SQL Server in IE, work on the specification was ceased.

The replacement for the WebDB API was the Indexed Database API. Unlike webDB, this was a NoSQL database implementation, which used object stores rather than the typical relational database implementation. The main problem with the IndexedDB API, it seemed to me, however, was that the syntax was just awful compared to it’s SQL alternative. The code samples found at Mozilla Hacks show this pretty well (although it seems that the point of the post is supposed to sing the advantages of IndexedDB over WebDB!). This example, taken from that post, shows the different code samples required to load and display all the kids in a database that have bought candy:

WebDB

var db = window.openDatabase("CandyDB", "1",
                             "My candy store database",
                             1024);
db.readTransaction(function(tx) {
  tx.executeSql("SELECT name, COUNT(candySales.kidId) " +
                "FROM kids " +
                "LEFT JOIN candySales " +
                "ON kids.id = candySales.kidId " +
                "GROUP BY kids.id;",
                function(tx, results) {
    var display = document.getElementById("purchaseList");
    var rows = results.rows;
    for (var index = 0; index &lt; rows.length; index++) {
      var item = rows.item(index);
      display.textContent += ", " + item.name + "bought " +
                             item.count + "pieces";
    }
  });
});

IndexedDB

candyEaters = [];
function displayCandyEaters(event) {
  var display = document.getElementById("purchaseList");
  for (var i in candyEaters) {
    display.textContent += ", " + candyEaters[i].name + "bought " +
                           candyEaters[i].count + "pieces";
  }
};

var request = window.indexedDB.open("CandyDB",
                                    "My candy store database");
request.onsuccess = function(event) {
  var db = event.result;
  var transaction = db.transaction(["kids", "candySales"]);
  transaction.oncomplete = displayCandyEaters;

  var kidCursor;
  var saleCursor;
  var salesLoaded = false;
  var count;

  var kidsStore = transaction.objectStore("kids");
  kidsStore.openCursor().onsuccess = function(event) {
    kidCursor = event.result;
    count = 0;
    attemptWalk();
  }
  var salesStore = transaction.objectStore("candySales");
  var kidIndex = salesStore.index("kidId");
  kidIndex.openObjectCursor().onsuccess = function(event) {
    saleCursor = event.result;
    salesLoaded = true;
    attemptWalk();
  }
  function attemptWalk() {
    if (!kidCursor || !salesLoaded)
      return;

    if (saleCursor &amp;&amp; kidCursor.value.id == saleCursor.kidId) {
      count++;
      saleCursor.continue();
    }
    else {
      candyEaters.push({ name: kidCursor.value.name, count: count });
      kidCursor.continue();
    }
  }
}

Pretty monstrous right? Which is a real shame, since IndexedDB has the potential to be a really, really useful in a client side developers toolkit.

In my last post, Javascripts Number Type, I stated that ‘everything in javascript extends Object, which means that it can have functions’, and by this I meant that it doesn’t have primitives as we are used to in other languages, since they have methods against them. However, I’ve recently learned that that was incorrect, although there are tricks in the language to make it look that way.

Primitives and Wrapper Objects

There are five primitives in javascript: number, string, boolean, null and undefined. Of these, number, string and boolean have wrapper objects, which encapsulate the primitive and augment it with a number of useful methods.

Primitive Wrapper
var n = 10;
console.log(typeof n); // number
var n = new Number(10);
console.log(typeof n); // Object
var s = “string”;
console.log(typeof s); // string
var s = new String(“string”);
console.log(typeof s); // Object
var b = true;
console.log(typeof b); // boolean
var b = new Boolean(true);
console.log(typeof b); // Object

This means that we can create a string and use one of its native methods, toUpperCase(), to convert it to uppercase:

var s = new String("shout!");
console.log(s.toUpperCase()); // SHOUT!

Using Wrapper Methods on Primitives

The functions associated with number, string and Boolean aren’t news to most of us, we tend to use them all the time. However, how often do we ever declare a number using new Number() or a boolean with new Boolean()?
This is where javascript is sneaky. When you attempt to use a function on a primitive it is converted to a wrapper object, the function is invoked, and then it is converted back to a primitive. This means that you can do things such as:

console.log("WHISPER".toLowerCase()); // whisper
console.log();

One Final Gotcha…

We’ve seen that we can invoke the wrapper functions on a primitive, so why would you ever want to use the new ___() notation? Well there’s one case where explicitly declaring that you need an object is important, and that’s when you want to augment your number by adding new functions or properties to it. The problem is, javascript will happily let you try and add new properties without reporting any errors, but these will not actually be added.

var prim = true;
prim.sayYesOrNo = function () {
    if (this) { return "yes"; } else { return "no"; }
};
console.log(prim.sayYesOrNo()); // undefined

var wrap = new Boolean(true);
wrap.sayYesOrNo = function () {
    if (this) { return "yes"; } else { return "no"; }
};
console.log(wrap.sayYesOrNo()); // yes

Virtually all programming languages use a variety of data types to represent numbers; for instance bytes, ints, floats and doubles. Back when memory and processing power was expensive, we needed to be careful to limit our usages. It is quicker to operate on smaller number types, such as bytes and chars, than on floats and doubles. Likewise, the larger number types take up more memory. The limitiation of using different number types is that we need to be careful to use suitable number types to avoid overflow errors.

Javascript was always designed to be an easy language to use. For that reason, it has only one number type: Number. Number is a 64-bit floating point (or as we usually call it, a double), which allows developers to forget about overflow issues. Additionally, now memory is cheap and we have an abundance of processing power, we don’t have to worry so much about the effects of using larger data types. Perhaps in 1995 when javascript was first introduced this was not so true as it is today, but with hindsight it was clearly a good decision.

Number, like everything else in javascript, extends Object, which means that it can have functions. There are five functions that are included natively: toExponential(), toFixed(), toPrecision(), toString() and valueOf(); but since Number is an object, we are also able to extend it by adding new functions to its prototype. [Although on the whole this practise is not advised unless you are building a general use utility framework such as underscore.js]

There is one gotcha with the javascript, and that is NaN. NaN, or Number.NaN, is the result of an illegal math operation, such as division by zero or the square root of a negative number. Oddly enough however, NaN !== NaN. This means that the following statements are all true:

3/0 !== 3/0
Math.Sqrt(-4) !== Math.Sqrt(-4)
Math.abs("text") !== Math.abs("text")

This seems a little odd until you consider that each of the expressions returns the same result, so the inequality makes more sense when if we muddle up the examples:

3/0 !== Math.abs("text")
Math.Sqrt(-4) !== Math.abs("text")
Math.Sqrt(-4) !==  3/0

Since javascript doesn’t know what either side of the condition really is – as it evaluates all as NaN – it cannot accurately conclude whether or not they are really equal. People are critical of this, but to me it really seems to be the only thing that makes sense.