Skip to content

Commit d9768e5

Browse files
voidstardbmbostock
authored andcommitted
100% to 125% faster #rgb/#rrggbb string parsing across all platforms. Tests pass. http://jsperf.com/rgb-str-vs-regex
1 parent 086de83 commit d9768e5

1 file changed

Lines changed: 12 additions & 12 deletions

File tree

src/color/rgb.js

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ function d3_rgb_parse(format, rgb, hsl) {
6767
var r = 0, // red channel; int in [0, 255]
6868
g = 0, // green channel; int in [0, 255]
6969
b = 0, // blue channel; int in [0, 255]
70+
value,
7071
m1, // CSS color specification match
7172
m2, // CSS color specification type (e.g., rgb)
7273
name;
@@ -98,20 +99,19 @@ function d3_rgb_parse(format, rgb, hsl) {
9899

99100
/* Hexadecimal colors: #rgb and #rrggbb. */
100101
if (format != null && format.charAt(0) === "#") {
101-
if (format.length === 4) {
102-
r = format.charAt(1); r += r;
103-
g = format.charAt(2); g += g;
104-
b = format.charAt(3); b += b;
105-
} else if (format.length === 7) {
106-
r = format.substring(1, 3);
107-
g = format.substring(3, 5);
108-
b = format.substring(5, 7);
102+
value = parseInt(format.substring(1), 16);
103+
if (!isNaN(value)) {
104+
if (format.length === 4) {
105+
r = (value & 0xf00) >> 4; r = (r >> 4) | r;
106+
g = (value & 0xf0); g = (g >> 4) | g;
107+
b = (value & 0xf); b = (b << 4) | b;
108+
} else if (format.length === 7) {
109+
r = (value & 0xff0000) >> 16;
110+
g = (value & 0xff00) >> 8;
111+
b = (value & 0xff);
112+
}
109113
}
110-
r = parseInt(r, 16);
111-
g = parseInt(g, 16);
112-
b = parseInt(b, 16);
113114
}
114-
115115
return rgb(r, g, b);
116116
}
117117

0 commit comments

Comments
 (0)