我们希望为angularJS,NodeJs,MongoDB应用中的用户分配一种独特的颜色。我们的想法是能够分配和识别具有独特颜色的用户列表(100或更多)。
有什么想法吗?
答案 0 :(得分:1)
在我看来,这个想法是以数学和可重复的方式计算颜色。好处是不必将此颜色存储在数据库中,而是让您的应用程序计算它:
这是fiddle
//HASH FUNCTION
String.prototype.hashCode = function() {
let hash = 0, i, chr, len;
if (this.length === 0) return hash;
for (i = 0, len = this.length; i < len; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
let users = [
{id: 111, name: 'John Doe'},
{id: 220, name: 'John Doe'},
{id: 305, name: 'John Doe'},
{id: 306, name: 'John Doe'},
{id: 310, name: 'Jane Doe'},
{id: 315, name: 'Jane Doe'},
{id: 320, name: 'Jane Doe'}
];
let hashes = [];
users.map((user) => {
//CALCULATE HASH
let hash = (user.id + user.name).hashCode() + '';
//CONVERT HASH TO NUMBER
let total = 0;
for (let i = 0; i < hash.length; i++) {
if (Number(hash[i])) {
total += Number(hash[i]);
}
}
hashes.push(total);
});
//PICK YOUR COLORS
let colors = ['#FFEBEE', '#FFCDD2', '#EF9A9A', '#E57373', '#EF5350', '#F44336', '#E53935', '#D32F2F', '#C62828', '#B71C1C', '#FF8A80', '#FF5252', '#FF1744', '#D50000', '#FCE4EC', '#F8BBD0', '#F48FB1', '#F06292', '#EC407A', '#E91E63', '#D81B60', '#C2185B', '#AD1457', '#880E4F', '#FF80AB', '#FF4081', '#F50057', '#C51162', '#F3E5F5', '#E1BEE7', '#CE93D8', '#BA68C8', '#AB47BC', '#9C27B0', '#8E24AA', '#7B1FA2', '#6A1B9A', '#4A148C', '#EA80FC', '#E040FB', '#D500F9', '#AA00FF', '#EDE7F6', '#D1C4E9', '#B39DDB', '#9575CD', '#7E57C2', '#673AB7', '#5E35B1', '#512DA8', '#4527A0', '#311B92', '#B388FF', '#7C4DFF', '#651FFF', '#6200EA', '#E8EAF6', '#C5CAE9', '#9FA8DA', '#7986CB', '#5C6BC0', '#3F51B5', '#3949AB', '#303F9F', '#283593', '#1A237E', '#8C9EFF', '#536DFE', '#3D5AFE', '#304FFE', '#E3F2FD', '#BBDEFB', '#90CAF9', '#64B5F6', '#42A5F5', '#2196F3', '#1E88E5', '#1976D2', '#1565C0', '#0D47A1', '#82B1FF', '#448AFF', '#2979FF', '#2962FF', '#E1F5FE', '#B3E5FC', '#81D4FA', '#4FC3F7', '#29B6F6', '#03A9F4', '#039BE5', '#0288D1', '#0277BD', '#01579B', '#80D8FF', '#40C4FF', '#00B0FF', '#0091EA', '#E0F7FA', '#B2EBF2', '#80DEEA', '#4DD0E1', '#26C6DA', '#00BCD4', '#00ACC1', '#0097A7', '#00838F', '#006064', '#84FFFF', '#18FFFF', '#00E5FF', '#00B8D4', '#E0F2F1', '#B2DFDB', '#80CBC4', '#4DB6AC', '#26A69A', '#009688', '#00897B', '#00796B', '#00695C', '#004D40', '#A7FFEB', '#64FFDA', '#1DE9B6', '#00BFA5'];
//ASSOCIATE COLOR AND USER
let result = [];
hashes.map((item, i) => {
let person = {
name: users[i].name,
color: colors[item % colors.length]
}
result.push(person);
});
希望它可以给你一些想法:)