Created
February 22, 2024 03:50
-
-
Save sandcastle/bb8762a43e48d3e5d68d97c30bb5ed0a to your computer and use it in GitHub Desktop.
String to color converter
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 stringToColor(str) { | |
// Predefined set of colors | |
const colors = ['#FF5733', '#33FF57', '#3357FF', '#F833FF', '#FF8333', '#33FFF8']; | |
// Simple hash function | |
let hash = 0; | |
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 | |
} | |
// Ensure the hash is a positive number | |
hash = Math.abs(hash); | |
// Map the hash to one of the predefined colors | |
const colorIndex = hash % colors.length; | |
return colors[colorIndex]; | |
} | |
// Example usage | |
console.log(stringToColor("hello")); // One color | |
console.log(stringToColor("world")); // Consistently returns the same color for "world" | |
console.log(stringToColor("world")); // Consistently returns the same color for "world" | |
console.log(stringToColor("hello world")); // Different string, different color |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment