Friday, December 27, 2024
Google search engine
HomeLanguagesJavascriptUnderscore.js _.iterators.unfoldWithReturn() Method

Underscore.js _.iterators.unfoldWithReturn() Method

With the help of _.iterators.unfoldWithReturn() method, we can get two values from iteration function where unary function is expected to return two values whenever function is invoked by using this method.

Syntax:

_.iterators.unfoldWithReturn(seed, unaryFn)

Return Value: It returns the two values from iteration function.

Note: To execute the below examples, you have to install the underscore-contrib library by using this command prompt and execute the following command.

npm install underscore-contrib

Example 1: In this example, we can see that by using _.iterators.unfoldWithReturn() method, we are able to get the values from iteration function where unary function returns two values whenever iteration function is invoked.




// Defining underscore contrib variable 
var _ = require('underscore-contrib');
  
function isGFG (val) {
    return [val, String(val.length)];
}
  
var geek = _.iterators.unfoldWithReturn("Geeks", isGFG);
  
for(var i = 0; i < 3; i++) {
    console.log(geek());
}


Output:

Geeks
[ 'Geeks', '5' ]
[ [ 'Geeks', '5' ], '2' ]

Example 2:




// Defining underscore contrib variable 
var _ = require('underscore-contrib');
  
function isGFG (val) {
    return [val + 1, val * 5];
}
  
var geek = _.iterators.unfoldWithReturn(1, isGFG);
  
for(var i = 0; i < 2; i++) {
    console.log(geek());
}


Output:

1
[ 2, 5 ]
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments