Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript randoms?

I have an object that looks something like

names = {
  m: [
       'adam',
       'luke',
       'mark',
       'john'
     ],
  f: [
       'lucy',
       'mary',
       'jill',
       'racheal'
     ],
  l: [
       'smith',
       'hancock',
       'williams',
       'browne'
     ]
};

What I want to do is.

I get a string that looks like

{m} {l} is a male name, so {f} {l} is a female name, {r} {l} must me a either/or(random) gender name

And I want it to randomly be populated from the correct keys.

so you might get

luke browne is a male name, so racheal smith is a female name, mary browne must be a either/or(random) gender name

How would I go about doing this?

the function skeleton would look something like

function names(mask, callback){}

and the last line of the code would be something like callback(replaced)

like image 639
Hailwood Avatar asked Mar 22 '26 16:03

Hailwood


2 Answers

You can use Math.random() to get a random value between 0 and 1. From there you can use Math.ceil() or Math.floor() with multiplication to get the desired range of values.

like image 64
nss Avatar answered Mar 25 '26 05:03

nss


There are two parts of JavaScript that you need to know for this question:

  1. Math.random(), which is the only way to generate random numbers within JavaScript. It generates a number between 0 and 1; you can get a random integer between 0 and n - 1 with Math.floor(Math.random() * n).
  2. Regular expressions, for getting the "template" strings out of the mask, and for performing the replacement. The expression mask.match(/{.}/)[0] will give you the first template string in the mask (e.g. '{m}' in the given case).

To replace the '{m}' in mask with 'foo', you'd write

mask = mask.replace(/{m}/, 'foo');

Put all the concepts above together in a while (mask.match(/{.}/) loop, and voila!

like image 21
Trevor Burnham Avatar answered Mar 25 '26 04:03

Trevor Burnham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!