NaN messes with sorting

I’m building some dynamic table sorting. Looks like NaN values are messing with the sorting. For the sake of the example, let’s use an array of number-like strings. Try pasting this in your console.

(function() {
  var numbers = '19 26 63 twelve 83 106 hundred zero 12'.split(' ');
  return numbers.sort();
})();
// ["106", "12", "19", "26", "63", "83", "hundred", "twelve", "zero"]

The resulting array is as expected, since the values are still strings.

Let’s parse those values as integers, using a compare function in sort.

(function() {
  var numbers = '19 26 63 twelve 83 106 hundred zero 12'.split(' ');
  function parse( value ) {
    return parseInt( value );
  }
  return numbers.sort( function( a, b ) {
    return parse( a ) < parse( b );
  });
})();
// ["63", "26", "19", "twelve", "106", "83", "hundred", "zero", "12"]

This looks just random. I believe what’s happening is how a NaN value from parseInt('foo') messes with the comparison. Comparing any number with NaN will return false.

14 > NaN
// false
NaN > 14
// false

Oh JavaScript, you so cray.

My solution is to account for NaN in the parser.

(function() {
  var numbers = '19 26 63 twelve 83 106 hundred zero 12'.split(' ');
  function parse( value ) {
    value = parseInt( value );
    value = isNaN( value ) ? Infinity : value;
    return value;
  }
  return numbers.sort( function( a, b ) {
    return parse( a ) > parse( b );
  });
})();
// ["12", "19", "26", "63", "83", "106", "twelve", "hundred", "zero"]

You don’t have to munge NaN as Infinity, but this at least treats the value as a number that can be properly compared.

Function.prototype.bind

Modernizr 2.5 added lots of robust feature detects and tests, but perhaps its most convienent feature is the addition of a Function.prototype.bind polyfill. In short, .bind() allows you to set this within a function.

As I employ prototypal objects and class methods a lot, I’m using .bind() a bunch. It’s helpful within setTimeout:

function ClassAct() {
  this.generation = Math.floor( Math.random() * 10 + 4 );
  this.name = 'James J. Jones, the ' + this.generation + 'th.';
}

ClassAct.prototype.sayHello = function() {
  console.log('Gday! I am ' + this.name );
};

// old, ugly way
ClassAct.prototype.sayDelayedHello = function() {
  // can't use `this` in here, because it will be set to the `window` object
  // have to hack it with local `_this` var
  var _this = this;
  setTimeout( function() {
    _this.sayHello();
  }, 1000 );
};

// with Function.prototype.bind()
ClassAct.prototype.sayDelayedHello = function() {
  setTimeout( this.sayHello.bind( this ), 1000 );
};

Or, you could use it for quick and easy event handling:

function ClassAct() {
  // say hello on click
  // without .bind( this ), `this` in sayHello() will not be ClassAct instance
  document.addEventListener( 'mousedown', this.sayHello.bind( this ), false );
}

See it in action: here’s a fiddle to compare using .bind() within class methods: Without Function.prototype.bind and with Function.prototype.bind.

Slicing arguments

In the jQuery Plugins Authoring tutorial, Ralph Holzmann details an intriguing pattern for plugin methods:

var args = Array.prototype.slice.call( arguments, 1 );
return methods[ method ].apply( this, args );
// (edited for clarity)

As the tutorial explains, this pattern is what enabled jQuery UI plugins to have multiple methods. Indeed, If you look deep within the coils of jQuery UI widget factory, you’ll find it there as well:

var args = slice.call( arguments, 1 );
instance[ options ].apply( instance, args );
// (again, edited for clarity)

I had thought of this argument-slicing method pattern just as another bit of JavaScript witch-craft that seemed to work, but I had no comprehension of why.

Today, I’m working on a sort of particle/field class and this pattern finally clicked. Here’s what I’m working with

// field has multiple particles
function Field() {
  this.particles = [];
  for ( var i=0; i < max; i++ ) {
    this.particles.push( new Particle( i ) );
  }
}

// particles have methods
function Particle( index ) {
  this.index = index;
}

Particle.prototype.logIndex = function() {
  console.log( this.index );
}

If I want logIndex on each particle in a field, I would have to loop through each particle and call its method.

Field.prototype.logParticleIndexes = function() {
  for ( var i=0, len=this.particles.length; i < len; i++ ) {
    this.particles[i].logIndex();
  }
}

This is all fine and well when you only have a couple methods in a field that have to iterate over each particle. But you could create another method that was more flexible, and trigger a method passed in from an argument.

Field.prototype.eachParticleDo = function( methodName ) {
  for ( var i=0, len=this.particles.length; i < len; i++ ) {
    this.particles[i][ methodName ]();
  }
}

myField.eachParticleDo('logIndex');

But if the particle has method that require arguments, we’ll need a way to pass those arguments in.

Particle.prototype.setColor = function( color ) {
  this.elem.style.backgroundColor = color;
};

This is where argument-slicing comes in.

Field.prototype.eachParticleDo = function( methodName ) {
  // pass in any other arguments after `methodName`
  var args = Array.prototype.slice.call( arguments, 1 );
  var particle;
  for ( var i=0, len = this.particles.length; i < len; i++ ) {
    particle = this.particles[i];
    // first argument, particle, is what `this` will be inside function
    // second argument is the arguments for that function
    particle[ methodName ].apply( particle, args );
  }
};

myField.eachParticleDo( 'setColor', 'blue' );

Let’s break down what’s going on up there. In order to get any arguments after the first one, methodName, we need to remove methodName from arguments. With a normal array, we could use ary.slice( 1 ). But because arguments is a bizarre array-like object, we need to use an equally bizarre method to slice it. For more on this, See Sebastiano Armeli’s Understanding Array.prototype.slice.apply(arguments) in JavaScript.

Now that the arguments are in a proper array, they can be used as the arguments with .apply(). Per flatline on Stack Overflow What is the difference between call and apply?:

The main difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly.

Nice. Here’s a quick particle demo with eachParticleDo in place.

See fiddle: Particle field with .eachParticleDo

Try opening up the raw fiddle with your console and enter.

myField.eachParticleDo( 'setColor', 'red' )

Varry var var

John Schulz turned me on to the code style of using var for every variable. This goes against most other code styles (see learn.jquery.com and Idiomatic JavaScript), which advise using one var, and listing following variables with commas.

// typically recommend
var firstName = 'Ryan',
    lastName = 'Gosling',
    age = 31,
    isAlive = true;

// multiple vars
var firstName = 'Ryan';
var lastName = 'Gosling';
var age = 31;
var isAlive = true;

At first I gawked at this style, but after using it for two months, I’m sticking with it. Using multiple vars have a couple benefits:

  • Easier to add more variables, no need to change any trailing comma or semi-colon.
  • Eliminates unnecessary git commit diffs, where a line has changed only because you changed a trailing semi-colon or comma.
  • Easier to read (IMO). var is a reserved keyword, so it jumps out when syntax highlighted.
  • Eliminates awkward tab spacing underneath the var. It only lines up if your tabs are 4 spaces wide.
  • [Per JFSIII] Helps collaboration, other devs might miss the change of semi-colon and accidentally add a global variable.

If you’re worried about bloating your code with all the superfluous vars, that should be taken care of when using a proper minifier.

Ignore initial popstate

Within Mike Taylor’s demo for Introducing the HTML5 History API, you’ll find this note:

window.addEventListener('popstate', function(e){
 // be nice to Chrome, the spec changed
 // and they haven't caught up yet
 // http://code.google.com/p/chromium/issues/detail?id=63040
 if (history.state){
   self.loadImage(e.state.path, e.state.note);
 }
}, false);

Per Chromium issue 63040, Chrome dispatches a popState event on initial page load. This was okay when HTML5 history was first introduced, but then the spec changed. It’s been over a year, and the bug still persists.

The easiest hack/solution, as proposed in comment 11, is to add the popstate listener right after the initial page load, in a setTimeout.

setTimeout( function() {
  window.addEventListener( 'popstate', myPopStateHandler, false );
}, 500 );

I’m weary of throwing a setTimeout in for a resolution, always seems like a kludge. But for now, hey it works.

Edit 5 Jan 2012 - delay of 500ms, cause dang that first pop state sticks around

isFinite

isFinite() is a top-level function (like isNaN()) that “Evaluates an argument to determine whether it is a finite number.” JFSIII pointed this out to me, debugging my code. I got lazy checking a numeric value was not undefined and had something like this:

// check if value is defined
if ( value ) {
  // do stuff..
}

The problem was that 0 would be a proper value, but it is evaluated as falsey in the above conditional.

!!0
// >> false
isFinite(0)
// >> true

// check if value is numeric
if ( isFinite(value) ) {
  // do stuff
}

isFinite() does not specifically check if the value is a number, as it returns true for booleans.

isFinite('foo')
// >> false
isFinite(function(){})
// >> false
isFinite(true)
// >> true
isFinite(false)
// >> true

Inspecting DOM object properties

I like taking a peek at native DOM objects like Element and Node using the console’s dir function.

dir( Element )

Then I crack open prototype see all the base properties and methods that native constructor has.

Element prototype

I discovered Element.contains() this way.

Returning to stop the function

I’ve been using return more to stop logic inside a function. See PPK: Returning to stop the function.

// within conditional
function doStuff() {
  var myCondition = checkCondition();
  if ( !myCondition ) {
    // do
    // lots
    // of
    // stuff
  }
}

// proceed if condition is met
function doStuff() {
  var myCondition = checkCondition();
  // don't proceed if not myCondition
  if ( !myCondition ) {
    return;
  }
  // do
  // lots
  // of
  // stuff
}

The benefit is that the subsequent code isn’t all held within the conditional, thus breaking it out of an unnecessary nest… like an newborn eagle on its first flight.

This stuff drives me crazy because I want to use awesome ternary magic BUT it’s practically the definition of the phrase “excessive trickiness.” I feel like your example, while elegant, would make other devs at my company hit me with hammers if they had to read or edit it later. Sigh.

Doug Avery

lerp

Here’s a basic utility function I’ve been using to calculate positions in a transforming object with multiple transforms. I know the start and end positions of each transform — this returns a value in-between given a percentage.

// returns interpolated value between
// A and B, where A = 0%, and B = 100%
var lerp = function( a, b, percent ) {
  return a + percent * ( b - a );
};

lerp( -10, 180, 0.5 ) // returns 85

Lerp is short for linear interpolation.

Nothing too impressive, but I’m saving this ‘cause I forget it every time I need it.