The _.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 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 underscore.js contrib library to be installed.
The underscore.js contrib library can be installed using npm install underscore-contrib –save
Example 1: In this example, we will generate an array using this method.
Javascript
// Defining underscore contrib variable var _ = require( 'underscore-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 generating function.
Javascript
// Defining underscore contrib variable var _ = require( 'underscore-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 ]