Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

8 October 2013

Javascript dictionary using objects as keys

One thing that bugs me about Javascript is the inability to have a dictionary with objects as keys. Objects are dictionaries, but essentially toString gets called on anything you use as a key, which isn't always very helpful.

Typical solutions are to call stringify on each object, which is relatively slow and doesn't guarantee reference equality, or to have a custom hashing function, which feels like unnecessary effort. (The jshashtable library generally looks useful, but unless you provide the hashing function the performance drops considerably.

So my requirements are:
  • A dictionary that takes objects as keys
  • And will only resolve values using the same instance of the object (not just some string match)
  • Is fast
  • Without any custom hashing functions
It took a little while to realize that since the key is an object, the value can be stored directly on it, so long as we know which property the value got stored in. Job done. But because my poor head wants to deal with something like a traditional dictionary API, it can be achieved something like this:

function Dict() {
    Dict.id = (Dict.id || 0) + 1;
    this._prop = '_dict' + Dict.id;
}
Dict.prototype = {
    add: function(key, value) {
        key[this._prop] = value;
    },
    contains: function(key) {
        return typeof key[this._prop] != 'undefined';
    },
    get: function(key) {
        return key[this._prop];
    },
    remove: function(key) {
        delete key[this._prop];
    }
};

// Sample usage
var a = {};
var b = {};
var c = {};

var dict1 = new Dict();
dict1.add(a, 123);
dict1.add(b, 456);
var dict2 = new Dict();
dict2.add(c, 789);

alert(dict1.get(a));         // 123
alert(dict1.contains(c));    // false
alert(dict2.contains(c));    // true
dict2.remove(c);
alert(dict2.contains(c));    // false

OK, it needs a whole lot more work, but you get the idea. We keep track of a global ID so that a key can be used in more than one dictionary simultaneously. If we want to have some way to enumerate over the values or get a count, then we'd also need to store keys/values in the Dictionary itself. I'd probably go with a doubly-linked-list, otherwise add/removes would get slow.

The main disadvantage is that we are adding an extra property to the key objects, which may be undesirable in some circumstances. But overall it solves the requirements without too much mess.

23 September 2013

Using $q promises to run synchronous code asynchronously

The Q Javascript library provides a great way to handle the results of asynchronous tasks in a simple flexible manner. But the APIs required to actually generate and return promises for your own synchronous code are often a bit verbose, particularly if you want to catch and pass on exceptions as well.

Here's a convenient shortcut: Just call $q.when() with no arguments, then place all of your synchronous code (that you want to behave asynchronously) in a subsequent .then() call. This will automatically pick up any results, or exceptions, and pass them on as promises.

E.g.
function myAsyncSqrt(value) {

  return $q.when()
    .then(function() {
      return Math.sqrt(value);
    });
}
...
var promise = myAsyncSqrt(16);
promise.then(
  function(res) { alert('answer:' + res); },
  function(err) { alert('uh oh:' + err); });

19 August 2013

How to mock an Angular service for testing

To inject a fake version of myService, and intercept calls to myMethod, do something like this:

Or check out the cool video here.

    var myMethodFake = function() { ... };

    beforeEach(function () {
        module(function ($provide) {
            mockMyService = {
                myMethod: jasmine.createSpy('myMethod').andCallFake(myMethodFake)
            };
            $provide.value('myService', mockMyService);
        });
    });

    it('does stuff', inject(function(myService) {
       myService.myMethod();
    });