Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You should use two functions: the first to parse the mask, and then second to randomly choose names.</p> <p>Parsing the mask is straightforward enough. A regular expression can be used to retrieve an array of all the keys. Then you can loop through these performing the replacements.</p> <pre><code>function names(mask, callback) { var replaced = mask; //get an array of all the keys (with braces) var keys = mask.match(/{[mflr]}/g); for (var i=0; i&lt;keys.length; i++) { //extract the "f" from "{f}" var type = keys[i].charAt(1); //make the replacement replaced = replaced.replace(keys[i], getNameFromObject(type)); } callback(replaced); } </code></pre> <p>The role of the second function is to choose a name from the object of names, given a certain type. In the question, this object has the identifier "names". This is also the identifier of the function that parses the mask. I recommend renaming the object to something similar to "allNames" because it will avoid possible namespace conflicts and is more expressive of the nature of the object.</p> <p>As suggested, Math.random() and Math.floor() are used to choose a random index of a name. You should not use Math.ceil(), as this might cause an off-by-one error, or require subtraction by one.</p> <pre><code>function getNameFromObject(type) { if (type == 'r') type = (Math.random() &gt; 0.5)? 'm' : 'f'; //assuming that the object has the type of name being requested //NOTE: "allNames" is used as the identifier of the data object var possibleNames = allNames[type]; //assuming the arrays can't be empty var randomIndex = Math.floor(Math.random() * possibleNames.length); return possibleNames[randomIndex]; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload