NeedThis – Your Personal Must-Have List


Fiona Muff, professional hand model

“Hey, what’s that movie we wanted to see called again?” – “Uhm…”

NeedThis is a website where you can create lists. Those lists are saved server-side and you can share the link to your list with your friends. Entries have three attributes: Name, Link and Status (Not released, Available, Downloading and Completed).

I’ve written NeedThis in Node.js. The lists are stored in a NoSQL database and on the frontend runs Backbone.js MVC. There’s really not much code behind it, but I couldn’t find a similar service on the internet that fits my needs.

Run JavaScript live on your Website

I’ve just written coderunner.js. It allows you to write standard <pre> tags and then convert them into executable code that your users can run on their computer. Here is an example:

for (var i = 0; i < 10; i++) {
  console.log('Number ' + i);

You can start coderunner.js by including the file itself, the stylesheet and then initializing like this:

document.addEventListener('DOMContentLoaded', function() {
  var autoRunner = new CodeRunner({ autorun: true });

  var runner = new CodeRunner({ autorun: false });

coderunner.js has no dependencies and is about 2 KB in size (uncompressed). It is currently only tested in WebKit and has no issues with prettify by Google.

Observer Pattern in JavaScript

Here is a simple, straight-forward observer implementation in JavaScript that you can use in any modern JavaScript environment. Please not that IE8 and below cannot use Array.prototype.filter and Array.prototype.forEach.

var Observable = {
  listeners: [ /* { event: String, fn: Function } */ ],
  _addListener: function(event, fn) {
    this.listeners.push({ event: event, fn: fn });
  _removeListener: function(event) {
    this.listeners = this.listeners.filter(function(listenerObj) {
      return listenerObj.event !== event; 
  on: function(event, fn) {
    this._addListener(event, fn);  
  off: function(event) {
  listenTo: function(target, event, fn) {
    target._addListener(event, fn);
  trigger: function(event) {
    this.listeners.filter(function(listenerObj) {
      return listenerObj.event === event; 
    }).forEach(function(listenerObj) {

You can set this object to a prototype of any of your classes:

// new class Person
var Person = function(name) { = name;

// inherit from Observable
Person.prototype = Observable;

// define getName method
Object.defineProperty(Person.prototype, 'getName', {
  writable: false,
  value: function() {

Any object that you instantiate from “Person” now is observable. This means you can easily do the following:

var jon    = new Person('Jon Snow');
var tyrion = new Person('Tyrion Lannister');

jon.listenTo(tyrion, 'greeting', function(event) {
  console.log('Received a ' + event + ' from ' + tyrion.getName());

jon.on('bye', function(event) {
  console.log('Received a ' + event + ' from ' + jon.getName());

tyrion.trigger('greeting'); // "Received a greeting from..."
jon.trigger('bye'); // "Received a bye from..."'bye'); // unbinds all 'bye' listeners
jon.trigger('bye'); // does not fire anything

The syntax is very similar to Backbone, but of course without any dependencies. This code works best in a modern NodeJS environment where you do not need to support old JavaScript implementations. Bitbucket repository.

This code makes no sense.. Or does it?


Beautiful right? This messy line of brackets, exclamation points and plus signs evaluates to the string “2014″. You can try it by pasting it into your browsers console or using Node.js.

Let’s have a closer look at the first part of it:


This produces an array with one entry: 2. If we break it down even further, it starts to make sense:


This code consists of four elements (differently colored). On the right we got a simple, empty array. The plus sign in front of it automatically casts it into a number, because that’s how loosely typed languages work. We can prove it by running this:

Number(new Array())

Alright, so casting an array into a number results in 0.  The next element we need to look into is the exclamation point. The “!” operator inverts a boolean. But our 0 from above is not a boolean. No problem, JavaScript just casts it into one like we would expect it to do in “normal” code. We are now left with this:


All we have to do now is simply cast true back into a number by using the plus operator:


Now if we chain two of those together, we get our first value of “2014″; “2″!


And that’s the whole magic. The rest is pretty much the same, I won’t explain it all here. There is a site called which can produce this kind of code. Quite interesting!

Weekend Project: Display a website on my TV when a League of Legends player starts a game


I really like the MOBA League of Legends which is currently the most played game in the world. In LoL there are two teams of five people fighting on a big map in order to destroy the enemy nexus. After starting a game, many people will visit during the loading screen, a site that provides live game details. You get insight into their ranking , runes and masteries which can possibly help you to win the game.

For my weekend project I wanted an application to do the following tasks for me:

  • Check if player “x” is in a game every 20 seconds
  • Start TV using CEC
  • Start a web browser and point it to
  • Wait until game is over and turn off TV

Sounds simple right?

Turning a TV on using CEC

Consumer Electronics Control (CEC) is used to control a TV over the HDMI cable. I found a library called libCEC (Tutorial) that compiles on Raspbian. LibCEC installes the command line utility cec-client that I used in my application.

echo "on 0" | cec-client -s

Piping “on 0″ into cec-client turns the TV on.  You can use “standby 0″ to turn it off. Now I need to find out how I can start a web browser on the Raspberry Pi.

Starting a browser in kiosk mode

Kiosk mode means starting it in fullscreen with no visible controls. I used the pre-installed browser Midori for this. But before you can start a browser, you need to start a graphical interface:

startx &

The “&” is used to start the process in background. “startx” should now have started a GUI on display :0. Now let’s start the browser:

midori -e Fullscreen --display :0 -a

That’s it. Using this knowledge I created a simple application to turn my TV on whenever I started a new game and display lolnexus. Since I often get snacks during loading screen and have to walk past my TV, I can now simultaneously prepare myself for the game.

The application (written in Node.js) can be found on Bitbucket. 

Store Objects in JavaScripts HTML5 LocalStorage

LocalStorage is really useful. It can save variables (just like cookies) in a users browser. But there is one problem which many people seem to encounter: Storing objects does not work.

localStorage.setItem('test', { someKey: 123 });

This line of code saves our object as a string. If we restore the stored item, we will get this:

// [object Object]

This is because JavaScript calls the .toString() method on our object, which simply outputs [object Object]. If we want to store and restore objects, we need to encode them into a JSON string. The following code implements my most used solution for storing objects:

var LocalStorageManager = function() { 
    if (typeof localStorage === 'undefined') {
        throw 'localStorage cannot be used in this browser';   

LocalStorageManager.prototype.setObject = function(key, obj) {
    localStorage.setItem(key, JSON.stringify(obj));

LocalStorageManager.prototype.getObject = function(key) {
    return JSON.parse(localStorage.getItem(key));
var storage = new LocalStorageManager();
storage.setObject('user', { name: 'john', age: 26 });

Yes, you could do this without an additional object, but it keeps stuff cleaner if you use one. If you got any questions, feel free to contact me in the comment section down below.

How to win the game 2048

Here is the strategy I used to beat the popular 2048 game. It is not a guaranteed win, but I have achieved multiple scores over 10’000 points and won two times.

Tile Movement

It is very important to never use all 4 directions in one game. Choose 3 directions and only use these. I always go for left, up and right, meaning I never press down.


Most guides will tell you to choose a corner and try to hold your biggest tile there. This will most likely fail, so try to always keep the biggest tiles on top of your board. After around 5000 points you should avoid having a 2 or 4 in your top two rows, because you just can’t combine them with a 128 (or a bigger tile of course) any time soon.


As soon as you have a 1024 and two 512 tiles everything I said above becomes irrelevant and you should try to combine those to a 2048, therefore winning the game.

Now there is an algorithm that has a 90% win rate, programmed by the creator of 2048, Gabriele Cirulli. You can check out the 2048 AI here and a Stackoverflow question regarding this issue here.

What are anonymous self-invoking functions in JavaScript?

Have you ever been confused by something like this?

(function() { 
    console.log('hello world');

This function invokes itself after it has been declared, meaning it calls itself right after you have declared it. All we are doing is wrapping the function into parentheses and then call it like you would call any function with (). Think of it this way:


Some people use .call() (which does exactly the same), because the other syntax can be confusing for people who have just started with JavaScript:


To finish this post off, let us have a look at a real world example of an anonymous, self-invoking function:

var list = (function() {
    // declare variables that cannot be used outside of the function scope
    var x = 10;
    var y = 20;

    return [x, y];

// correctly logs [10, 20]

// throws a reference error

for-Loop with Delay in JavaScript

I had multiple JavaScript beginners come to me and ask me this question:
How can I create a for-loop with x ms delay in between?

This code is what most have come up with (for quick readers: not what you are looking for!):

for (var index = 1; index <= 50; index++) {
    setTimeout(function() {
    }, 100);    

Now this prints "50" fifty times, because a for-loop is synchronous while setTimout is asynchronous. This means that the for-loop is finished very fast and has startet 50 setTimeouts. After 100ms all of those setTimeout functions will fire together, therefore printing "50" fifty times. Note that the var-keyword binds variables to the function scope, not the current block scope like in other languages.

In order to create a for-loop with actual delay - in our case printing a number, waiting 100ms and printing the next number - you need to create a self-invoking, recursive function. Don't worry, it's not that hard.

var maxLoops = 50;
var counter = 0;

(function next() {
    if (counter++ >= maxLoops) return;

    setTimeout(function() {
    }, 100);

Here we declare two variables, maxLoops and counter. These are for keeping track of how many times the function has called itself. Afterwards we create the function "next", put it in brackets and call it immediately. This is why it's called a self-invoking function.

The if-statement does two things. First of all it counts up our counter variable using the ++ operator. It also returns the function if it has been called 50 times, therefore stopping the loop.

The last part is the most important. We create our setTimeout function and then call next() after the number has been printed. And that's how you create a for-loop with delay in JavaScript.

Here is an even shorter, but harder to understand solution:

(function next(counter, maxLoops) {
    // break if maxLoops has been reached
    if (counter++ >= maxLoops) return;

    setTimeout(function() {

        // call next() recursively
        next(counter, maxLoops);
    }, 100);
})(0, 50);

Simple Registry Pattern Implementation in JavaScript

Have you ever had to deal with something like this?

switch (input) {
    case '200':
        correspondingEvent = 'success';
    case '404':
        correspondingEvent = 'error';
    case '500':
        correspondingEvent = 'error';
    // etc...

A huge switch statement that you cannot dynamically change. There is a design pattern called Registry Pattern for exactly this case. It is basically an object/array which maps different conditions.

Here is a JavaScript implementation of said pattern:

var registry = {
    '200': 'success',
    '404': 'error',
    '500': 'error',
    '403': 'error',

var input = '200', correspondingEvent;

if (input in registry) {
    correspondingEvent = registry[input];   
} else {
    // handle invalid input   

Adding or removing new cases is very easy:

registry['401'] = 'error';
delete registry['401'];

I would like to thank Christian Strotz for opening my eyes on this one, since I originally used an array instead of an object. (like in most other programming languages).