Skip to content

Instantly share code, notes, and snippets.

@sandcastle
Created February 22, 2024 03:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sandcastle/bb8762a43e48d3e5d68d97c30bb5ed0a to your computer and use it in GitHub Desktop.
Save sandcastle/bb8762a43e48d3e5d68d97c30bb5ed0a to your computer and use it in GitHub Desktop.
String to color converter
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