Binary to decimal converter in JavaScript
Flawed exercise

Before I begin, I would like to point out that the exercise is flawed:


The task is not really converting the input from a binary to a decimal representation.  Rather, it is to convert it to a number, whose conventional string representation is rendered in base 10.  The test suite included this test:


xit('11010 is decimal 26', function() {
  expect(new Binary('11010').toDecimal()).toEqual(26);
});



… which could also have been written as:

xit('11010 is twenty-six', function() {
  expect(new Binary('11010').toDecimal()).toEqual(0x1a);
});

It is bad practice to return 0 for new Binary('junk').toDecimal().  Acceptable results would be to either throw an exception or return Number.NaN.


Review

Your invalidInput function either returns true or falls off the end.  Good practice would be to name it isInvalidInput, and have it explicitly return true or false.  Better yet, reverse the sense and call it isValidInput.  Even better, don't expose the validation function as a method at all — you don't really need one.

this.binary.split('').reverse() and Math.pow(…) seem extravagant.

Suggested solution

// Constructor
var Binary = function(binary) {
  this.binary = binary;
  this.base = 2;
};

Binary.prototype.toDecimal = function() {  // &lt;-- Method name is a misnomer!
  var output = 0;
  for (var i = 0; i &lt; this.binary.length; i++) {
    output *= 2;
    switch (this.binary.charAt(i)) {
      case '0': break;
      case '1': output += 1; break;
      default:  return 0;   // &lt;-- This sucks, but the test suite requires it!
    }
  }
  return output;
}