Open In App

Underscore.js _.iterators.unfoldWithReturn() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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 ]

Last Updated : 28 Oct, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads