Created
May 4, 2020 20:00
-
-
Save masyukun/faf0663b520aba1ea68a240dce1776fa to your computer and use it in GitHub Desktop.
Color-hash any string to a stable color
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// DONE: Translated to XQuery | |
if (!String.prototype.hashCode){ | |
String.prototype.hashCode = function() { | |
var hash = 0, i, chr, len; | |
if (this.length == 0) return hash; | |
for (i = 0, len = this.length; i < len; i++) { | |
chr = this.charCodeAt(i); | |
hash = ((hash << 5) - hash) + chr; | |
hash |= 0; // Convert to 32bit integer | |
} | |
return hash; | |
}; | |
}; | |
if (!String.prototype.pad){ | |
String.prototype.pad = function(length) { | |
let s = this + ""; | |
while (s.length < length) s = "0" + s; | |
return s; | |
}; | |
}; | |
// I've been spoiled by XQuery's fn:last() function... | |
if (!Array.prototype.last){ | |
Array.prototype.last = function(){ | |
return this[this.length - 1]; | |
}; | |
}; | |
var hashStringToHsvColor = function(string){ | |
if (typeof(string) == "string") { | |
var hash = string.hashCode(); | |
return { | |
h: (hash & 0xFF0000) >> 16, | |
s: (hash & 0x00FF00) >> 8, | |
v: (hash & 0x0000FF) | |
}; | |
} else { | |
return { | |
h: 0, | |
s: 0, | |
v: 0 | |
}; | |
}; | |
}; | |
/** Accepts values from 0 to 1 */ | |
var HSVtoRGB = function(h, s, v) { | |
var r, g, b, i, f, p, q, t; | |
if (h && s === undefined && v === undefined) { | |
s = h.s, v = h.v, h = h.h; | |
} | |
i = Math.floor(h * 6); | |
f = h * 6 - i; | |
p = v * (1 - s); | |
q = v * (1 - f * s); | |
t = v * (1 - (1 - f) * s); | |
switch (i % 6) { | |
case 0: r = v, g = t, b = p; break; | |
case 1: r = q, g = v, b = p; break; | |
case 2: r = p, g = v, b = t; break; | |
case 3: r = p, g = q, b = v; break; | |
case 4: r = t, g = p, b = v; break; | |
case 5: r = v, g = p, b = q; break; | |
} | |
return { | |
r: Math.floor(r * 255), | |
g: Math.floor(g * 255), | |
b: Math.floor(b * 255) | |
}; | |
}; | |
var string2color = function(string) { | |
var hsv = hashStringToHsvColor(string); | |
var rgb = HSVtoRGB(hsv.h/255, hsv.s/255, hsv.v/255); | |
return "#" + rgb.r.toString(16).pad(2) + rgb.g.toString(16).pad(2) + rgb.b.toString(16).pad(2); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment