Using _.random. Can I pass a function as a parameter?

I am trying to make a function where I randomly get a date or a string “foo”, but I keep getting zero as a response.

var moment = require(‘moment’);
var containter = moment().add(_.random(0, 13),‘months’).format(“MM.YYYY.”);
var variants = [‘foo’, containter];
var option = variants[Math.floor(Math.random()*variants.length)];
pm.environment.set(“someFoo”, option);

Seems to work ok for me. This is pretty much the same code in a loop.

var moment = require("moment");

for (let i = 0; i < 10; i++) {
    var containter = moment().add(_.random(0, 13),"months").format("MM.YYYY.");
    var variants = ["foo", containter];
    var option = variants[Math.floor(Math.random()*variants.length)];
    console.log(option);
}

image

Perhaps check the quotes, as I had to change a few to normal double quotes to get it to work.

You can also use the lodash sample method instead of the math.random(), array.length and math.floor() method.

The library is built into Postman and you don’t have to declare it.

var moment = require("moment");

for (let i = 0; i < 10; i++) {
    var containter = moment().add(_.random(0, 13),"months").format("MM.YYYY.");
    var variants = ["foo", containter];
    var option = _.sample(variants);
    console.log(option);
}

Than you. I see it doesn’t work without it, but why do I need a loop?

I understand it like this

// calculates a random date
var containter = moment().add(_.random(0, 13),“months”).format(“MM.YYYY.”);

//defines the variants
var variants = [“foo”, containter];

//chooses one of the variants
var option = _.sample(variants);

//we use the chosen variant
console.log(option);

You don’t need a loop. I added a loop just to prove that its generating random data.

If you run it manually once or twice, then there is a chance, that it will just show “foo”.

This just repeats the same code four times - no loop.

    var moment = require("moment");
    
    var containter = moment().add(_.random(0, 13),"months").format("MM.YYYY.");
    var variants = ["foo", containter];
    var option = _.sample(variants);
    console.log(option);

    var containter = moment().add(_.random(0, 13),"months").format("MM.YYYY.");
    var variants = ["foo", containter];
    var option = _.sample(variants);
    console.log(option);

    var containter = moment().add(_.random(0, 13),"months").format("MM.YYYY.");
    var variants = ["foo", containter];
    var option = _.sample(variants);
    console.log(option);

    var containter = moment().add(_.random(0, 13),"months").format("MM.YYYY.");
    var variants = ["foo", containter];
    var option = _.sample(variants);
    console.log(option);

image

I see. I did get “foo” 4 times, so I thought it doesn’t work. Thanks! :slight_smile: