What is the Deque.push() method in collections in Node.js?

In this shot, we will discuss the Deque.push() function in Node.js. The Deque collection is available in the collections package. There are many data structure implementations in the collections package, including Deque.

Installation

To install the collections Node package, you can run the command below in your local system:

npm i collections

You can also execute the command in the terminal below to install the collections package.

Terminal 1
Terminal
Loading...

Syntax

The syntax of the Deque.push() function is given below:

int push(value);

Parameters

The Deque.push() function accepts the values that need to be pushed to the deque.

Return value

The Deque.push() function returns an integer value that denotes the number of elements in the deque after pushing the specified elements.

Implementation

Once you have the collections package installed, we can move to the implementation and see how the code works.

var Deque = require("collections/deque");
var deque_one = new Deque([1, 2, 3]);
console.log("Number of elements in Deque: ", deque_one.length);
console.log("List before calling push(): ", deque_one.toArray());
var num_elements = deque_one.push(10);
num_elements = deque_one.push("Hello");
num_elements = deque_one.push("Educative.io", "NodeJS", 10.5);
console.log("Number of elements in Deque: ", num_elements);
console.log("List after calling push(): ", deque_one.toArray());

Explanation

  • In line 1, we import the required package.

  • In line 3, we create an object of Deque and add three elements to it.

  • In lines 5-6, we print the number of elements and the current elements present in the Deque.

  • In line 8, we call the push() function and pass the value 10. Here, we store the result of the push() function in a variable called num_elements, which contains the number of elements after pushing the specified elements.

  • In line 9, we again push the value Hello.

  • In line 10, we pass multiple values, as this will help directly push multiple values in one go into our deque.

  • Finally, in lines 12-13, we print the number of elements and the current elements present in the Deque.

So, in this way, we can easily push elements in a Deque data structure in Node.js.

Free Resources