首页 > 解决方案 > 使单词有意义的颜色

问题描述

我们有 Az 字符和 abcdef0-9 颜色。

我需要在同一个单词上始终获得相同的颜色,(苹果总是红色,汽车总是绿色,汽车 - 总是橙色) - 即使单词有 1 或 3 个字母,我每次都希望看到相同的颜色。在我的函数中,如果没有数学颜色的字母,我有随机函数。

请帮我升级功能并将数学随机替换为类似get letter index in alphabet divide on colors char position或其他的东西

export function MakeSenseColor(str) {
  if(!str && typeof str !== 'string') return '';

  const chars1 = 'abc6789';
  const chars2 = 'abcdef0123456789';

  const Digits = 'qйwцeуrкtеyнuгiшoщpзaхsъdфfыgвhаjпkрlоzлxдcжvэbяnчmсмитьбю1234567890';
  const splittedStr = str.split('').map((s,i,arr) => {
    const charPos = s && (Digits.split('')).indexOf(`${s}`.toLowerCase());

    if(!charPos || charPos === -1) return '0';

    if (charPos >= 0 ) {
      const char = (charPos * chars2.length) / Digits.length
      const charColor = (char * 6) / arr.length;

      return chars2[parseInt(charColor)];
    }

    return '0';
  });

  let color = '#';

  for (let i = 0; color.length < 7; i++) {
    const add = splittedStr[i%6] || chars1.charAt(Math.floor(Math.random() * chars1.length))

    color = color + add;
  }

  return color;
}

标签: javascriptmathrandomcolors

解决方案


我只是对字符串进行哈希处理并使用它来生成一个指示颜色的十六进制字符串。此处的哈希实现https://stackoverflow.com/a/52171480/1358308对我来说看起来相对不错。

// borrowed from https://stackoverflow.com/a/52171480/1358308
function cyrb53(str, seed = 0) {
    let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
    for (let i = 0, ch; i < str.length; i++) {
        ch = str.charCodeAt(i);
        h1 = Math.imul(h1 ^ ch, 2654435761);
        h2 = Math.imul(h2 ^ ch, 1597334677);
    }
    h1 = Math.imul(h1 ^ (h1>>>16), 2246822507) ^ Math.imul(h2 ^ (h2>>>13), 3266489909);
    h2 = Math.imul(h2 ^ (h2>>>16), 2246822507) ^ Math.imul(h1 ^ (h1>>>13), 3266489909);
    return 4294967296 * (2097151 & h2) + (h1>>>0);
};

function MakeSenseColor(str) {
    // hash the string and convert to hex
    let hash = cyrb53(str).toString(16);

    // just use the last 6 characters and prepend character to indicate color
    return '#' + hash.slice(-6);
}

这给了我独特而一致的结果:

  • '苹果' =#002f86
  • '汽车' =#684a21
  • '汽车' =#c10e83

这些颜色与您在问题中指出的颜色不同,但我想您可以硬编码一些您关心的颜色。


推荐阅读