Alexander Gugel

Read this first

Array.prototype.push

I’m always amazed by the excellent readability of V8’s source code. I think everyone should have a rough idea about where to look for specific implementation details of the most common JavaScript functions.

As an example, let’s look at how Arraypush is implemented in V8. V8 implements all (well, most) Array.prototype functions as BIFs in src/js/array.js:

// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Appends the arguments to the end of the array and returns the new
// length of the array. See ECMA-262, section 15.4.4.7.
function ArrayPush() {
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.push");

  var array = TO_OBJECT(this);
  var n = TO_LENGTH(array.length);
  var m = arguments.length;

  // Subtract n from kMaxSafeInteger rather than testing m + n >
  //
...

Continue reading →


Custom RxJS 5 operators

While still in beta, I think RxJS 5 is absolutely awesome! One of the most underrated features of RxJS 4 is (or was?) the ability to define custom operators using let. While let is still supported in RxJS 5, it’s more elegant to define custom operators using regular functions and apply them using the proposed :: operator.

You can read more about the this-binding syntax in the ES7 proposal. Essentially it defines a nicer syntax for applying an unbound function to an arbitrary object.

Let’s say we want to define a custom operator that increments numbers by a fixed constant:

ArrayObservable.create([1, 2, 3])
  ::map(x => x + 5)
  .subscribe(x => console.log(x)) // => 6, 7, 8

We might want to extract out ::map(x => x + 5) into a reusable factory that creates an observable that can be applied to the ArrayObservable:

function increment (plus) {
  return this::map(x => x + plus)
}
...

Continue reading →


Simple animated bar charts using D3 and data-attributes

D3 is incredible powerful, but sometimes all you need is a bar chart. This snippet allows you to define one in a very declarative way.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
  .chart {
    height: 70px;
    width: 300px;
    border-bottom: 1px solid ccc;
    display: block;
    margin: 1em;
  }
  .chart .bar {
    fill: ccc;
  }
</style>
<svg class="chart" data-bar-chart data-data="23,43,10,13,10,20,30,23,43,10,13,10,20,30" data-bar-width="15"></svg>
<svg class="chart" data-bar-chart data-data="19,65,23,31,32,44,5,32,23,23,54,65" data-bar-width="15"></svg>
<svg class="chart" data-bar-chart data-data="34,43,65,21,5,43,43,32,32,12,31,32,12,32,23,12" data-bar-width="15"></svg>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

  $('[data-bar-chart]').each(function (i, svg) {
    var
...

Continue reading →


Minimal Node.JS logger for 12-factor apps

A twelve-factor app never concerns itself with routing or storage of its output stream. It should not attempt to write to or manage logfiles. Instead, each running process writes its event stream, unbuffered, to stdout. During local development, the developer will view this stream in the foreground of their terminal to observe the app’s behavior.

  • from 12factor.net/logs

Done. This is all you need (dependencies: lodash and color):

// Usage:
// var logger = require('./logger');
// logger.debug('Debug message');
// logger.info('Info message');
// logger.warn('Warn message');
// logger.error('Error message');
// logger.addLevels({
//   silly: 'white'
// });
// logger.silly('Silly message');
//
// Further reading:
// * http://12factor.net/logs

var colors = require('colors'),
    _ = require('lodash');

var makeLogFunction = function (color, level) {
  return function (msg) {
...

Continue reading →


How I hacked the Bower Registry and what I learned from it

Bower is a front-end package manager created at Twitter. It has about 20k active users and solves a real problem: Front-end package management. Two weeks ago, I stumbled upon a huge security risk allowing me to manipulate the underlying database and execute malicious code. In this post I’m going to explain the vulnerability I discovered.

Why it was vulnerable

The way Bower validates a package is by checking if the corresponding Git repo actually exists. Since Git has a command for that, they decided to use git ls-remote [repo]. This isn’t such a bad idea, the problem was the way it was implemented in lib/validURL.js:

module.exports = function(url, cb) {
    var exec = require('child_process').exec;

    exec('git ls-remote ' +  url).on('exit', function(exitCode) {
        cb(exitCode === 0);
    });
};

The usage of exec in Node.JS is a HUGE security risk! Oftentimes, it can be...

Continue reading →


Linked List without a single if-statement? - Challenge accepted!

// PoC: Implemented methods: addToTail(value), removeHead() => value, contains(value) => boolean
var tail = {
  next: this,
  removeHead: function () {
    return null;
  },
  contains: function (value) {
    return false;
  },
  addToTail: function (value) {
    return new Node(value);
  }
};

var Node = function (value, next) {
  this.value = value;
  this.next = next || tail;
};

Node.prototype.addToTail = function (value) {
  this.next = this.next.addToTail(value);
  return this;
};

Node.prototype.contains = function (value) {
  // Ok, condition...
  return this.value === value ? true : this.next.contains(value);
};

var LinkedList = function () {
  this.head = tail;
};

LinkedList.prototype.addToTail = function (value) {
  this.head = this.head.addToTail(value);
};

LinkedList.prototype.removeHead = function () {
  var oldHead = this.head;
  this.head = oldHead.next;
  return
...

Continue reading →


Simple Domainhacks using Node.JS

Coming up with good domain names is hard. This Node.JS script takes the hassle out of finding them by using the built in dictionary, which is available on every mac by default. Simply define the top level domains you want the script to consider (e.g. co for every .co, io for every .io domain etc.), save it and run it using node domainhacks.js.

var fs = require('fs');

var words = fs.readFileSync('/usr/share/dict/words', {
    encoding: 'utf8'
}).split('\n');

var tlds = ['co', 'com', 'io', 'de', 'it'];

var results = [];

for (var i = 0; i < words.length; i++) {
    var wordArray = words[i].split('');
    for (var j = 0; j < tlds.length; j++) {
        var tld = tlds[j];
        var lastLetters = wordArray.slice(-tld.length).join('');
        if (lastLetters === tld) {
            wordArray.splice(-tld.length, 0, '.');
            results.push(wordArray.join(''));
        }
    }
}
...

Continue reading →


Storing nested objects in Redis

Since Redis supports the usage of a Hash Tables, one dimensional JavaScript-like objects can be modeled it quite easily. The problem though is that hash tables can’t be nested - at least in Redis.

Assume we have the following JavaScript object:

var house = {
  roof: {
    color: 'black'
  },
  street: 'Market',
  buildYear: '1996'
};

This object could be stored in Redis using two different approaches:

  1. Storing the object as a JSON string using SET house:1 "{....}"

    This approach was fairly common before Redis started supporting Hash Tables. There is nothing wrong with this solution. Parsing and stringifying objects is usually not a performance issue and having the option to store nested objects is really convenient. There is only one major drawback: You can not retrieve parts of the object. The only way to access the stored data is by doing a GET house:1. You can not specify the...

Continue reading →


Introducing The NERD Stack

Don’t be MEAN! Be a friendly NERD!

During my 2 day Hackathon project and the subsequent short project phase at Hack Reactor, I needed an easy to use stack suited for agile development. Typically, people choose the popular MEAN Stack for this type of job. But since I dislike the idea of having to follow a pre-defined boilerplate with lots of overhead (just look at the Yeoman generators), I decided to start completely from scratch and not rely on any opinionated frameworks at all. Finally, I decided to choose the following stack, which is - in my opinion - very well suited for rapid prototyping while guaranteeing high-reliability, scalability and performance (so many buzz words in one sentence -wohahaha!).

Without further blabla, here is the stack:

  • Node.JS

    Node.JS is very well suited for rapid prototyping. Since I needed to have the ability to crawl the [BitTorrent Mainline DHT...

Continue reading →