Collect.js whenNotEmpty() Function
Last Updated :
12 Jan, 2021
Collect.js is a fluent and convenient wrapper for working with arrays and objects. The whenNotEmpty() function executes the callback function when the collection is not empty.
Installation: Install the Collect.js module using the following command:
npm install --save collect.js
Syntax:
collection.whenNotEmpty(callback)
Parameters: This function takes only one parameter i.e. the callback function which executes if the collection is not empty.
Return Value: This function returns the new collection object.
Example 1: Filename-index.js
Javascript
const collect = require( 'collect.js' )
var myCollection = [
'Good Morning' ,
'Good Evening' ,
'Good Afternoon'
]
const collection = collect(myCollection);
collection.whenNotEmpty(item => item.push( 'Good Night' ));
console.log(collection.all());
|
Run the index.js file using the following command:
node index.js
Output:
[ 'Good Morning', 'Good Evening', 'Good Afternoon', 'Good Night' ]
Example 2: Filename-index.js
Javascript
const collect = require( 'collect.js' )
var myCollection = [ 'One' , 'Two' , 'Three' ]
const collection = collect(myCollection);
collection.whenNotEmpty((item) => {
item.push( 'Four' )
item.push( 'Five' )
item.push( 'Six' )
});
console.log(collection.all());
|
Run the index.js file using the following command:
node index.js
Output:
[ 'One', 'Two', 'Three', 'Four', 'Five', 'Six' ]
Reference: https://collect.js.org/api/whenNotEmpty.html
Share your thoughts in the comments
Please Login to comment...