Color: combine stringToRgb, namedToRgb and hexToRgb and optimize a bit.

This commit is contained in:
Jonathan Puckey 2011-03-09 14:20:09 +01:00
parent ba42884f57
commit 741652aa9c

View file

@ -65,28 +65,32 @@ var Color = this.Color = Base.extend(new function() {
}; };
function stringToRGB(string) { function stringToRGB(string) {
return string.match(/^#[0-9a-f]{3,6}$/i) if (string.match(/^#[0-9a-f]{3,6}$/i)) {
? hexToRgb(string) var hex = string.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
: namedToRgb(string); if (hex.length >= 4) {
}; var rgb = [];
for (var i = 1; i < 4; i++)
function hexToRgb(string) { rgb.push(parseInt(hex[i].length == 1
var hex = string.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/); ? hex[i] + hex[i] : hex[i], 16) / 255);
if (hex.length >= 4) { return rgb;
var rgb = []; }
for (var i = 1; i < 4; i++) } else {
rgb.push(parseInt(hex[i].length == 1 var hex = namedColors[string];
? hex[i] + hex[i] : hex[i], 16) / 255); if (!hex)
return rgb; throw new Error('The named color "' + string
+ '" does not exist.');
hex = hex.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
if (hex.length >= 4) {
var rgb = new Array(3);
for (var i = 0; i < 3; i++) {
var channel = hex[i + 1];
rgb[i] = parseInt(channel.length == 1
? channel + channel : channel, 16) / 255;
}
return rgb;
}
} }
}; };
function namedToRgb(name) {
var hex = namedColors[name];
if (!hex)
throw new Error('The named color "' + name + '" does not exist.');
return hex && hexToRgb(hex);
};
return { return {
beans: true, beans: true,
@ -146,7 +150,7 @@ var Color = this.Color = Base.extend(new function() {
}, },
getType: function() { getType: function() {
return this._alpha == -1 ? this._colorType : 'a' + this._colorType; return this._colorType;
}, },
getComponents: function() { getComponents: function() {