Skip to content

Commit

Permalink
group-pm: fix colorHashFromString
Browse files Browse the repository at this point in the history
colorHashFromString() now considers all charecters 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
empty strings.

Fixes: #3985
  • Loading branch information
Maskedman99 committed Mar 27, 2020
1 parent e2359b2 commit 4276aa1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 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);
});
});
7 changes: 2 additions & 5 deletions src/utils/color.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,10 @@ export const foregroundColorFromBackground = (color: ColorValue): 'black' | 'whi

export const colorHashFromString = (name: string): string => {
let hash = 0;
for (let i = 1; i < name.length; i++) {
for (let i = 0; i < name.length; i++) {
hash = hash * 31 + name.charCodeAt(i);
hash %= 0x1000000;
}

let colorHash = hash.toString(16);
colorHash = colorHash.padStart(6, '0');

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

0 comments on commit 4276aa1

Please sign in to comment.