10

I've a for loop in javascript shown below. How to convert it to lodash for loop? In such scenarios using lodash is advantageous over javascript for loop?

I've not used lodash much. Hence please advice.

for (var start = b, i = 0; start < end; ++i, ++start) {
// code goes here
}
Temp O'rary
  • 5,366
  • 13
  • 49
  • 109

3 Answers3

12

You can use lodash range
https://lodash.com/docs/4.17.4#range

_.range(5, 10).forEach((current, index, range) => {
    console.log(current, index, range)
})

// 5, 0, [5, 6, 7, 8, 9, 10]
// 6, 1, [5, 6, 7, 8, 9, 10]
// 7, 2, [5, 6, 7, 8, 9, 10]
// 8, 3, [5, 6, 7, 8, 9, 10]
// 9, 4, [5, 6, 7, 8, 9, 10]
// 10, 5, [5, 6, 7, 8, 9, 10]
iamandrewluca
  • 3,411
  • 1
  • 31
  • 38
7

I will imagine that b = 3 and end = 10 if I run your code and print the variables here is what I will get:

var b = 3;
var end = 10;

for (var start = b, i = 0; start < end; ++i, ++start) {
  console.log(start, i);
}

> 3 0
> 4 1
> 5 2
> 6 3
> 7 4
> 8 5
> 9 6

To perform this with lodash (or underscore) I will first generate an array with range then iterate over it and gets the index on each iteration.

Here is the result

var b = 3;
var end = 10;

// this will generate an array [ 3, 4, 5, 6, 7, 8, 9 ]
var array = _.range(b, end); 

// now I iterate over it
_.each(array, function (value, key) {
  console.log(value, key);
});

And you will get the same result. The complexity is the same as the previous one (so no performance issue).

IxDay
  • 3,667
  • 2
  • 22
  • 27
  • 1
    So, no performance or memory advantage, right? better to go with vanilla javascript for loop? – Temp O'rary Jul 07 '15 at 09:30
  • 1
    If you will use a lot of data manipulation lodash is always better than vanilla javascript. see http://filimanjaro.com/blog/2014/introducing-lazy-evaluation/ for perfomance questions. It is cleaner and more adaptive than vanilla js. If you only need a for loop it does not require a full library, but if you build a real application manipulating data, this lib is quite mandatory. – IxDay Jul 07 '15 at 09:49
0

It seems there is no lodash way for writing loose for loops (those not iterating over a collection), but here is a simplified version of it:

for (var i = 0; i < end - b; i++) {
      var start = i + b;
      // code goes here
}
Binkan Salaryman
  • 3,008
  • 1
  • 17
  • 29
  • OK. In that case, I will wait for some time until more suggestions come in and if no more suggestions come in I will mark yours as solution. – Temp O'rary Jul 06 '15 at 14:05