DailyJS

DailyJS

The JavaScript blog.


Tagtutorial
Featured

libraries data maps tutorial sponsored-content geoip

Introduction to SimpleMaps

Posted on .

Interactive maps are a great way to visualize geographic data or improve website navigation. Now that SVG is supported by all modern browsers, it has become a popular format for interactive maps. Vector maps scale beautifully and are an attractive and lightweight alternative to Google Maps and OpenStreetMap.

SimpleMaps is a commercial interactive map library. It adds region-level zooming, responsiveness, legacy browser support, latitude/longitude calibration, mobile-friendly tooltips and more to an otherwise static SVG file. If you'd prefer to implement these features on your own, it also offers a free library of web-optimized SVG maps (MIT licensed).

This tutorial will demonstrate what is possible with SimpleMaps and how to get started. To begin, go to http://simplemaps.com/world and download the world map trial. Open test.html in a web browser to view the map.

Initial

The map consists of two JavaScript files: worldmap.js and mapdata.js. The vector paths and the map logic are stored in the worldmap.js file. All customizations to the map are stored in the mapdata.js file. The map can be easily customized by making changes to the mapdata.js file in a text editor and refreshing the browser.

The mapdata.js file contains defaults that can be overwritten for individual countries. For example, to make all countries red, you would simply set:

state_color: 'red',  

in the main_settings object. To override that default and make the USA blue, you'd simply add:

color: 'blue',  

to the US state_specific object. The description property for each country accepts HTML which will be displayed in the tooltip upon hover or (when a mobile device is detected) click.

To speed up the customization process, SimpleMaps offers an online customization tool that makes it easy to customize properties quickly using a spreadsheet. Countries, locations, and regions can all be customized using this Excel-like interface. Changes to the map are reflected in real time.

Customization

All customizations are automatically saved to the mapdata.js file. This makes it easy to switch between the convenience of the spreadsheet editor and the control of making changes directly to the JavaScript object. It is even possible to edit the JavaScript code online using the "Code" tab.

Code

When you are finished, you can install the map on a webpage by embedding both scripts and adding a target <div>:

<script type="text/javascript" src="mapdata.js"></script>  
<script type="text/javascript" src="worldmap.js"></script>  
<div id="map"></div>  

To fully integrate SimpleMaps with other web page elements you can utilize its JavaScript API. This makes it possible to update the map, listen for map events, and dynamically zoom around the map.

All around, SimpleMaps aims to simplify the process of creating interactive maps while retaining the flexibility that has made SVG maps so popular.

Featured

tutorial promises

JavaScript Promises ... In Wicked Detail

Posted on .

This post is by Matt Greer. You can find the original here: mattgreer.org/articles/promises-in-wicked-detail/

I've been using Promises in my JavaScript code for a while now. They can be a little brain bending at first. I now use them pretty effectively, but when it came down to it, I didn't fully understand how they work. This article is my resolution to that. If you stick around until the end, you should understand Promises well too.

We will be incrementally creating a Promise implementation that by the end will mostly meet the Promise/A+ spec, and understand how promises meet the needs of asynchronous programming along the way. This article assumes you already have some familiarity with Promises. If you don't, promisejs.org is a good site to check out.

Why?

Why bother to understand Promises to this level of detail? Really understanding how something works can increase your ability to take advantage of it, and debug it more successfully when things go wrong. I was inspired to write this article when a coworker and I got stumped on a tricky Promise scenario. Had I known then what I know now, we wouldn't have gotten stumped.

The Simplest Use Case

Let's begin our Promise implementation as simple as can be. We want to go from this

doSomething(function(value) {  
  console.log('Got a value:' value);
});

to this

doSomething().then(function(value) {  
  console.log('Got a value:' value);
});

To do this, we just need to change doSomething() from this

function doSomething(callback) {  
  var value = 42;
  callback(value);
}

to this "Promise" based solution

function doSomething() {  
  return {
    then: function(callback) {
      var value = 42;
      callback(value);
    }
  };
}

fiddle

This is just a little sugar for the callback pattern. It's pretty pointless sugar so far. But it's a start and yet we've already hit upon a core idea behind Promises

Promises capture the notion of an eventual value into an object

This is the main reason Promises are so interesting. Once the concept of eventuality is captured like this, we can begin to do some very powerful things. We'll explore this more later on.

Defining the Promise type

This simple object literal isn't going to hold up. Let's define an actual Promise type that we'll be able to expand upon

function Promise(fn) {  
  var callback = null;
  this.then = function(cb) {
    callback = cb;
  };

  function resolve(value) {
    callback(value);
  }

  fn(resolve);
}

and reimplement doSomething() to use it

function doSomething() {  
  return new Promise(function(resolve) {
    var value = 42;
    resolve(value);
  });
}

There is a problem here. If you trace through the execution, you'll see that resolve() gets called before then(), which means callback will be null. Let's hide this problem in a little hack involving setTimeout

function Promise(fn) {  
  var callback = null;
  this.then = function(cb) {
    callback = cb;
  };

  function resolve(value) {
    // force callback to be called in the next
    // iteration of the event loop, giving
    // callback a chance to be set by then()
    setTimeout(function() {
      callback(value);
    }, 1);
  }

  fn(resolve);
}

fiddle

With the hack in place, this code now works ... sort of.

This Code is Brittle and Bad

Our naive, poor Promise implementation must use asynchronicity to work. It's easy to make it fail again, just call then() asynchronously and we are right back to the callback being null again. Why am I setting you up for failure so soon? Because the above implementation has the advantage of being pretty easy to wrap your head around. then() and resolve() won't go away. They are key concepts in Promises.

Promises have State

Our brittle code above revealed something unexpectedly. Promises have state. We need to know what state they are in before proceeding, and make sure we move through the states correctly. Doing so gets rid of the brittleness.

  • A Promise can be pending waiting for a value, or resolved with a value.
  • Once a Promise resolves to a value, it will always remain at that value and never resolve again.

(A Promise can also be rejected, but we'll get to error handling later)

Let's explicitly track the state inside of our implementation, which will allow us to do away with our hack

function Promise(fn) {  
  var state = 'pending';
  var value;
  var deferred;

  function resolve(newValue) {
    value = newValue;
    state = 'resolved';

    if(deferred) {
      handle(deferred);
    }
  }

  function handle(onResolved) {
    if(state === 'pending') {
      deferred = onResolved;
      return;
    }

    onResolved(value);
  }

  this.then = function(onResolved) {
    handle(onResolved);
  };

  fn(resolve);
}

fiddle

It's getting more complicated, but the caller can invoke then() whenever they want, and the callee can invoke resolve() whenever they want. It fully works with synchronous or asynchronous code.

This is because of the state flag. Both then() and resolve() hand off to the new method handle(), which will do one of two things depending on the situation:

  • The caller has called then() before the callee calls resolve(), that means there is no value ready to hand back. In this case the state will be pending, and so we hold onto the caller's callback to use later. Later when resolve() gets called, we can then invoke the callback and send the value on its way.
  • The callee calls resolve() before the caller calls then(): In this case we hold onto the resulting value. Once then() gets called, we are ready to hand back the value.

Notice setTimeout went away? That's temporary, it will be coming back. But one thing at a time.

With Promises, the order in which we work with them doesn't matter. We are free to call then() and resolve() whenever they suit our purposes. This is one of the powerful advantages of capturing the notion of eventual results into an object

We still have quite a few more things in the spec to implement, but our Promises are already pretty powerful. This system allows us to call then() as many times as we want, we will always get the same value back

var promise = doSomething();

promise.then(function(value) {  
  console.log('Got a value:', value);
});

promise.then(function(value) {  
  console.log('Got the same value again:', value);
});

This is not completely true for the Promise implementation in this article. If the opposite happens, ie the caller calls then() multiple times before resolve() is called, only the last call to then() will be honored. The fix for this is to keep a running list of deferreds inside of the Promise instead of just one. I decided to not do that in the interest of keeping the article more simple, it's long enough as it is :)

Chaining Promises

Since Promises capture the notion of asynchronicity in an object, we can chain them, map them, have them run in parallel or sequential, all kinds of useful things. Code like the following is very common with Promises

getSomeData()  
.then(filterTheData)
.then(processTheData)
.then(displayTheData);

getSomeData is returning a Promise, as evidenced by the call to then(), but the result of that first then must also be a Promise, as we call then() again (and yet again!) That's exactly what happens, if we can convince then() to return a Promise, things get more interesting.

then() always returns a Promise

Here is our Promise type with chaining added in

function Promise(fn) {  
  var state = 'pending';
  var value;
  var deferred = null;

  function resolve(newValue) {
    value = newValue;
    state = 'resolved';

    if(deferred) {
      handle(deferred);
    }
  }

  function handle(handler) {
    if(state === 'pending') {
      deferred = handler;
      return;
    }

    if(!handler.onResolved) {
      handler.resolve(value);
      return;
    }

    var ret = handler.onResolved(value);
    handler.resolve(ret);
  }

  this.then = function(onResolved) {
    return new Promise(function(resolve) {
      handle({
        onResolved: onResolved,
        resolve: resolve
      });
    });
  };

  fn(resolve);
}

fiddle

Hoo, it's getting a little squirrelly. Aren't you glad we're building this up slowly? The real key here is that then() is returning a new Promise.

Since then() always returns a new Promise object, there will always be at least one Promise object that gets created, resolved and then ignored. Which can be seen as wasteful. The callback approach does not have this problem. Another ding against Promises. You can start to appreciate why some in the JavaScript community have shunned them.

What value does the second Promise resolve to? It receives the return value of the first promise. This is happening at the bottom of handle(), The handler object carries around both an onResolved callback as well as a reference to resolve(). There is more than one copy of resolve() floating around, each Promise gets their own copy of this function, and a closure for it to run within. This is the bridge from the first Promise to the second. We are concluding the first Promise at this line:

var ret = handler.onResolved(value);  

In the examples I've been using here, handler.onResolved is

function(value) {  
  console.log("Got a value:", value);
}

in other words, it's what was passed into the first call to then(). The return value of that first handler is used to resolve the second Promise. Thus chaining is accomplished

doSomething().then(function(result) {  
  console.log('first result', result);
  return 88;
}).then(function(secondResult) {
  console.log('second result', secondResult);
});

// the output is
//
// first result 42
// second result 88


doSomething().then(function(result) {  
  console.log('first result', result);
  // not explicitly returning anything
}).then(function(secondResult) {
  console.log('second result', secondResult);
});

// now the output is
//
// first result 42
// second result undefined

Since then() always returns a new Promise, this chaining can go as deep as we like

doSomething().then(function(result) {  
  console.log('first result', result);
  return 88;
}).then(function(secondResult) {
  console.log('second result', secondResult);
  return 99;
}).then(function(thirdResult) {
  console.log('third result', thirdResult);
  return 200;
}).then(function(fourthResult) {
  // on and on...
});

What if in the above example, we wanted all the results in the end? With chaining, we would need to manually build up the result ourself

doSomething().then(function(result) {  
  var results = [result];
  results.push(88);
  return results;
}).then(function(results) {
  results.push(99);
  return results;
}).then(function(results) {
  console.log(results.join(', ');
});

// the output is
//
// 42, 88, 99
Promises always resolve to one value. If you need to pass more than one value along, you need to create a multi-value in some fashion (an array, an object, concatting strings, etc)

A potentially better way is to use a Promise library's all() method or any number of other utility methods that increase the usefulness of Promises, which I'll leave to you to go and discover.

The Callback is Optional

The callback to then() is not strictly required. If you leave it off, the Promise resolves to the same value as the previous Promise

doSomething().then().then(function(result) {  
  console.log('got a result', result);
});

// the output is
//
// got a result 42

You can see this inside of handle(), where if there is no callback, it simply resolves the Promise and exits. value is still the value of the previous Promise.

if(!handler.onResolved) {  
  handler.resolve(value);
  return;
}

Returning Promises Inside the Chain

Our chaining implementation is a bit naive. It's blindly passing the resolved values down the line. What if one of the resolved values is a Promise? For example

doSomething().then(result) {  
  // doSomethingElse returns a Promise
  return doSomethingElse(result)
}.then(function(finalResult) {
  console.log("the final result is", finalResult);
});

As it stands now, the above won't do what we want. finalResult won't actually be a fully resolved value, it will instead be a Promise. To get the intended result, we'd need to do

doSomething().then(result) {  
  // doSomethingElse returns a Promise
  return doSomethingElse(result)
}.then(function(anotherPromise) {
  anotherPromise.then(function(finalResult) {
    console.log("the final result is", finalResult);
  });
});

Who wants that crud in their code? Let's have the Promise implementation seamlessly handle this for us. This is simple to do, inside of resolve() just add a special case if the resolved value is a Promise

function resolve(newValue) {  
  if(newValue && typeof newValue.then === 'function') {
    newValue.then(resolve);
    return;
  }
  state = 'resolved';
  value = newValue;

  if(deferred) {
    handle(deferred);
  }
}

fiddle

We'll keep calling resolve() recursively as long as we get a Promise back. Once it's no longer a Promise, then proceed as before.

It is possible for this to be an infinite loop. The Promise/A+ spec recommends implementations detect infinite loops, but it's not required.
Also worth pointing out, this implementation does not meet the spec. Nor will we fully meet the spec in this regard in the article. For the more curious, I recommend reading the Promise resolution procedure.

Notice how loose the check is to see if newValue is a Promise? We are only looking for a then() method. This duck typing is intentional, it allows different Promise implementations to interopt with each other. It's actually quite common for Promise libraries to intermingle, as different third party libraries you use can each use different Promise implementations.

Different Promise implementations can interopt with each other, as long as they all are following the spec properly.

With chaining in place, our implementation is pretty complete. But we've completely ignored error handling.

Rejecting Promises

When something goes wrong during the course of a Promise, it needs to be rejected with a reason. How does the caller know when this happens? They can find out by passing in a second callback to then()

doSomething().then(function(value) {  
  console.log('Success!', value);
}, function(error) {
  console.log('Uh oh', error);
});

As mentioned earlier, the Promise will transition from pending to either resolved or rejected, never both. In other words, only one of the above callbacks ever gets called.

Promises enable rejection by means of reject(), the evil twin of resolve(). Here is doSomething() with error handling support added

function doSomething() {  
  return new Promise(function(resolve, reject) {
    var result = somehowGetTheValue(); 
    if(result.error) {
      reject(result.error);
    } else {
      resolve(result.value);
    }
  });
}

Inside the Promise implementation, we need to account for rejection. As soon as a Promise is rejected, all downstream Promises from it also need to be rejected.

Let's see the full Promise implementation again, this time with rejection support added

function Promise(fn) {  
  var state = 'pending';
  var value;
  var deferred = null;

  function resolve(newValue) {
    if(newValue && typeof newValue.then === 'function') {
      newValue.then(resolve, reject);
      return;
    }
    state = 'resolved';
    value = newValue;

    if(deferred) {
      handle(deferred);
    }
  }

  function reject(reason) {
    state = 'rejected';
    value = reason;

    if(deferred) {
      handle(deferred);
    }
  }

  function handle(handler) {
    if(state === 'pending') {
      deferred = handler;
      return;
    }

    var handlerCallback;

    if(state === 'resolved') {
      handlerCallback = handler.onResolved;
    } else {
      handlerCallback = handler.onRejected;
    }

    if(!handlerCallback) {
      if(state === 'resolved') {
        handler.resolve(value);
      } else {
        handler.reject(value);
      }

      return;
    }

    var ret = handlerCallback(value);
    handler.resolve(ret);
  }

  this.then = function(onResolved, onRejected) {
    return new Promise(function(resolve, reject) {
      handle({
        onResolved: onResolved,
        onRejected: onRejected,
        resolve: resolve,
        reject: reject
      });
    });
  };

  fn(resolve, reject);
}

fiddle

Other than the addition of reject() itself, handle() also has to be aware of rejection. Within handle(), either the rejection path or resolve path will be taken depending on the value of state. This value of state gets pushed into the next Promise, because calling the next Promises' resolve() or reject() sets its state value accordingly.

When using Promises, it's very easy to omit the error callback. But if you do, you'll never get any indication something went wrong. At the very least, the final Promise in your chain should have an error callback. See the section further down about swallowed errors for more info.

Unexpected Errors Should Also Lead to Rejection

So far our error handling only accounts for known errors. It's possible an unhandled exception will happen, completely ruining everything. It's essential that the Promise implementation catch these exceptions and reject accordingly.

This means that resolve() should get wrapped in a try/catch block

function resolve(newValue) {  
  try {
    // ... as before
  } catch(e) {
    reject(e);
  }
}

It's also important to make sure the callbacks given to us by the caller don't throw unhandled exceptions. These callbacks are called in handle(), so we end up with

function handle(deferred) {  
  // ... as before

  var ret;
  try {
    ret = handlerCallback(value);
  } catch(e) {
    handler.reject(e);
    return;
  }

  handler.resolve(ret);
}

Promises can Swallow Errors!

It's possible for a misunderstanding of Promises to lead to completely swallowed errors! This trips people up a lot

Consider this example

function getSomeJson() {  
  return new Promise(function(resolve, reject) {
    var badJson = "<div>uh oh, this is not JSON at all!</div>";
    resolve(badJson);
  });
}

getSomeJson().then(function(json) {  
  var obj = JSON.parse(json);
  console.log(obj);
}, function(error) {
  console.log('uh oh', error);
});

fiddle

What is going to happen here? Our callback inside then() is expecting some valid JSON. So it naively tries to parse it, which leads to an exception. But we have an error callback, so we're good, right?

Nope. That error callback will not be invoked! If you run this example via the above fiddle, you will get no output at all. No errors, no nothing. Pure chilling silence.

Why is this? Since the unhandled exception took place in our callback to then(), it is being caught inside of handle(). This causes handle() to reject the Promise that then() returned, not the Promise we are already responding to, as that Promise has already properly resolved.

Always remember, inside of then()'s callback, the Promise you are responding to has already resolved. The result of your callback will have no influence on this Promise

If you want to capture the above error, you need an error callback further downstream

getSomeJson().then(function(json) {  
  var obj = JSON.parse(json);
  console.log(obj);
}).then(null, function(error) {
  console.log("an error occured: ", error);
});

Now we will properly log the error.

In my experience, this is the biggest pitfall of Promises. Read onto the next section for a potentially better solution

done() to the Rescue

Most (but not all) Promise libraries have a done() method. It's very similar to then(), except it avoids the above pitfalls of then().

done() can be called whenever then() can. The key differences are it does not return a Promise, and any unhandled exception inside of done() is not captured by the Promise implementation. In other words, done() represents when the entire Promise chain has fully resolved. Our getSomeJson() example can be more robust using done()

getSomeJson().done(function(json) {  
  // when this throws, it won't be swallowed
  var obj = JSON.parse(json);
  console.log(obj);
});

done() also takes an error callback, done(callback, errback), just like then() does, and since the entire Promise resolution is, well, done, you are assured of being informed of any errors that erupted.

done() is not part of the Promise/A+ spec (at least not yet), so your Promise library of choice might not have it.

Promise Resolution Needs to be Async

Early in the article we cheated a bit by using setTimeout. Once we fixed that hack, we've not used setTimeout since. But the truth is the Promise/A+ spec requires that Promise resolution happen asynchronously. Meeting this requirement is simple, we simply need to wrap most of handle()'s implementation inside of a setTimeout call

function handle(handler) {  
  if(state === 'pending') {
    deferred = handler;
    return;
  }
  setTimeout(function() {
    // ... as before
  }, 1);
}

This is all that is needed. In truth, real Promise libraries don't tend to use setTimeout. If the library is NodeJS oriented it will possibly use process.nextTick, for browsers it might use the new setImmediate or a setImmediate shim (so far only IE supports setImmediate), or perhaps an asynchronous library such as Kris Kowal's asap (Kris Kowal also wrote Q, a popular Promise library)

Why Is This Async Requirement in the Spec?

It allows for consistency and reliable execution flow. Consider this contrived example

var promise = doAnOperation();  
invokeSomething();  
promise.then(wrapItAllUp);  
invokeSomethingElse();  

What is the call flow here? Based on the naming you'd probably guess it is invokeSomething() -> invokeSomethingElse() -> wrapItAllUp(). But this all depends on if the promise resolves synchronously or asynchronously in our current implementation. If doAnOperation() works asynchronously, then that is the call flow. But if it works synchronously, then the call flow is actually invokeSomething() -> wrapItAllUp() -> invokeSomethingElse(), which is probably bad.

To get around this, Promises always resolve asynchronously, even if they don't have to. It reduces surprise and allows people to use Promises without having to take into consideration asynchronicity when reasoning about their code.

Promises always require at least one more iteration of the event loop to resolve. This is not necessarily true of the standard callback approach.

Before We Wrap Up ... then/promise

There are many, full featured, Promise libraries out there. The then organization's promise library takes a simpler approach. It is meant to be a simple implementation that meets the spec and nothing more. If you take a look at their implementation, you should see it looks quite familiar. then/promise was the basis of the code for this article, we've almost built up the same Promise implementation. Thanks to Nathan Zadoks and Forbes Lindsay for their great library and work on JavaScript Promises. Forbes Lindsay is also the guy behind the promisejs.org site mentioned at the start.

There are some differences in the real implementation and what is here in this article. That is because there are more details in the Promise/A+ spec that I have not addressed. I recommend reading the spec, it is short and pretty straightforward.

Conclusion

If you made it this far, then thanks for reading! We've covered the core of Promises, which is the only thing the spec addresses. Most implementations offer much more functionality, such as all(), spread(), race(), denodeify() and much more. I recommend browsing the API docs for Bluebird to see what all is possible with Promises.

Once I came to understand how Promises worked and their caveats, I came to really like them. They have led to very clean and elegant code in my projects. There's so much more to talk about too, this article is just the beginning!

If you enjoyed this, you should follow me on Twitter to find out when I write another guide like this.

Further Reading

More great articles on Promises

Found a mistake? if I made an error and you want to let me know, please email me or file an issue. Thanks!

Featured

tutorial encapsulation

Encapsulation Breaking

Posted on .

Encapsulation is the process by which an object's internal components and behavioral details are hidden from calling code. Only that which should be exposed is exposed, making objects self-contained black boxes to the outside world. Many languages support encapsulation by supplying visibility modifiers (e.g., private) and constructs such as inner classes.

Unfortunately, JavaScript offers very little in the encapsulation department. While there are certain tricks that can wrap protected code in closures (see Module Pattern), many have disadvantages that compromise code flexibility and extensibility.

Standard Convention

Instead of using closure-based encapsulation, which often makes object-oriented inheritance difficult, many libraries and code-bases opt to mark private properties and functions with an underscore prepend. This convention makes inspecting the properties and functions easy within browser debuggers.

var Person = function(first, last){  
  // private properties _first, _last, and _id
  this._first = first;
  this._last = last;
  this._id = this._generateId();
};

Person.prototype = {  
  getId : function(){
    return this._id;
  },
  getFirstName: function(){
    return this._first;
  },
  getLastName : function(){
    return this._last;
  },
  // private function to generate an id for this object
  _generateId : function(){
    return new Date().getTime().toString();
  }
};

This convention is commonplace, similar to naming constants in uppercase. The downside is that private properties and functions can still be accessed, thus breaking encapsulation because of careless coding.

Encapsulation Breaking

The dynamic nature of JavaScript allows for a free-for-all environment where a developer can do whatever he or she wants. Consider the following:

var person = new Person("Bob", "Someguy");  
console.log(person._first); // logs "Bob"  

This appears all fine and well, but now we've coupled our code to the Person implementation. Any change to the internals -- the category of change encapsulation should protect us against -- could break calling code.

var Person = function(first, last){  
  this._firstName = first; // property change
  this._lastName = last; // property change
  this._id = this._generateId();
};

// ... 
var person = new Person("Bob", "Someguy");  
console.log(person._first); // logs "undefined"  

These bugs can be difficult to track, especially since the application code may not have changed...an updated external library or resource, in which Person may be defined, is all that it takes. The best defense against such couplings is to avoid breaking encapsulation. If a property or method is marked as private, do not access, modify, or invoke it. The overhead in rethinking the architecture and design is almost always less than the cost of dealing with the consequences of breaking encapsulation.

In other words: "Developers don't let developers break encapsulation."

Method Stealing

As troublesome as accessing private properties can be in JavaScript, there is another much more insidious practice that seems commonly accepted: method stealing.

The methods Function.prototype.call and Function.protoype.apply are integral to modern libraries and code-bases by allowing a method to inject a custom context (this reference) into the execution scope. Without these capabilities the reliance on closures to achieve the same effect would be too cumbersome.

Just as some properties should be hidden, so too should some methods. Given our prior example, Person.prototype._generateId() might function as an inadequate UUID generator. A clever developer notices that another available method Book.prototype._setUUID() sets a this._id property on all Book objects whose value is much more unique across space and time than Person.prototype._generateId();

var Book = function(title, author){  
  this._title = title;
  this._author = author;
  this._id = null;
  this._setUUID();
}
Book.prototype = {  
  getId : function(){
    return this._id;
  },
  getTitle : function(){
    return this._title;
  },
  getAuthor : function(){
    return this._author;
  },
  _setUUID : function(){
    var result = '';
    for(var i=0; i<32; i++)
    {
      result += Math.floor(Math.random()*16).toString(16);
    } 
    this._id = result;
  }
};

In return, the developer has chosen to "steal" this behavior from Book for Person and modify Person.prototype._generateId() to invoke Book.prototype._setUUID().

var Person = function(first, last){  
  // private properties _first, _last, and _id
  this._first = first;
  this._last = last;
  this._id = null;
  this._generateId();
};

Person.prototype = {  
  getId : function(){
    return this._id;
  },
  getFirstName: function(){
    return this._first;
  },
  getLastName : function(){
    return this._last;
  },
  // private function to generate an id for this object
  _generateId : function(){
    // sets this._id withing _setUUID()
    Book.prototype._setUUID.call(this);
  }
};

Again this works...ostensibly so, by having this._id set by Book.prototype._setUUID(). The design is brittle, however, because Book's internals can be refactored unbeknownst to Person, thus breaking Person objects. If Book.prototype._setUUID() is refactored to set this._uuid rather than this._id then all Person.prototype.getId() invocations will return undefined. With one myopic decision we broke our application because it was easier to break encapsulation rather than rethink the design.

Conclusion

There is not much of a conclusion except do not break encapsulation. In fact, apply the Golden Rule while coding: treat other code as you wish yours would be treated. Any API deficiencies should be brought to the original author, not hacked apart to make it usable for one use case or instance. The maintenance headache down the road is just not worth it.

Featured

functional tutorial

Functional Programming in JavaScript

Posted on .

JavaScript has two parents: Scheme and Self. We can thank Self for all of the object-orientedness of JavaScript and indeed we do in our code and our tutorials. However, Scheme played just as important a role in the language's design, and we would do ourselves ill to overlook JavaScript's functional heritage.

What exactly does it mean for JavaScript to be functional? "Functional" merely describes a collection of traits a given language may or may not have. A language like Haskell has all of them: immutable variables, pattern matching, first class functions, and others. Some languages hardly have any, like C. While JavaScript certainly doesn't have immutable variables or pattern matching it does have a strong emphasis on first class functions; mutating, combining, and using these function objects for cleaner and more succinct code is the purpose of this tutorial.

Partial Application

Partial application is a technique for taking a function f and binding it against one or more arguments to produce a new function g with those arguments applied. We'll demonstrate this operation by adding a helper function p to Function's prototype.

Function.prototype.p = function() {  
  // capture the bound arguments
  var args = Array.prototype.slice.call(arguments);
  var f = this;
  // construct a new function
  return function() {
    // prepend argument list with the closed arguments from above
    var inner_args = Array.prototype.slice.call(arguments);
    return f.apply(this, args.concat(inner_args))
  };
};

var plus_two = function(x,y) { return x+y; };  
var add_three = plus_two.p(3);  
add_three(4); // 7  

Composition

Composition is an operation that produces a new function z by nesting functions f and g. You can think of it in this way: z(x) == f(g(x)). Let's add a helper like we did for partial application.

Function.prototype.c = function(g) {  
  // preserve f
  var f = this;
  // construct function z
  return function() {
    var args = Array.prototype.slice.call(arguments);
    // when called, nest g's return in a call to f
    return f.call(this, g.apply(this, args));
  };
};

var greet = function(s) { return 'hi, ' + s; };  
var exclaim = function(s) { return s + '!'; };  
var excited_greeting = greet.c(exclaim);  
excited_greeting('Pickman') // hi, Pickman!  

Flipping

Flipping at first seems like a scary and arbitrary thing to do to a poor Function. However, it is useful when one desires to use partial application to bind arguments other than the first. To perform a flip we take function f which takes parameters (a,b) and construct a function g which takes parameters (b,a).

Function.prototype.f = function() {  
  // preserve f
  var f = this;
  // construct g
  return function() {
    var args = Array.prototype.slice.call(arguments);
    // flip arguments when called
    return f.apply(this, args.reverse());
  };
};

var div = function(x,y) { return x / y; };  
div(1, 2) // 0.5  
div.f()(1,2) // 2  

Point-Free Style

Point-free programming is a style of coding that one doesn't see much outside of languages like Haskell or OCaml. However, it can help drastically reduce the use of the rather verbose function declaration syntax omnipresent in JavaScript code. Programming in a point-free style is made possible by our helpers above, and we'll combine them to illustrate this concept.

// We'll start by solving the following problem in a non point-free way.
// Produce a function which, given a list, returns the same list with
// every number made negative.

// First, declare some helpers:
var negate = function(x) { return -1 * x; };  
var abs = function(x) { return Math.abs(x); };  
var map = function(a, f) { return a.map(f); };  
var numbers = [-1, 2, 0, -2, 3, 4, -6]

var negate_all = function(array) { return map(array, function(x) { return negate(abs(x)) };  
negate_all(numbers); // [-1, -2, 0, -2, -3, -4, -6]

// That solves it; but we can do better:

var negate_all = map.f().p(negate.c(abs));  
negate_all(numbers); // [-1, -2, 0, -2, -3, -4, -6]  

What did we do here? First, we flipped map's signature to be (f,a); this allows us to then partially apply a function to map and turn it into a function that takes only a single parameter: the array we wish to negate. But what function do we want to bind to our map? The result of negate.c(abs), which represents a function that does negate(abs(x)). We've produced the same function in the end and solved our problem. In the former attempt, we declare a new function to imperatively do what we wish; in the latter we construct a new function based on functions we already have.

What makes this point-free? Note the redundancy of the array argument in the former declaration. We already have a function that knows how to produce a new array from an existing one; why not convert that function into a new one to do what we want? We cut characters by 37% and, for many, achieve better readability.

Conclusions

In the end, functional programming is a matter of taste. For some it is a thing of subtle beauty and for others a wild nest of parentheses. This tutorial is a suggestion of styles that might be and is in no way a 'Functional is better' argument. If this has piqued the reader's interest, she or he may be interested in the following resources:

Featured

linked-data tutorial

A Simple Linked Data and JavaScript Tutorial

Posted on .

Disclaimer: This article by Ric is a short tutorial on how to consume Linked Data using JavaScript. Some of the examples use Ric's company's new Linked Data publishing platform, [PublishMyData](http://publishmydata.com).

Introduction

Mention Linked Data or RDF and many developers run screaming. The truth
is that Linked Data is
really rather simple (and in many cases you don't even need to use
RDF if you don't want to). In this tutorial we're going to use jQuery to request some data from a Linked Data
service, and then display the results in a table and on a map. You can
see the final result of the tutorial
here (just view source to see all the code).

Writing the SPARQL Query

We'll need to run some SPARQL to get the data we're interested in
(SPARQL is a query language analogous to SQL for relational databases). The following query selects
the names and locations (northing and easting) of all the secondary
schools in the City of Manchester (district
'00BN'
).

PREFIX rdfs: 

SELECT ?name ?northing ?easting WHERE {
  ?school   .
  ?school rdfs:label ?name .
  ?school   .
  ?school  ?northing .
  ?school  ?easting .
}

Constructing the URL to call against the endpoint

The SPARQL endpoint we're using expects requests in the following
format:

http://sparql.publishmydata.com?query=URL-ENCODED-SPARQL&output=FORMAT

We could have used the encodeURI JavaScript function to
encode the SPARQL, but I just copied and pasted the url from the
browser's address bar after clicking on the "JSON" link under the
results on this
page
,
where I originally wrote the SPARQL.

{
  "head": {
    "vars": [ "name" , "northing" , "easting" ]
  } ,
  "results": {
    "bindings": [
      {
        "name": { "type": "literal" , "value": "Parrs Wood High School" } ,
        "northing": { "datatype": "http://www.w3.org/2001/XMLSchema#integer" , "type": "typed-literal" , "value": "390094" } ,
        "easting": { "datatype": "http://www.w3.org/2001/XMLSchema#integer" , "type": "typed-literal" , "value": "385464" }
      },
      ...
    ]
  }
}

The array in head.vars contains the variables that we
selected in the SPARQL query, and results.bindings contains
one object per row of results.

Using jQuery to call the URL

We'll just call the query against the endpoint using jQuery's
ajax function (but you could use any other framework if you
prefer). Notice that we use
JSONP data type to avoid CORS issues.

  //<![CDATA[
  var queryUrl = "http://publishmydata.com/sparql.json?q=PREFIX+rdfs%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23%3E%0D%0A%0D%0ASELECT+%3Fname+%3Fnorthing+%3Feasting+WHERE+%7B%0D%0A%0D%0A++%3Fschool+%3Chttp%3A%2F%2Feducation.data.gov.uk%2Fdef%2Fschool%2FdistrictAdministrative%3E+%3Chttp%3A%2F%2Fstatistics.data.gov.uk%2Fid%2Flocal-authority-district%2F00BN%3E+.+%0D%0A%0D%0A++%3Fschool+rdfs%3Alabel+%3Fname+.%0D%0A%0D%0A++%3Fschool+%3Chttp%3A%2F%2Feducation.data.gov.uk%2Fdef%2Fschool%2FphaseOfEducation%3E+%3Chttp%3A%2F%2Feducation.data.gov.uk%2Fdef%2Fschool%2FPhaseOfEducation_Secondary%3E+.%0D%0A%0D%0A++%3Fschool+%3Chttp%3A%2F%2Fdata.ordnancesurvey.co.uk%2Fontology%2Fspatialrelations%2Fnorthing%3E+%3Fnorthing+.%0D%0A%0D%0A++%3Fschool+%3Chttp%3A%2F%2Fdata.ordnancesurvey.co.uk%2Fontology%2Fspatialrelations%2Feasting%3E+%3Feasting+.%0D%0A%7D";

  $.ajax({
    dataType: "jsonp",  
    url: queryUrl
  });             
  //]]>

Making an HTML table from the results

Let's create a table in the html:

... and add a success callback, to populate it with the results of the SPARQL.

$.ajax({
  dataType: "jsonp",
  url: queryUrl
  success: function(data) {    
    // get the table element
    var table = $("#results");              

    // get the sparql variables from the 'head' of the data.
    var headerVars = data.head.vars; 

    // using the vars, make some table headers and add them to the table;
    var trHeaders = getTableHeaders(headerVars);
    table.append(trHeaders);  

    // grab the actual results from the data.                                          
    var bindings = data.results.bindings;

    // for each result, make a table row and add it to the table.
    for(rowIdx in bindings){
      table.append(getTableRow(headerVars, bindings[rowIdx]));
    } 
  }
});

In the code above, I've used a few simple helper functions which just
loop through the data from the JSON, and make table rows and cells from
it.

function getTableHeaders(headerVars) {
  var trHeaders = $("");
  for(var i in headerVars) {
    trHeaders.append( $("" + headerVars[i] + "") );
  }
  return trHeaders;
}

function getTableRow(headerVars, rowData) {
  var tr = $("");
  for(var i in headerVars) {
    tr.append(getTableCell(headerVars[i], rowData));
  }
  return tr;
}

function getTableCell(fieldName, rowData) {
  var td = $("");
  var fieldData = rowData[fieldName];
  td.html(fieldData["value"]);
  return td;
}

Plotting the schools on a map

Now things start to get interesting. To draw the map, we'll need to
include a couple of external scripts:

The LatLngToOSGB.js script is for converting
northings/eastings into latitude/longitudes. Frustratingly, Google uses
the World Geodetic System
(WGS84)
, for lat/long but the NEtoLL function from that library returns
values using the Ordnance Survey National Grid
(OSGB36)
. So we'll need to do a 2-step process to convert them if we want accurate positions for the map
points. The functions below wrap up that conversion for you:

// extra conversion functions: Google uses WGS84 whereas the National Grid uses OSGB36
// (thanks to: http://www.roxburgh.net/projects/googlemaps/)

// Returns object with attributes lat and lon
function ENtoLL84(easting, northing) {
  var vlatlng = NEtoLL(easting, northing);
  return OGBToWGS84(vlatlng.lat, vlatlng.lon, 0);
}

// Returns object with attributes east and north
function LL84toEN(lat, lon) {
  var vlatlon = WGS84ToOGB(lat, lon, 0);
  return LLtoNE(vlatlon.lat, vlatlon.lon);
} 

Now we've got that out of the way, lets make a div for the map to live
in:

... and a function to plot the schools' locations:

function drawMap(data) {
  // make a map, centred on Manchester
  var manchesterLatLon = new google.maps.LatLng(53.480110, -2.237940);
  var myOptions = {
    zoom: 11,
    center: manchesterLatLon,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  // add a marker for each school 
  var bindings = data.results.bindings; 
  for (var i in bindings) {

    var schoolData = data.results.bindings[i];

    var northing = schoolData["northing"]["value"];
    var easting = schoolData["easting"]["value"];
    var name = schoolData["name"]["value"];

    // call our 2-step conversion
    var latLng = ENtoLL84(easting, northing);

    // make a marker with the label as the school name
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng( latLng.lat, latLng.lon ),
      map: map,
      title: name
    });
  } 
} 

Now all that's left to do is to add the call to drawMap to
the ajax success callback.

$.ajax({
  url: queryUrl
  success: function(data) {

    // ... existing code here

    drawMap(data);
  }
});

You should now have something that looks a bit like this
page
.