Open In App

Lodash _.iterateUntil() Method

Last Updated : 16 Sep, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The Lodash _.iterateUntil() Method takes two functions, one is used as a result generator, other function used as a stop-check and a seed value say n and returns an array of each generated result.  The operation of _.iterateUntil() method is such that the result generator is passed with the seed value at the start and each subsequent result which will continue until a result fails the check function.

The generator function is feed with the starting seed value and hence array is generated until the stop-check function returns false.

Syntax:

_.iterateUntil(genFunc, checkFunc, seed_val)

Parameters: This method accepts three parameters as mentioned above and described below:

  • genFunc: The function is used as a result generator.
  • checkFunc: The function used as stop-check.
  • seed_val: The value passed to the generator at starting.

Return Value: This method returns a generated array.

Note: This will not work in normal JavaScript because it requires the lodash contrib library to be installed. 

The lodash contrib library can be installed using npm install lodash-contrib –save

Example 1: In this example, we will generate an array using this method.

Javascript




// Defining lodash contrib variable
var _ = require('lodash-contrib'); 
   
// Defining Generating function
var genFunc = 
    function(n) { 
        return n + 1; 
    }
  
// Defining stop-check function
var checkFunc = 
    function(n) { 
        return n < 11; 
    }
  
// Generating an array
var arr = _.iterateUntil(genFunc, checkFunc, 1);
console.log("Generated Array : ");
console.log(arr);


Output:

Generated Array :
[
  2, 3, 4,  5, 6,
  7, 8, 9, 10
]

Example 2: In this example, we will generate an array of 2’s table using this method by giving a seed value 0 and returning n+2 from the generating function.

Javascript




// Defining lodash contrib variable
var _ = require('lodash-contrib'); 
   
// Defining Generating function
var genFunc = 
    function(n) { 
        return n + 2; 
    }
// Defining stop-check function
var checkFunc = 
    function(n) { 
        return n < 21; 
    }
// Generating an array
var arr = _.iterateUntil(genFunc, checkFunc, 0);
console.log("Generated Array : ");
console.log(arr);


Output:

Generated Array :
[
   2,  4,  6,  8, 10,
  12, 14, 16, 18, 20
]    


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads