Author Archive

3rd April
2014
written by Poul

As a developer in the .NET world where LINQ is first class citizen, when going to JavaScript it seems that some methods are missing. There is even a few libraries that tries to remedy this, but if you are just looking to get the job done the most often used methods are right at hand. (Looking for features such as Lazy-evaluation or observables, linq.js and RxJS offers these).

In the following I’ll list the most used operations and their JavaScript equivalents cheat sheet style. Notice that I’m using Lambda expressions in JavaScript to get the code a bit more concise, if they aren’t available just replace expressions like:

(data) => {}

with

function(data) {}

All operations are executed against this example:

var persons = [
    { firstname: 'Peter', lastname: 'Jensen', type: 'Person', age: 30 },
    { firstname: 'Anne', lastname: 'Jensen', type: 'Person', age: 50  },
    { firstname: 'Kurt', lastname: 'Hansen', type: 'Person', age: 40  }
];

Notice that some of the operations modifies the source array, if you don’t want that just clone it with:

persons.slice(0);

Every operation is named after the method’s name in LINQ:

All

C#
	var result = persons.All(person => person.type == "Person");
JavaScript
	var result = persons.filter(person => person.type == 'Person').length == persons.length;

Concat

C#
	var result = persons.Concat(persons);
JavaScript
	var result = persons.concat(persons);

Count

C#
	var result = persons.Count();
JavaScript
	var result = persons.length;

Distinct

C#
	var lastnames = persons.Select(person => person.lastname);
    var result = lastnames.Distinct();
	
JavaScript
	var lastnames = persons.map(person => person.lastname);
    var result = lastnames.filter((value, index) => lastnames.indexOf(value) == index);

Empty

C#
	var result = Enumerable.Empty<dynamic>();
JavaScript
	var result = [];

First

C#
	var result = persons.First();
JavaScript
	var result = persons[0];
    if (!result) throw new Error('Expected at least one element to take first')

FirstOrDefault

C#
	var result = persons.FirstOrDefault();
JavaScript
	var result = persons[0];

ForEach

C#
	var fullnames = new List<string>();
    persons.ForEach(person => fullnames.Add(person.firstname + " " + person.lastname));
JavaScript
var fullnames = [];
persons.forEach(person => fullnames.push(person.firstname + ' ' + person.lastname))

GroupBy

C#
	var result = persons.GroupBy(person => person.lastname);
JavaScript
	var result = persons.reduce((previous, person) => {
		(previous[person.lastname] = previous[person.lastname] || []).push(person);
    	return previous;
	}, []);

IndexOf

C#
	var result = persons.IndexOf(persons[2]);
JavaScript
	var result = persons.indexOf(persons[2]);

Last

C#
	var result = persons.Last();
JavaScript
	var result = persons[persons.length-1];
    if (!result) throw new Error('Expected at least one element to take last')

LastOrDefault

C#
	var result = persons.LastOrDefault();
JavaScript
	var result = persons[persons.length-1];

OrderBy

C#
	var result = persons.OrderBy(person => person.firstname);
JavaScript
	persons.sort((person1, person2) => person1.firstname.localeCompare(person2.firstname));

OrderByDescending

C#
	var result = persons.OrderByDescending(person => person.firstname);
JavaScript
	persons.sort((person1, person2) => person2.firstname.localeCompare(person1.firstname));

Reverse

C#
	persons.Reverse();
JavaScript
	var result = persons.reverse();

Select

C#
	var result = persons.Select(person => new {fullname = person.firstname + " " + person.lastname});
JavaScript
	var result = persons.map(person => ({ fullname: person.firstname + ' ' + person.lastname }) );

Single

C#
	var result = persons.Single(person => person.firstname == "Peter");
JavaScript
	var onePerson = persons.filter(person => person.firstname == "Peter"); 
    if (onePerson.length != 1) throw new Error('Expected at excactly one element to take single')
    var result = onePerson[0];

Skip

C#
	var result = persons.Skip(2);
JavaScript
	var result = persons.slice(2, persons.length); 

Take

C#
	var result = persons.Take(2);
JavaScript
	var result = persons.slice(0, 2);

Where

C#
	var result = persons.Where(person => person.lastname == "Jensen");
JavaScript
	var result = persons.filter(person => person.lastname == 'Jensen');

So clearly you don’t need a library if you only need the basic operations. The code above with tests is available at GitHub.

This post is also available in Danish at QED.dk.

25th March
2014
written by Poul

One day when I was surfing cat videos professional relevant videos on Youtube I noticed a red progress-indicator:

My first thought was – I want this in my apps. How did they do it?
If you lower the bandwidth a pattern emerges:

youtube-slow

Aha! When you click on a video, Youtube will start a request to fetch informations about it, animate the bar to 60% where it waits until the call is completed and finally animates it to 100%.

Utter deception but without doubt a well thought-out solution. As long as you are on a sufficiently fast connection and the amount of data that needs to be transferred is limited the illusion is complete.

It has to be said that even if Youtube cheats a little it is a much better solution than those spinners you see on the majority of sites with asynchronous requests today:

It gives no sense of progress and no indication if the transfer has stopped. I’ve also experienced many sites where errors aren’t handled correctly and you end up with a eternal spinner – or at least until you loose patience and refresh the page.

Dan Saffer expresses it in simple terms in the book Designing Gestural Interfaces: Touchscreens and Interactive Devices

Progress bars are an excellent example of responsive feedback: they don’t decrease waiting time, but they make it seem as though they do. They’re responsive.

With the very diverse connection speeds we have today I’d say that the need is even greater – The Youtube example from before might hit the sweet spot on an average connection, but If you are sitting away from high speed connectivity maybe on a mobile connection with Edge (nevermind that you probably cannot see the video itself) the wait can easily outweigh your patience.

As Jakob Nielsen writes in Usability Engineering; Feedback is important, especially if the response time varies

10 seconds is about the limit for keeping the user’s attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.

Requirements for the solution

There are many ways to add continuous feedback but each come with their own limitations. To be able to use the solution in most problem areas we need to set some requirements:

The solution should:

  • Be integratable into existing solutions without too much extra work and (almost) without changes to the server.
  • Should work across domains, when the client lives on one domain and communicates with the server on a different. (Also called Cross Origin Resource Sharing or CORS).
  • Work in all browsers.
  • Be able to send a considerable amount of data both back and forth.

 

The first attempts

When communicating with a server from JavaScript, it is under normal circumstances a request that is started and a little while later you get a status indicating whether the call was a success or not. So no continuous feedback. The naive solution could be to make multiple single requests but the overhead of a request is relatively expensive so the combined overhead would be too big.

If you look at HTTP/1.1 there is a possibility to split a response from the server in multiple parts – the method is called chunked http:

chunked

If we send a agreed number of chunks we are able to tell the user how far the request has come.

 

Traditional AJAX call

Traditional AJAX calls – typically executed via XMLHttpRequest generally don’t give any frequent feedback and if you want to execute it as a CORS-call you need to make changes to the server and it will give an extra request if the call is with authorization. The support in older browsers is limited.

 

JSONP

JSONP is an old technique to circumvent the CORS problems with AJAX. A call where you basically add a script tag that lives on the remote server that will then be executed within the scope of the current page.

In a weak moment I tried to implement chunked http in a JSONP call – multiple JavaScript methods in one script that would then be executed continuously. Of course it didn’t work – the browser won’t execute any code until the JavaScript file has been fully loaded.

 

Other technologies

I also looked at Server Sent Events, but thats not supported by Internet Explorer.
WebSockets requires a greater change on the server side and it also gives some challenges with security, cookies etc. when we are outside the traditional http-model.

Failure is always an option

Adam Savage

The final solution

HiddenFrame is a technique where you create a hidden iframe and let it fetch a lump of HTML from the server. If there is any script-tags in this lump, they will be executed as the browser meets each end-tag. So there we have a potential solution.

Sending data is no problem either because we can start the fetch itself by executing a form-post.

And where does JavaScript Promises fit into all this?

Well to get a good API I’ve used a Promise-implementation that offers continuous feedback via the progress-method and handles any success and failure-scenarios:

new LittleConvoy.Client('HiddenFrame').send({ url: 'http://example' }, { name: 'Ford'})
    .progressed(function (progress) {
      ... progress contains percentile progress and will be called 10 times
    })
    .then(function (data) {
      ... the call was a success and data contains the result
    })
    .catch(function (message) {
       ... the call failed and message contains the error message object
    });

On the server side a library is added, currently only available for Microsoft ASP.NET MVC. The JSON producing methods that you already have are just decorated with a attribute that makes sure that everything works:

public class DemoController : Controller
{
    [LittleConvoyAction(StartPercent = 40)]
    public ActionResult Echo(object source)
    {
      return new JsonResult {Data = source };
    }
}

 

Demo or it didn’t happen

  • A small demo is available here.
  • The code is available at GitHub
  • The library can be installed via the .NET package manager NuGet as LittleConvoy.

 

The future

  • The transport layer itself is separate from the client so extra methods can be added, adding traditional AJAX and WebSockets would be an obvious choice in the future if it can be done with too many changes on the server side.
  • Some Promise implementations offer cancellation, it would be great if you could cancel a call.
  • Sending data gives no feedback – it would be great if that was somehow possible.

 

Related work

  • Comet is a collection of technologies that offers push for the browser and it also contains a implementation of iframe-communication but is targeted permanent communication channels.
  • SignalR is like Comet build for push and permanent communication channels
  • Socket.IO is an abstraction over WebSockets that contains fallback to iframe-communication but more targeted Node.js.

This post is also available in Danish at QED.dk

3rd March
2014
written by Poul

In my previous post in Danish I looked at how to perform asynchronous calls by using promises. Now the time has come to pick which library that fits the next project.

There is a lot of variants and the spread is huge. One search for promise via the node package manager npmjs.org gave 1150 libraries which either provides or are dependent on promises. Of these I have picked 12 different libraries to look at, all are open source and all offer a promise-like structure.

Updates:

  • 2014/03/06 – Fixed a few misspellings (@rauschma via Twitter)
  • 2014/03/07 – Removed raw sizes, since they did’nt make much sense (@x-skeww via Reddit)
  • 2014/03/07 – Added that catiline uses lie underneath. (@CWMma via Twitter)
  • 2014/03/07 – Added clarification on what the test does. (@CWMma via Twitter)

The API across the libraries are almost alike, so I’ve decided to look at:

Features
What kind of generic promise related features does each library offer?

Size
And I’m thinking mostly browsers here – how many extra bytes will this add to my site?

Speed
How fast are the basic promise operations in the library? You would expect that these will execute many times so this is important.

 

The libraries

First an overview of the selected candidates, their license and author. Note that the name is linking to the source of the library (typical Github).

 

License Author Note
Bluebird MIT Petka Antonov Loaded with features and should be one of the fastest around and with special empathizes on error handling via good stack traces. Features can be toggled via custom builds.
Catiline MIT Calvin Metcalf Mostly designed for handling of web workers but contains a promise implementation. Uses lie underneath.
ES6 Promise polyfill MIT Jake Archibald Borrows code from RSVP, but implemented according to the ECMAScript 6 specification.
jQuery MIT  The jQuery Foundation Classic library for DOM-manipulation across browsers.
kew Apache 2.0  The Obvious Corporation I’m guessing it is pronounced ‘Q’, can be considered as a optimized edition of Q but with a smaller feature set.
lie MIT Calvin Metcalf
MyDeferred MIT RubaXa Small Gist style implementation
MyPromise MIT cho45@lowreal.net Small Gist style implementation
Q MIT Kris Kowal Well known implementation, a light edition of it can be found in the popular AngularJS framework from Google.
RSVP MIT Tilde
when MIT cujoJS
Yui BSD Yahoo! Yahoo’s library for DOM-manipulation across browsers.

 

Features

The following is a look at the library feature set, looking only at features directly linked to promises:

 

Promises/A+ Progression Delayed promise Parallel synchronization Web Workers Cancellation Generators Wrap jQuery
Bluebird ✓ (+389 B) ✓ (+615 B) ✓ (+272 B) ✓ (+396 B) ✓ (+276 B)
Catiline
ES6 Promise polyfill
JQuery
kew
lie
MyDeferred
MyPromise
Q
RSVP
when
Yui


The numbers in parenthesis by Bluebird is the additional size in bytes each feature will add.

Promises/A+
Is the Promises/A+ specification implemented?

Progression
Are methods provided for notification on status on asynchronous tasks before the task is completed?

Delayed promise
Can you create a promise that is resolved after a specified delay?

Parallel synchronization
Are there methods for synchronization of multiple operations, can we get a resolved promise when a bunch of other promises are resolved?

Web Workers
Can asynchronous code be executed via a web worker – pushed to a separate execution thread?

Cancellation
Can promise execution be stopped before it is finished?

Generators
Are coming functions around JavaScript generators supported?

Wrap jQuery
Can promises produced by jQuery be converted to this library’s promises?

 

Size

Every library have been minified via Googles Closure compiler. All executed on ‘Simple’ to prevent any damaging changes. For libraries that support custom builds I have picked the smallest configuration that still supports promises. The result is including compression in the http-stack, so its actually the raw number of bytes one would expect that the application is added when using each library:

 

Minified and compressed

Speed

The speed has been measured via the site jsPerf which gives the option to execute the same tests across a lot of different browsers and platforms including mobile and tablets. The test creates a new promise with each library and measures how much latency is imposed on execution of the asynchronous block (see more detailed explanation here). Note that the test was not created by me, but a lot of fantastic people (current version is 91). The numbers are average across platforms:

 

Operations per second

Conclusion

Over half of the worlds websites already uses jQuery. If you have worked with promises in jQuery, you quickly find that they are inadequate.
I have previously had problems with failing code that doesn’t reject the promise on error as you would expect, but where the error still bubbles up and ends up being a global browser error. The promise specification dictates that errors should be caught and the promise rejected, which is not what happens in jQuery.

So if you today have a site based on jQuery, the obvious choice is to pick one of the libraries that offers conversion from jQuery’s unsafe promises to one of the more safe kind. If size is a priority either Q or when are good suggestions, loaded with features and at a decent speed.

If you are less worried about size, Bluebird is a better choice. The modularity makes it easy to toggle features and it has a significant test suite that covers performance on a lot of other aspects than the single one covered by this post.

If performance is essential, kew is a good bet. A team has picked up Q and looked into lowering its resource requirements. This has resulted in a light weight but very fast library.

If you are looking for a more limited solution with good speed and without big libraries, the ES6 Promise polyfill is a good choice – then in the long term when the browsers catch up, the library can be removed completely.

This post is also available in Danish at QED.dk

31st December
2010
written by Poul

When we found out that my dad was going to spend his Christmas in Thailand, we immediately jumped in; suddenly we had an opportunity to see some family even though we were so far away from home.

My dad has a house in Sangkha where he and his thai wife along with her family are staying while in Thailand. Sangkha is a small city located quite close to the Cambodian border – almost 500 km east of Bangkok, so going there takes most of a day. We decided to go by bus and didn’t regret it.

There is at least three kinds of busses between the east and west; A very cheap one which features only natural air-conditioning (all windows opened), a relatively cheap one, which does have real air-conditing but not really anything else, and then the expensive one which has both air-conditioning, onboard toilet and where food and drinks are served by a nice thai girl in uniform.

We took the latter one and it made the trip a breeze. Once there we booked a room at a nice motel close to my dads house. The room was quite spacious with hot shower, fridge, king bed and very cheap; 350 baht pr. night (about 65 DKK or 12 USD).

Before we went, we’d already talked about making a traditional Danish Christmas dinner and in one of the big Bangkokian malls we’d found red cabbage in a jar and brought along – and my dad had already purchased a duck, which left us only with one problem – how to cook it? Normally in Denmark the duck is roasted in an oven, but at my dads house there were only two gas cookers and a small open barbecue. So we went to Surin – a larger city only 45 km from Sangkha to look for duck-roasting-appliances.

Unfortunatly we were unable to find one of those half-sphere charcoal grills – we’ve been using those for ducks with great success before. Instead we settled on a big bowl-like owen which we quickly christened ‘Otto’ – I think it was the brand name, but we used it in lack of better term. It works almost like a convection oven except the heat comes from the lid and it only barely fits a whole duck. It ended up working very well – since the heat came from above, and the rest of Otto is really just a bowl, it leaves plenty of room for the juices to gather at the bottom; a good basis for the traditional Christmas gravy.

The traditional Danish Christmas dinner dessert is risalamande/ris à l’amande – not nearly as french as it sounds but very good. The basis of this dessert is rice overcooked in milk. Now we could have chosen to cook the rice in a pot as we’d normally do it in Denmark, but since rice cookers  are so widely used here, we opted to use that instead, not really knowing if it would work. It turned out to work beautifully; a typically problem when cooking this dish is that the rice and milk quickly get burned on the bottom of the pot – the rice cooker on the other hand is build for this, and as soon as the rice is boiled, it changes to keeping-it-hot-mode which turned out to be a perfect temperature.

After all the eating, my dad surprised us when he dug out a Christmas tree for us to dance around (probably one of the weirdest Danish Christmas traditions). The Thai part of the family even joined us, and politely hummed along to our Danish Christmas songs.

The Christmas celebration turned out to be much more fun and traditional than we could have hoped for; before even going to Thailand, we’d talked about how Christmas would be with an average temperature of 25 degrees and how we would miss the family and the food. But to us it turned out to be a very good Christmas – although next year I think we’ll spend it in Denmark and maybe go for the warmer territories between Christmas and New Year’s Eve.

Merry Christmas everyone and a happy New Year.

12th August
2010
written by Poul

This little Lego monkey wants to be King Kong…

Wannabe King Kong

Wannabe King Kong by Poul Foged

Tags: , ,