Category Archives: Web

Slickest Way to Have an Index Counter Variable in a for..of Loop in TypeScript

There is no index variable available in a for..of loop in TypeScript. You can either use Array.prototype.forEach or my custom generator function:

interface IndexEnumerator extends Array {
  0: T;
  1: number;
}

function* indexEnumerator(iterable: Iterable) {
  let index = 0;
  for (let item of iterable) {
    yield <IndexEnumerator>[item, index];
    index++;
  }
}

Usage example:

interface Person {
  name: string;
  age: number;
}

let people: Person[] = [
  { name: 'Patrick', age: 23 },
  { name: 'Trong', age: 22 },
  { name: 'Hansruedi', age: 57 }
];

for (const [person, index] of indexEnumerator(people)) {
  console.log(`${person.name} is ${person.age} years old.`);
}

ES6 Variable Swap Explained

The following ES6 code swaps the values of two variables:

var x = 1;
var y = 2;
[x, y] = [y, x];

It works by using a Destructuring assignment on the array [y, x]. Destructuring is used to extract values from an array or an object. You are able to do this for example:

var [month, year] = [5, 1990]

The example above creates two local variables called “month” and “year” with the respective values 5 and 1990. In the swap example we are omitting the “var” keyword and end up with two simple assignment calls (most ES6 transpilers end up creating the following code):

var x = 1;
var y = 2;
var temp = [x, y];
x = temp[1];
y = temp[0];

NeedThis – Your Personal Must-Have List

Screenshot

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 });
  autoRunner.makeExecutable('pre.executable.autorun');

  var runner = new CodeRunner({ autorun: false });
  runner.makeExecutable('pre.executable:not(.autorun)');
});

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 note 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) {
    this._removeListener(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) {
      listenerObj.fn(listenerObj.event); 
    });
  },
};

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

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

// inherit from Observable
Person.prototype = Observable;

// define getName method
Object.defineProperty(Person.prototype, 'getName', {
  writable: false,
  value: function() {
     return this.name;  
  }
});

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..."

jon.off('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 JSFuck.com which can produce this kind of code. Quite interesting!

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:

localStorage.getItem('test');
// [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 });
console.log(storage.getObject('user'));

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.