How to use the times function from lodash

Find comprehensive JavaScript lodash.times code examples handpicked from public code repositorys.

lodash.times is a function in the Lodash library that generates an array of a specified length by invoking a given function a certain number of times.

7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
* @example
*
* var diceRolls = _.times(3, _.partial(_.random, 1, 6));
* // => [3, 6, 4]
*
* _.times(3, function(n) { mage.castSpell(n); });
* // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively
*
* _.times(3, function(n) { this.cast(n); }, mage);
* // => also calls `mage.castSpell(n)` three times
fork icon73
star icon711
watch icon29

+ 5 other calls in file

375
376
377
378
379
380
381
382
383
384
// Intercept meeting materials request
const materialsUrl = (new URL(event.agenda.url)).pathname
const materialsInfo = {
  url: event.agenda.url,
  slides: {
    decks: _.times(5, idx => ({
      id: 100000 + idx,
      title: faker.commerce.productName(),
      url: `/meeting/${meetingData.meeting.number}/materials/slides-${meetingData.meeting.number}-${event.acronym}-${faker.internet.domainWord()}`,
      ext: ['pdf', 'html', 'md', 'txt', 'pptx'][idx]
fork icon194
star icon199
watch icon41

+ 7 other calls in file

How does lodash.times work?

In Lodash, lodash.times is a function that generates an array of a specified length by invoking a given function a certain number of times. When you call lodash.times with a number n and a function func, it invokes func n times and creates an array of the results. The value returned by each invocation of func is added to the array in the order in which it was called. For example, if you call lodash.times(3, () => Math.random()), Lodash will invoke the anonymous function three times, each time generating a random number between 0 and 1. Lodash will then create an array of these three random numbers and return it. lodash.times is useful for generating arrays of a specific length with predictable or randomized values. By passing in different functions to lodash.times, you can generate arrays with a variety of values or patterns. Overall, lodash.times is a simple but powerful function in Lodash that makes it easy to generate arrays of a specific length with customizable values.

37
38
39
40
41
42
43
44
45
46
user = databaseBuilder.factory.buildUser();
targetProfile = databaseBuilder.factory.buildTargetProfile();
campaign = databaseBuilder.factory.buildCampaign({
  targetProfileId: targetProfile.id,
});
campaignSkills = _.times(8, (index) => {
  return databaseBuilder.factory.buildCampaignSkill({
    campaignId: campaign.id,
    skillId: skillIds[index],
  });
fork icon48
star icon192
watch icon20

381
382
383
384
385
386
387
388
389
390
module.exports.templateSettings    = _.templateSettings;
module.exports.ternary             = _.ternary;
module.exports.third               = _.third;
module.exports.throttle            = _.throttle;
module.exports.thru                = _.thru;
module.exports.times               = _.times;
module.exports.titleCase           = _.titleCase;
module.exports.toArray             = _.toArray;
module.exports.toDash              = _.toDash;
module.exports.toFinite            = _.toFinite;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

Ai Example

1
2
3
4
5
6
7
const _ = require("lodash");

// Generate an array of 10 random numbers
const randomArray = _.times(10, () => Math.random());

// Log the array to the console
console.log(randomArray);

In this example, we're using lodash.times to generate an array of 10 random numbers. We pass in the number 10 as the first argument to lodash.times to specify the length of the array, and a function that generates a random number between 0 and 1 using Math.random as the second argument. lodash.times then invokes the anonymous function 10 times, generating a random number each time, and creates an array of the 10 random numbers. We log the array to the console using console.log. When you run this code, you'll see that an array of 10 random numbers is printed to the console. Note that the values in the array will be different each time you run the code, since Math.random generates a new random number each time it is called.

71
72
73
74
75
76
77
78
79
80

beforeEach('populate redis', function populateRedis() {
  const audience = this.users.config.jwt.defaultAudience;
  const promises = [];

  ld.times(totalUsers, () => {
    const user = createUser(this.users.flake.next());
    const item = saveUser(this.users.redis, USERS_METADATA, audience, user);
    promises.push(item);
  });
fork icon13
star icon8
watch icon7

+ 9 other calls in file

4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
interleave: _.weave,

// Returns an array of a value repeated a certain number of
// times.
repeat: function(t, elem) {
  return _.times(t, function() { return elem; });
},

// Returns an array built from the contents of a given array repeated
// a certain number of times.
fork icon3
star icon2
watch icon1

+ 235 other calls in file

971
972
973
974
975
976
977
978
979
980
981
982
983
console.log(stubString); // => ''


const stubTrue = _.stubTrue();
console.log(stubTrue); // => true


const times = _.times(3, String);
console.log(times); // => ['0', '1', '2']


const toPath = _.toPath('a.b.c');
console.log(toPath); // => ['a', 'b', 'c']
fork icon0
star icon4
watch icon0

+ 15 other calls in file

144
145
146
147
148
149
150
151
152
153
    getTokens(sentence.tokenization).map((token) =>
      range(token.textSpan.start, token.textSpan.ending)
    )
  )
);
const char2tok = times(communication.text.length).map(() => []);
tok2char.forEach((tokenTextIndices, globalTokenIndex) =>
  tokenTextIndices.forEach((textIndex) =>
    char2tok[textIndex].push(globalTokenIndex)
  )
fork icon2
star icon3
watch icon0

110
111
112
113
114
115
116
117
118
119
console.log(req.params.count)
let count = (req.params.count==null ||req.params.count==undefined) ? 10 : req.params.count;

db.remove({}, { multi: true });

_.times(count, (index) => {
    let contact = {
        "firstName": faker.name.firstName(),
        "lastName": faker.name.lastName(),
        "email": faker.internet.email(),
fork icon0
star icon0
watch icon1

+ 3 other calls in file

193
194
195
196
197
198
199
200
201
202
it('supports just running queries', function () {
  const pool = new Pool({ poolSize: 9 })
  const text = 'select $1::text as name'
  const values = ['hi']
  const query = { text: text, values: values }
  const promises = _.times(30, () => pool.query(query))
  return Promise.all(promises).then(function (queries) {
    expect(queries).to.have.length(30)
    return pool.end()
  })
fork icon0
star icon0
watch icon1

+ 5 other calls in file

573
574
575
576
577
578
579
580
581
582
    countColumn = 'count(*)';
    break;
}
let count;
const inserts = [];
_.times(40, function(i) {
  inserts.push({
    email: 'email' + i,
    first_name: 'Test',
    last_name: 'Data',
fork icon0
star icon0
watch icon1

+ 2 other calls in file

115
116
117
118
119
120
121
122
123
124
  expect(sheet.rowCount).toEqual(oldRowCount + 1);
});

it('will update sheet.rowCount if new rows are added (while not in insert mode)', async () => {
  const oldRowCount = sheet.rowCount;
  const dataForMoreRowsThanFit = _.times(INITIAL_ROW_COUNT, () => ({
    numbers: '999', letters: 'ZZZ',
  }));
  const newRows = await sheet.addRows(dataForMoreRowsThanFit);
  const updatedRowCount = sheet.rowCount;
fork icon0
star icon0
watch icon1

17
18
19
20
21
22
23
24
25
26
27
};


describe("Acceptance tests for Pool class", () => {
  describe("can make a cube pool", () => {
    it("should return a sealed cube pool with length equal to player length", () => {
      const cubeList = times(720, constant("island"));
      const playersLength = 8;
      const playerPoolSize = 90;
      const got = Pool.SealedCube({cubeList, playersLength, playerPoolSize});
      assert.equal(got.length, playersLength);
fork icon0
star icon0
watch icon1

+ 3 other calls in file

28
29
30
31
32
33
34
35
36
37
38
39
40


// const randomVal = () => {
//   return nodash.ceiling(Math.random() * 100);
// };


// const arr = lodash.times(15, randomVal);
// console.log(arr, "arr");


// const original = {
//   name: "rajeev",
fork icon0
star icon0
watch icon0

+ 9 other calls in file

45
46
47
48
49
50
51
52
53
54
const versionResult = yield pool.query('SHOW server_version_num')
const version = parseInt(versionResult.rows[0].server_version_num, 10)
const queryColumn = version < 90200 ? 'current_query' : 'query'

const queryText = 'SELECT COUNT(*) as counts FROM pg_stat_activity WHERE ' + queryColumn + ' = $1'
const queries = _.times(20, () => pool.query(queryText, [queryText]))
const results = yield Promise.all(queries)
const counts = results.map((res) => parseInt(res.rows[0].counts, 10))
expect(counts).to.eql(_.times(20, (i) => 1))
return yield pool.end()
fork icon0
star icon0
watch icon0

60
61
62
63
64
65
66
67
68
69
var bucketMins = (opts && opts.bucketMins) || 5;
var bucketMsecs = times.mins(bucketMins).msecs;

var lastSGVMills = sbx.lastSGVMills();

var buckets = _.times(bucketCount, function createBucket (index) {
  var fromMills = lastSGVMills - offset - (index * bucketMsecs);
  return {
    index: index
    , fromMills: fromMills
fork icon0
star icon0
watch icon0

1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
  return res.write(chunk)
}

// note - this is unintentionally invalid JS, just try executing it anywhere
write('function ')
_.times(100, () => {
  return write('😡😈'.repeat(10))
})

write(' () { }')
fork icon0
star icon0
watch icon0

137
138
139
140
141
142
143
144
145
146
147
148


run_test("random_int", () => {
    const min = 0;
    const max = 100;


    _.times(500, () => {
        const val = util.random_int(min, max);
        assert.ok(min <= val);
        assert.ok(val <= max);
        assert.equal(val, Math.floor(val));
fork icon0
star icon0
watch icon0

642
643
644
645
646
647
648
649
650
651
it('reacts to ENAMETOOLONG errors and tries to shorten the filename', async () => {
  const err = new Error('enametoolong')

  err.code = 'ENAMETOOLONG'

  _.times(50, (i) => fs.outputFileAsync.onCall(i).rejects(err))

  const fullPath = await screenshots.getPath({
    specName: 'foo.js',
    name: 'a'.repeat(256),
fork icon0
star icon0
watch icon0

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)