Jun 15

#nodejs module for parsing key/value strings

Since my regexp test on parsing a string was a success, I created a #nodejs module for parsing strings. And the funny part, I scrapped the regexp 🙂 It now supports multiple keys and multiple values.

So you can do something like this:

var res = ps.parse('"foo bar" bar,"foo bar"=1 bar,"foo bar"=bar,"foo bar"');
res = [
   ['foo bar', undefined],
   ['bar', '1'],
   ['foo bar', '1'],
   ['bar', ['bar', 'foo bar']],
   ['foo bar', ['bar', 'foo bar']]

You can find the code at GitHub or as a npm module

Jun 15

#javascript and parsing param string

Got a little challenge parsing strings like:

Little brown="and yellow" fox=1 jumps over=lazy dog

I wanted to split it into an array with key/value pairs, so the result would be:

var res =
[ [ 'Little', undefined ],
  [ 'brown', 'and yellow' ],
  [ 'fox', '1' ],
  [ 'jumps', undefined ],
  [ 'over', 'lazy' ],
  [ 'dog', undefined ] ]

And here the regexp guy in me popped out and wanted to go for a short version. I ended up with

var text = 'Little brown="and yellow" fox=1 jumps over=lazy dog';

var res = text.match(/([^=\s]+="[^"]+")|\S+/g).map(function (p) {
    return p.match(/^([^=\s]*)(?:="?([^"]*)"?)?$/).splice(1, 2);


The first one (/([^=\s]+="[^"]+")|\S+/g) splits the string into an array of param|param=value|param="value with space". The second one (/^([^=\s])(?:="?([^"])"?)?$/) split that array into separate arrays which contains key,value and remove the possible double quote on the value. Since match return all the splits, I splice out the values from the new array, 1 and 2.

And there you go.

You can find the last version at GitHub

PS: This rely on that array.map() exists, which it does in #nodejs

Jun 15

@nodejs and object sort speed

I was coding a scheduler and needed a sorted array of the schedules, so I started to investigate the speed of different sorting variants I could use.

I created a little program (https://gist.github.com/flogvit/c9df93ab37ca4dbd2d7f) to test 4 different variants.

For the test I created an array with 100000 objects { v: num }, where num is 100000 to 1. v is the value I want to sort on. Then I did the sort 10 times for each variant, and then again running this 5 times.

The first variant was standard compare (compare):

function compare(a, b) {
  if (a.v < b.v)
    return -1;
  if (a.v > b.v)
    return 1;
  return 0;


The second was a value only version doing the minus variant (compareValue):

function compareValue(a, b) {
  return a.v - b.v;


Third variant is using async (async):

   async.sortBy(sortarray, function (entry, callback) {
      callback(null, entry.v);
    }, function (err, results) {
      sortarray = results;

And last variant is using underscore (underscore):

sortarray = _.sortBy(sortarray, 'v');

The result where smaller is better:

compare 36.00
compareValue 36.58
underscore 50.84
async 228.48

And the full output from each run:

$ node --expose-gc sort.js
Running compare for average 30.8 ms
Running compareValue for average 38 ms
Running async for average 227 ms
Running underscore for average 51.8 ms
Running compare for average 38.8 ms
Running compareValue for average 36.6 ms
Running async for average 230.7 ms
Running underscore for average 49.5 ms
Running compare for average 37.2 ms
Running compareValue for average 35.2 ms
Running async for average 234.7 ms
Running underscore for average 52.6 ms
Running compare for average 37.4 ms
Running compareValue for average 37.1 ms
Running async for average 224.4 ms
Running underscore for average 49.4 ms
Running compare for average 35.8 ms
Running compareValue for average 36 ms
Running async for average 225.6 ms
Running underscore for average 50.9 ms
May 15

Reformat your source code with #IntelliJ

Writing correctly formatted code isn't easy to do all the time. So what do you do when you have eg written your json files like:

{ "test": "testing"
, "bla": "blabla"
, "yo": "yo to you"}

and want it to be:

  "test": "testing",
  "bla": "blabla",
  "yo": "yo to you"

You go into your file and press alt-win-l (alt-cmd-l on mac). Voila. It's formatted correctly.

But then you understand that you have a lot of files that needs to be reformatted. Well, select all you files in the project window (shift/alt) and when in the project window press alt-win-l. You probably get a popup asking for optimizing, rearranging etc. Just leave them and press OK. Voila. All files correctly formatted.

Now you can go and get your well earned coffee break.

May 15

IntelliJ and TODO

When you code, it's often you come up with an idea or shortcoming of your function. It's easy to code on and think you can remember it later. You don't, trust me.

So what do you do when you're in an editor like IntelliJ? Well, you add a TODO: entry.

// TODO: This should probably be shortened
// TODO: Perhaps add yield on each result to support generators?
// TODO: Add callback?
var fibonacci = function(pos) {
    if (pos===0) return 0;
    if (pos===1) return 1;
    var result = 1;
    var last = 0;
    for(var i=2;i<=pos;i++) {
        var newLast = result;
        result = result+last;
        last = newLast;
    return result;


We came up with three ideas when writing that function. Then you switch to another file, do you stuff. Before you know it, it's gone two weeks since you added the TODO blocks. So what do you do in IntelliJ? You press win-6 (Windows) or cmd-6 (Mac) and get your TODO-list up and running. Choose Project (or File or Scope), and find all your TODOs. And if you wonder how to remove the list again, just press the same win-6, cmd-6

May 15

Node.js and random port

Sometimes you need to open a random port on your node server. You can of course try a random one to see if it fails, but a npm module makes this easy:

npm install portfinder
var pf = require('portfinder');
var http = require('http');

// If you want to change the first port to check
pf.basePort = 9000; // default is 8000

pf.getPort(function(err, port) {
  if (err) return; // handle error
  console.log("I'm now listening on port "+port);

More information about the module is found at npmjs.com