Last active
February 17, 2016 11:08
-
-
Save eswak/59df54dcd7397163eaa8 to your computer and use it in GitHub Desktop.
JavaScript string to 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
function str2num (str) { | |
var hash = 0, i, chr, len; | |
if (str == 0) return hash; | |
for (i = 0, len = str.length; i < len; i++) { | |
chr = str.charCodeAt(i); | |
hash = ((hash << 5) - hash) + chr; | |
hash |= 0; | |
} | |
return hash; | |
}; | |
function str2color (str) { | |
var hash = str2num(str); | |
return { | |
r: (hash & 0xFF0000) >> 16, | |
g: (hash & 0x00FF00) >> 9, | |
b: (hash & 0x0000FF), | |
rgba: function() { | |
return 'rgba(' + this.r + ', ' + this.g + ', ' + this.b + ', 1)'; | |
}, | |
hex: function () { | |
return '#' + ((1 << 24) + (this.r << 16) + (this.g << 8) + this.b).toString(16).slice(1); | |
} | |
}; | |
} | |
function uuid2str (uuid) { | |
if (!/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/.test(uuid)) { | |
return null; | |
} | |
var parts = uuid.replace(/\-/g, ''); | |
parts = [ | |
parts.substring(0, 8), | |
parts.substring(8, 16), | |
parts.substring(16, 24), | |
parts.substring(24, 32) | |
].map(str2num); | |
var vowels = [ | |
'a', 'e', 'i', 'o', 'u', | |
'ai', 'eu', 'oi', 'ou' | |
]; | |
var consonants = [ | |
'r', 't', 'y', 'p', 's', 'd', 'f', 'g', 'k', 'l', 'm', 'w', 'v', 'b', 'n', | |
'tr', 'pr', 'sr', 'dr', 'fr', 'gr', 'kr', 'vr', 'br', | |
'bl', 'sl', 'pl', 'kl', | |
'sk', | |
]; | |
var syllables = []; | |
consonants.forEach(function (consonant) { | |
vowels.forEach(function (vowel) { | |
syllables.push(consonant + vowel); | |
}); | |
}); | |
parts = parts.map(function (part, i) { | |
return syllables[Math.abs(part) % syllables.length]; | |
}); | |
return parts.join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment