How can i assign user a number between 1 to 150 using their name or id or hash. For example, John = 28 and it will always be the same and not random. How can i do this when the input is theoretically unlimited.
Asked
Active
Viewed 65 times
-4
-
Does this answer your question? [Generate a Hash from string in Javascript](https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript) – pilchard Jul 03 '21 at 12:51
-
Why not assign the first username of it's kind a random number. When another user signs up, you make a check if there exists a user with that same username and then assign them the same number. i.e the first John gets a random number, when the second john signs up, search your db for 'John' and give the new John the same number. – Samuel Anyanwu Jul 03 '21 at 12:53
-
Are you using storage of any sort? – Peter Smith Jul 03 '21 at 12:57
2 Answers
1
A very simple approach (because your reason for doing this isn't given) is to total the numerical value of each character in the string and take the modulus of 150:
function assignNumber(str) {
let total = 0;
for (let i=0; i<str.length;i++) {
total+= str.charCodeAt(i);
}
return( total % 150)+1; // Mod 150 gives a result between 0 and 149. Add one to adjust the range.
}
let str = "Now is the time for all good men to come to the aid of the party";
console.log(assignNumber(str)); // 37

Wai Ha Lee
- 8,598
- 83
- 57
- 92

Tangentially Perpendicular
- 5,012
- 4
- 11
- 29
0
I'm a beginner in js so I tried my best:- hope this will help u
'use strict';
function randomNumberGenerator()
{
const randomNumber =Math.floor(Math.random() * 150);
return randomNumber;
}
function numberAssign(employeeName)
{
const employee = employeeName;
const randomNumber =randomNumberGenerator()
return `${employee} = ${randomNumber}`;
}
const result=numberAssign('john');
console.log(result);

Harshal
- 199
- 3
- 8
-
This will allocate a random number to each name submitted, so 'John' will get different numbers on each call (probably). The OP seems to want the same number for the same source string, so that 'John' is always 28, or whatever... – Tangentially Perpendicular Jul 03 '21 at 13:13