Created
June 18, 2015 07:10
-
-
Save mpneuried/3bbfc5ebc28533b9903e to your computer and use it in GitHub Desktop.
Color Hashing: Generate a hex color out of a given string. This works in Node and in the browser
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
hashFnv32a = (str, asString, seed) -> | |
#jshint bitwise:false | |
i = undefined | |
l = undefined | |
hval = (if (seed is `undefined`) then 0x811c9dc5 else seed) | |
i = 0 | |
l = str.length | |
while i < l | |
hval ^= str.charCodeAt(i) | |
hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24) | |
i++ | |
# Convert to 8 digit hex string | |
return ("0000000" + (hval >>> 0).toString(16)).substr(-8) if asString | |
return hval >>> 0 | |
#colorHash = _.memoize ( str )-> # It makes sense to memorize/cache the result | |
colorHash = ( str )-> | |
hash = hashFnv32a(str) | |
r = (hash & 0xFF0000) >> 16 | |
g = (hash & 0x00FF00) >> 8 | |
b = hash & 0x0000FF | |
return "#" + ("0" + r.toString(16)).substr(-2) + ("0" + g.toString(16)).substr(-2) + ("0" + b.toString(16)).substr(-2) | |
colorHash( "abc" ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment