Skip to content

Commit 28c153c

Browse files
committed
refactor(functions): Make sure only named exports are used (usernameToColor)
Signed-off-by: Ferdinand Thiessen <opensource@fthiessen.de>
1 parent 0a60d10 commit 28c153c

File tree

3 files changed

+58
-61
lines changed

3 files changed

+58
-61
lines changed

src/functions/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,4 @@ export * from './emoji/index.ts'
1010
export * from './isDarkTheme/index.ts'
1111
export * from './preloadImage/index.ts'
1212
export * from './reference/index.js'
13-
export { default as usernameToColor } from './usernameToColor/index.js'
13+
export { usernameToColor } from './usernameToColor/index.js'

src/functions/usernameToColor/index.js

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,60 @@
33
* SPDX-License-Identifier: AGPL-3.0-or-later
44
*/
55

6-
export { default } from './usernameToColor.js'
6+
import { GenColors } from '../../utils/GenColors.js'
7+
8+
import md5 from 'md5'
9+
10+
/**
11+
* Generate a color from a username
12+
* Originally taken from https://github.com/nextcloud/server/blob/master/core/js/placeholder.js
13+
*
14+
* @param {string} username Display name or user id to generate from
15+
* @return {{ r: number, g: number, b: number }} the RGB color
16+
*/
17+
export function usernameToColor(username) {
18+
// Normalize hash
19+
let hash = username.toLowerCase()
20+
21+
// Already a md5 hash?
22+
if (hash.match(/^([0-9a-f]{4}-?){8}$/) === null) {
23+
hash = md5(hash)
24+
}
25+
26+
hash = hash.replace(/[^0-9a-f]/g, '')
27+
28+
const steps = 6
29+
const finalPalette = GenColors(steps)
30+
31+
/**
32+
* Convert a string to an integer evenly
33+
*
34+
* @param {string} hash The hash to convert
35+
* @param {number} maximum Largest number allowed
36+
*/
37+
function hashToInt(hash, maximum) {
38+
let finalInt = 0
39+
const result = []
40+
41+
// Splitting evenly the string
42+
for (let i = 0; i < hash.length; i++) {
43+
// chars in md5 goes up to f, hex:16
44+
result.push(parseInt(hash.charAt(i), 16) % 16)
45+
}
46+
47+
// Adds up all results
48+
for (const j in result) {
49+
finalInt += result[j]
50+
}
51+
52+
// chars in md5 goes up to f, hex:16
53+
// make sure we're always using int in our operation
54+
return parseInt(parseInt(finalInt, 10) % maximum, 10)
55+
}
56+
return finalPalette[hashToInt(hash, steps * 3)]
57+
}
58+
59+
/**
60+
* @deprecated use the named export of `usernameToColor` instead
61+
*/
62+
export default usernameToColor

src/functions/usernameToColor/usernameToColor.js

Lines changed: 0 additions & 59 deletions
This file was deleted.

0 commit comments

Comments
 (0)