I have a table of action logs in my application. I want to assign rows a random colour based on the sessionID of that entry to help see patterns/grouped actions.
I have this so far:
console.log(stringToColorCode('mj3bPTCbIAVoNr93me1I'));
function stringToColorCode(str) {
return '#'+ ('000000' + (Math.random()*0xFFFFFF<<0).toString(16)).slice(-6);
}
However I need to replace Math.random() with my string-integer, are there any techniques for converting a string to a random number that remains consistent with the random string?
Get the desired String. Create an empty StringBuffer object. Convert it into a character array using the toCharArray() method of the String class.
Try reusing the Random objects throughout the loop. Or var color = $"#{random. Next(0x1000000):X6}"; with string interpolation in C# 6.
As requested, posting this as an awswer
var stringHexNumber = ( // 1
parseInt( // 2
parseInt('mj3bPTCbIAVoNr93me1I', 36) // 3
.toExponential() // 4
.slice(2,-5) // 5
, 10) & 0xFFFFFF // 6
).toString(16).toUpperCase(); // "32EF01" // 7
So, what's going on?
3
where 'mj3bPTCbIAVoNr93me1I'
gets converted to an Integer, say x
, by interpreting it as a base-36 number. x
is put into it's exponential form as a String on line 4
. This is because with that many characters, x
can be huge, this example is around 8e30
, so convert it to a form that will be pretty standard. 5
trims off the beginning and end so you'll be left with just digits, e.g. '8.123e+30'.slice(2, -5)
becomes '12'
.2
, where this gets converted back into an Integer again, this time in base 10.6
truncates this number down to the range 0..16777215 (=== 0xFFFFFF)
using a fast bitwise AND. This will also convert NaN
to 0
.7
converts this back into the upper case hex format we are used to seeing colours in, by writing the number in base 16
and changing the case.If you want to use this, you may also want to ensure that the final number is 6
digits and stick a #
on the front, which can be done via
'#' + ('000000' + stringHexNumber).slice(-6); // "#32EF01"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With