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'
     ]
};

I want to do it.

I get a line that looks like

{m} {l} is a masculine name, so {f} {l} is a feminine name, {r} {l} must be me / or a (random) gender name

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

so you can get

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

How should I do it?

function skeleton will look something like this:

function names(mask, callback){}

and the last line of code will look like callback(replaced)

+3
source share
5 answers

Math.random() 0 1. Math.ceil() Math.floor() , .

+3

JavaScript, :

  • Math.random(), JavaScript. 0 1; 0 n - 1 Math.floor(Math.random() * n).
  • "" . mask.match(/{.}/)[0] (, '{m}' ).

'{m}' mask 'foo',

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

while (mask.match(/{.}/) voila!

+2

-, , :

/\{(\w)\}/g

, {r}, . :

names.r = names.m.concat(names.f);

names.r names.m, names.f. string.replace .

, , , " ".

function replaceNames(mask, callback) {
    callback(mask.replace(/\{(\w)\}/g, function(all, category) {
        var arr = names[category];
        return arr[Math.floor(Math.random() * arr.length)];
    }));
}
+1

- :

function randomName(names){
    var _names = [];
    for(i in names) _names.push(i);
    var random = Math.floor(Math.random()*_names.length);
    if(random) random -= 1; // only m and f
    return names[_names[random]][Math.floor(Math.random()*names[_names[random]].length)];
    }
0

: , .

. . .

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<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);
}

, , . "". , . "allNames", .

, Math.random() Math.floor() . Math.ceil(), " " .

function getNameFromObject(type) {

    if (type == 'r')
        type = (Math.random() > 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];
}
0

Source: https://habr.com/ru/post/1796723/


All Articles