Book Image

Hands-On Data Structures and Algorithms with JavaScript

By : Kashyap Mukkamala
Book Image

Hands-On Data Structures and Algorithms with JavaScript

By: Kashyap Mukkamala

Overview of this book

Data structures and algorithms are the fundamental building blocks of computer programming. They are critical to any problem, provide a complete solution, and act like reusable code. Using appropriate data structures and having a good understanding of algorithm analysis are key in JavaScript to solving crises and ensuring your application is less prone to errors. Do you want to build applications that are high-performing and fast? Are you looking for complete solutions to implement complex data structures and algorithms in a practical way? If either of these questions rings a bell, then this book is for you! You'll start by building stacks and understanding performance and memory implications. You will learn how to pick the right type of queue for the application. You will then use sets, maps, trees, and graphs to simplify complex applications. You will learn to implement different types of sorting algorithm before gradually calculating and analyzing space and time complexity. Finally, you'll increase the performance of your application using micro optimizations and memory management. By the end of the book you will have gained the skills and expertise necessary to create and employ various data structures in a way that is demanded by your project or use case.
Table of Contents (16 chapters)
Title Page
Copyright and Credits
PacktPub.com
Contributors
Preface
5
Simplify Complex Applications Using Graphs
Index

Sets versus WeakSets


Now, we understand the fundamental meaning of weak in the term WeakMap or WeakSetIt is not very complex to predict how sets work and how WeakSet differs from them. Let's take a quick look at the functional difference and then move on to the API.

Understanding WeakSets

WeakSet is very similar to WeakMap; the values that a WeakSet can hold are only objects and cannot be primitives just like in the case of a WeakMap. The WeakSets are also not enumerable, so you do not have direct access to the values available inside the set.

Let's create a small example and understand the difference between a Set and a WeakSet: 

var set = new Set();
var wset = new WeakSet();

(function() {

  var a = {a: 1};
  var b = {b: 2};
  var c = {c: 3};
  var d = {d: 4};

  set.add(1).add(2).add(3).add(4);
  wset.add(a).add(b).add(b).add(d);

})();

console.dir(set);
console.dir(wset);

One important thing to note is that WeakSet does not accept primitives and can only accept objects similar to the...