UNPKG

wix-style-react

Version:
29 lines (23 loc) 876 B
import { avatarColorList } from './constants'; /* stringToColor returns a different color for each string. ** Each string will ALWAYS receives the same color, so the color will always be consistent per string **/ var stringToColor = function stringToColor(name) { if (!name) { return; } var hash = stringToNumber(name); var index = hash % avatarColorList.length; // this sets an index between 0 and array.length. return avatarColorList[index]; }; /* stringToNumber creates a number for each string. ** for example the string: "Hi" number will be 177. ** charCode of "H" = 72, charCode of "i" = 105. 72 + 105 = 177 ** This creates a unique number for each string **/ var stringToNumber = function stringToNumber(str) { return str.split('').reduce(function (acc, _char) { return acc + _char.charCodeAt(); }, 0); }; export default stringToColor;