mpneuried
6/18/2015 - 7:10 AM

Color Hashing: Generate a hex color out of a given string. This works in Node and in the browser

Color Hashing: Generate a hex color out of a given string. This works in Node and in the browser

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" )