unique-window-colors icon indicating copy to clipboard operation
unique-window-colors copied to clipboard

Bad hash function

Open kk-kien opened this issue 2 years ago • 1 comments

Given two strings which only differs at the last character, the hash code does not differ much. As a result, the resulted colors of these two strings are very similar.

e.g.

hashCode('my-repo-1') = 1331048407
hashCode('my-repo-2') = 1331048408

Here is the source code I found in the repo:

// https://www.designedbyaturtle.co.uk/convert-string-to-hexidecimal-colour-with-javascript-vanilla/
// Hash any string into an integer value
// Then we'll use the int and convert to hex.
function hashCode(str: string) {
  var hash = 0;
  for (var i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
  }
  return hash;
}

From my experience, quite a lot of developers clone one repo and add suffixes like -1, -2, etc. That's because we want to avoid switching between branches.

My suggestion is to use a better hash function. For example, you can use this lightweight PRNG library, https://www.npmjs.com/package/random-seed.

kk-kien avatar Mar 29 '22 04:03 kk-kien

I somehow always get green even if the name of my repo is quite different. On Ubuntu if that makes any difference

nickph7 avatar Dec 06 '23 15:12 nickph7