Collect.js is a fluent and convenient wrapper for working with arrays and objects. The tap() function accepts the collection as a parameter and without affecting the collection it allows the user to tap into the collection at a specific point and do anything with the item.
Installation:Â Install the Collect.js module using the following command:
npm install --save collect.js
Syntax:Â Â
collection.tap(callback)
Parameters: This function takes only one parameter i.e. the callback function which executes as per user need.
Return Value: This function returns the new collection object.
Example 1: Filename-index.jsÂ
// Requiring module
const collect = require('collect.js')
// User defined collection
var myCollection = [2, 4, 3, 1, 5]
// Function call
var newCollection = collect(myCollection)
.tap((collection) => {
// Printing collection
console.log(collection.all());
})
console.log(newCollection)
Run the index.js file using the following command:
node index.js
Output:
[ 2, 4, 3, 1, 5 ]
Collection { items: [ 2, 4, 3, 1, 5 ] }Example 2: Filename-index.jsÂ
// Requiring module
const collect = require('collect.js')
// User defined collection
var myCollection = [-1,2,0,25]
// Sorting and displaying result
collect(myCollection).sort().tap((collection) => {
console.log(collection.all());
})
Run the index.js file using the following command:
node index.js
Output:
[ -1, 0, 2, 25 ]
Reference: https://collect.js.org/api/tap.html