1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
var
util = require('util'),
color_map = [
'black',
'red',
'green',
'yellow',
'blue',
'magenta',
'cyan',
'white'
],
color_weights = [
[0, 0, 0],
[255, 0, 0],
[0, 255, 0],
[255, 255, 0],
[0, 0, 255],
[255, 0, 255],
[0, 255, 255],
[255, 255, 255]
],
reset = '\x1b[30m';
function hex_to_rgb ( hex ) {
var
base_16;
if ( hex.indexOf('#') === 0 ) {
hex = hex.slice(1);
}
base_16 = parseInt(hex, 16);
if ( isNaN(base_16) ) {
base_16 = 0;
}
return [
( base_16 >> 16 ) & 255,
( base_16 >> 8 ) & 255,
base_16 & 255
];
}
function get_fitness ( source, target ) {
return Math.abs(source - target);
}
function get_closest_color ( red, green, blue ) {
var
current_color,
best_color = null,
current_fit,
best_fit = 765,
index = color_map.length;
while ( index -- ) {
current_color = color_weights [index];
current_fit = get_fitness(red, current_color [0]) + get_fitness(green, current_color [1]) + get_fitness(blue, current_color [2]);
if ( current_fit <= best_fit ) {
best_fit = current_fit;
best_color = color_map [index];
}
}
return best_color;
}
function generate ( color ) {
var
resolved_color,
index;
function colorize ( text ) {
if ( typeof text !== 'string' ) {
text = util.format(text);
}
return resolved_color + text + reset;
}
index = color_map.indexOf(color);
if ( index !== -1 ) {
resolved_color = '\x1b[3' + index + 'm';
}
else {
resolved_color = reset;
}
return colorize;
}
function create_color ( color, green, blue ) {
var
index,
resolved_color;
if ( typeof color === 'string' ) {
if ( color [0] === '#' ) {
resolved_color = get_closest_color.apply(null, hex_to_rgb(color));
}
}
else if ( typeof color === 'number' ) {
resolved_color = get_closest_color(color, green, blue);
}
else {
resolved_color = reset;
}
return generate(resolved_color);
}
color_map.map(function ( item ) {
create_color [item] = generate(item);
});
module.exports = create_color;
|