This exercise with a test suite is from here. I did not intend to use ES6 features, it's plain old JavaScript. That's why I seek advice more on the good practices, performance side, than modern syntax. Basically anything to make this code more elegant, without ES6.
// Constructor
var Binary = function(binary) {
this.binary = binary;
this.base = 2;
};
// Transform the string input in a reversed array
Binary.prototype.reverseInput = function() {
return this.binary.split('').reverse();
};
// Handle the conversion to decimal
Binary.prototype.toDecimal = function() {
var output = 0;
binaryArray = this.reverseInput();
if (this.invalidInput()) {
return output;
}
for (var i = 0, j = binaryArray.length; i < j; i++) {
output += binaryArray[i] * Math.pow(this.base, i);
}
return output;
}
// Check if any character is not a 1 or a 0
Binary.prototype.invalidInput = function() {
for (var i = 0, j = this.binary.length; i < j; i++) {
if (this.binary[i] != '0' && this.binary[i] != '1') {
return true;
}
}
}
module.exports = Binary;