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)
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.
There are two parts of JavaScript that you need to know for this question:
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).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!
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