Reputation: 3826
according to one of StackOverflow topics I tried to create own RGB to HEX colors converter.
I don't know why but instead converting it double RGB numbers.
So when input is rgb(0, 128, 192)
it console out #00128192
.
My code is:
fromRGB: {
toHEX: {
supportFunc: function(number) {
var hex = number.toString(16);
return hex.length == 1 ? '0' + hex : hex;
},
convert: function(r, g, b) {
var lol = '#' + this.supportFunc(r) + this.supportFunc(g) + this.supportFunc(b);
console.log(lol);
}
},
prepareAndExecute: function(color_field) {
// preparing
var numbers = color_field.match(/\d+/g);
if(numbers.length == 3) {
this.toHEX.convert(numbers[0], numbers[1], numbers[2]);
} else {
alert('wrong RGB number format');
}
//this.toHSL(preparedValue);
}
}
I execute prepare function, lol
variable is the one that should contains converted color in HEX format.
What is wrong with my code, why it doesn't work?
Upvotes: 3
Views: 693
Reputation: 31682
Explanation:
It's because you're passing strings not numbers to supportFunc
.
The result of match
in prepareAndExecute
is an array of strings, thus when you call toString
in supportFunc
, you are calling String.prototype.toString
(not Number.prototype.toString
) which return the string as is.
Solution:
In supportFunc
, convert number
to a number before using toString
:
var hex = Number(number).toString(16); // using Number to convert a string to a number (you can use parseInt or unary + if you like)
or convert them before passing them to convert
:
this.toHEX.convert(+numbers[0], +numbers[1], +numbers[2]); // using unary +
Upvotes: 1