You can only return one value. Use an object. In fact, the whole thing can be made into an object:
Code:
String.prototype.splitEvery = function(n) {
var s = this,
p = [];
while(s.length < 0) {
p.push(s.substr(0, n));
s = s.substr(n);
}
return p;
};
String.prototype.padFront = function(n, c) {
var d = c || "0",
s = this;
while(s.length < n)
s = d + s;
return s;
};
function Colour(r, g, b) {
this.red = r;
this.green = g;
this.blue = b;
}
Colour.fromThreeDigitHex = function(str) {
var rgb = str.substr(1).splitEvery(1);
for(var i = 0; i < rgb.length; ++i)
rgb[i] = parseInt(rgb[i] + rgb[i], 16);
return new Colour(rgb[0], rgb[1], rgb[2]);
};
Colour.prototype.toThreeDigitHex = function() {
return "#" + this.red.toString(16).padFront(2).charAt(0)
+ this.green.toString(16).padFront(2).charAt(0)
+ this.blue.toString(16).padFront(2).charAt(0);
};
Colour.fromSixDigitHex = function(str) {
var rgb = str.substr(1).splitEvery(2);
for(var i = 0; i < rgb.length; ++i)
rgb[i] = parseInt(rgb[i], 16);
return new Colour(rgb[0], rgb[1], rgb[2]);
};
Colour.prototype.toSixDigitHex = function() {
return "#" + this.red.toString(16).padFront(2)
+ this.green.toString(16).padFront(2)
+ this.blue.toString(16).padFront(2);
};
Colour.fromCSSRGB = function(str) {
var rgb = str.substr(4).substr(0, rgb.length - 1).replace(/ /g, "").split(",");
for(var i = 0; i < rgb.length; ++i)
rgb[i] = parseInt(rgb[i], 10);
return new Colour(rgb[0], rgb[1], rgb[2]);
};
Colour.prototype.toCSSRGB = function() {
return "rgb(" + [this.red, this.green, this.blue].join(", ") + ")";
};
Colour.fromString = function(str) {
if(str.charAt(0) === "#" && str.length === 4)
return Colour.fromThreeDigitHex(str);
else if(str.charAt(0) === "#" && str.length === 7)
return Colour.fromSixDigitHex(str);
else if(str.indexOf("rgb(") === 0)
return Colour.fromCSSRGB(str);
else throw new Error("Bad colour passed to Colour.fromString()");
};
Bookmarks