-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
60 lines (53 loc) · 1.87 KB
/
index.ts
File metadata and controls
60 lines (53 loc) · 1.87 KB
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
export class String2HexCodeColor {
defaultShadePercentage = 0;
constructor(defaultShadePercentage?: number) {
if(defaultShadePercentage) this.defaultShadePercentage = defaultShadePercentage;
}
shadeColor(color: string, percent: number | undefined) {
if (!percent) {
percent = this.defaultShadePercentage;
}
const f = parseInt(color.slice(1), 16);
const t = percent < 0 ? 0 : 255;
const p = percent < 0 ? percent * -1 : percent;
const R = f >> 16;
const G = f >> 8 & 0x00FF;
const B = f & 0x0000FF;
const result = '#' + (0x1000000 + (Math.round((t - R) * p) + R) * 0x10000 +
(Math.round((t - G) * p) + G) * 0x100 + (Math.round((t - B) * p) + B)).toString(16).slice(1);
return result;
}
stringToColor(str: string, shadePercentage?: number) {
if (!str) str = "";
if (str.length<4){
str = str + this.preHash(str).toString();
}
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
let colour = '#';
for (let i = 0; i < 3; i++) {
const value = (hash >> (i * 8)) & 0xFF;
colour += ('00' + value.toString(16)).substr(-2);
}
if (shadePercentage || (this.defaultShadePercentage!==0)){
return this.shadeColor(colour, shadePercentage);
}
return colour;
}
preHash(str: string) {
{
let hash = 0;
if (str.length === 0) {
return hash;
}
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
}
}