Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Hands-On Data Structures and Algorithms with JavaScript

You're reading from   Hands-On Data Structures and Algorithms with JavaScript Write efficient code that is highly performant, scalable, and easily testable using JavaScript

Arrow left icon
Product type Paperback
Published in Jan 2018
Publisher Packt
ISBN-13 9781788398558
Length 332 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Kashyap Mukkamala Kashyap Mukkamala
Author Profile Icon Kashyap Mukkamala
Kashyap Mukkamala
Arrow right icon
View More author details
Toc

Creating a stack

Now that we know when and why we would want to use a stack, let's move on to implementing one. As discussed in the preceding section, we will use a WeakMap() for our implementation. You can use any native data type for your implementation, but there are certain reasons why WeakMap() would be a strong contender. WeakMap() retains a weak reference to the keys that it holds. This means that once you are no longer referring to that particular key, it gets garbage-collected along with the value. However, WeakMap() come with its own downsides: keys can only be nonprimitives and are not enumerable, that is, you cannot get a list of all the keys, as they are dependent on the garbage collector. However, in our case, we are more concerned with the values that our WeakMap() holds rather than keys and their internal memory management.

Implementing stack methods

Implementing a stack is a rather easy task. We will follow a series of steps, where we will use the ES6 syntax, as follows:

  1. Define a constructor:
class Stack {
constructor() {

}
}
  1. Create a WeakMap() to store the stack items:
const sKey = {};
const items = new WeakMap();

class Stack {
constructor() {
items.set(sKey, [])
}
}
  1. Implement the methods described in the preceding API  in the Stack class:
const sKey = {};
const items = new WeakMap();

class Stack {
constructor() {
items.set(sKey, []);
}

push(element) {
let stack = items.get(sKey);
stack.push(element);
}

pop() {
let stack = items.get(sKey)
return stack.pop()
}

peek() {
let stack = items.get(sKey);
return stack[stack.length - 1];
}

clear() {
items.set(sKey, []);
}

size() {
return items.get(sKey).length;
}
}
  1. So, the final implementation of the Stack will look as follows:
var Stack = (() => {
const sKey = {};
const items = new WeakMap();

class Stack {

constructor() {
items.set(sKey, []);
}

push(element) {
let stack = items.get(sKey);
stack.push(element);
}

pop() {
let stack = items.get(sKey);
return stack.pop();
}

peek() {
let stack = items.get(sKey);
return stack[stack.length - 1];
}

clear() {
items.set(sKey, []);
}

size() {
return items.get(sKey).length;
}
}

return Stack;
})();

This is an overarching implementation of a JavaScript stack, which by no means is comprehensive and can be changed based on the application's requirements. However, let's go through some of the principles employed in this implementation.

We have used a WeakMap() here, which as explained in the preceding paragraph, helps with internal memory management based on the reference to the stack items.

Another important thing to notice is that we have wrapped the Stack class inside an IIFE, so the constants items and sKey are available to the Stack class internally but are not exposed to the outside world. This is a well-known and debated feature of the current JS Class implementation, which does not allow class-level variables to be declared. TC39 essentially designed the ES6 Class in such a way that it should only define and declare its members, which are prototype methods in ES5. Also, since adding variables to prototypes is not the norm, the ability to create class-level variables has not been provided. However, one can still do the following:

    constructor() {
this.sKey = {};
this.items = new WeakMap();
this.items.set(sKey, []);
}

However, this would make the items accessible also from outside our Stack methods, which is something that we want to avoid.

Testing the stack

To test the Stack we have just created, let's instantiate a new stack and call out each of the methods and take a look at how they present us with data:

var stack = new Stack();
stack.push(10);
stack.push(20);

console.log(stack.items); // prints undefined -> cannot be accessed directly

console.log(stack.size()); // prints 2

console.log(stack.peek()); // prints 20

console.log(stack.pop()); // prints 20

console.log(stack.size()); // prints 1

stack.clear();

console.log(stack.size()); // prints 0

When we run the above script we see the logs as specified in the comments above. As expected, the stack provides what appears to be the expected output at each stage of the operations.

Using the stack

To use the Stack class created previously, you would have to make a minor change to allow the stack to be used based on the environment in which you are planning to use it. Making this change generic is fairly straightforward; that way, you do not need to worry about multiple environments to support and can avoid repetitive code in each application:

// AMD
if (typeof define === 'function' && define.amd) {

define(function () { return Stack; });

// NodeJS/CommonJS

} else if (typeof exports === 'object') {

if (typeof module === 'object' && typeof module.exports ===
'object') {

exports = module.exports = Stack;
}

// Browser

} else {

window.Stack = Stack;
}

Once we add this logic to the stack, it is multi-environment ready. For the purpose of simplicity and brevity, we will not add it everywhere we see the stack; however, in general, it's a good thing to have in your code.

If your technology stack comprises ES5, then you need to transpile the preceding stack code to ES5. This is not a problem, as there are a plethora of options available online to transpile code from ES6 to ES5.
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime