Monday, December 30, 2024
Google search engine
HomeLanguagesJavascriptCollect.js unlessEmpty() Function

Collect.js unlessEmpty() Function

Collect.js is a fluent and convenient wrapper for working with arrays and objects. The unlessEmpty() 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.unlessEmpty(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




// Requiring module
const collect = require('collect.js')
  
// User defined collection
var myCollection = [1, 2]
  
// Creating collection object
const collection = collect(myCollection);
  
// Callback execution since collection
// object is not empty
collection.unlessEmpty(item => item.push(3));
  
// Printing collection
console.log(collection.all());


Run the index.js file using the following command:

node index.js

Output:

[ 1, 2, 3 ]

Example 2: Filename-index.js 

Javascript




// Requiring module
const collect = require('collect.js')
  
// User defined collection
var myCollection = []
  
// Creating collection object
const collection = collect(myCollection);
  
// No callback execution since
// collection is not empty
collection.unlessEmpty((item) => {
  item.push(1)
  item.push(2)
});
  
// Printing collection
console.log(collection.all());


Run the index.js file using the following command:

node index.js

Output:

[ ]

Reference: https://collect.js.org/api/unlessEmpty.html

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!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments