Skip to content

Commit

Permalink
group-pm: fix colorHashFromString
Browse files Browse the repository at this point in the history
colorHashFromString() now considers all characters in the string. It
can also now return colors with no red component in it. Also fixed the
cases where the function returned #NaN for very long or very short
strings.

[ray: Minor copyedits to commit message.]

Fixes: #3985
  • Loading branch information
Maskedman99 authored and rk-for-zulip committed Apr 13, 2020
1 parent 4559548 commit fc00fab
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
12 changes: 10 additions & 2 deletions src/utils/__tests__/color-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,21 @@ describe('foregroundColorFromBackground', () => {

describe('colorHashFromString', () => {
test('returns a 6 digit hex number to use as a color ', () => {
const hash = colorHashFromString('John Doe');
expect(hash).toHaveLength(7);
expect(colorHashFromString('')).toHaveLength(7);
expect(colorHashFromString('😃')).toHaveLength(7);
expect(colorHashFromString('John Doe')).toHaveLength(7);
expect(colorHashFromString('abcdefghijklmnopqrstuvwxyz'.repeat(50))).toHaveLength(7);
});

test('produces the same output for the same input', () => {
const hash1 = colorHashFromString('John Doe');
const hash2 = colorHashFromString('John Doe');
expect(hash1).toEqual(hash2);
});

test('produces different output for similar inputs', () => {
const hash1 = colorHashFromString('John Doe, Juan Pérez');
const hash2 = colorHashFromString('John Doe, Jean Dupont');
expect(hash1).not.toEqual(hash2);
});
});
10 changes: 4 additions & 6 deletions src/utils/color.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,9 @@ export const foregroundColorFromBackground = (color: ColorValue): 'black' | 'whi
export const colorHashFromString = (name: string): string => {
let hash = 0;
for (let i = 0; i < name.length; i++) {
hash = hash * 31 + name.charCodeAt(1);
hash = hash * 31 + name.charCodeAt(i);
hash %= 0x1000000;
}
let colorHash = hash % 0xffffff;
if (colorHash < 0x100000) {
colorHash += 0x100000;
}
return `#${colorHash.toString(16)}`;

return `#${hash.toString(16).padStart(6, '0')}`;
};

0 comments on commit fc00fab

Please sign in to comment.