JS - Nodes

Nodes

Nodes are building blocks to more complicated data structures, formed when many Nodes are linked together.

  • Data helps to store information
  • Next is a link to other Nodes for easier traversal
Create Node Class
// Node.js
class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
    this.previous = null;
  }
 
  setNextNode(node) {
    if (node instanceof Node || node === null) {
      this.next = node;
    } else {
      throw new Error('Next node must be a member of the Node class');
    }
  }
 
  setPreviousNode(node) {
    if (node instanceof Node || node === null) {
      this.previous = node;
    } else {
      throw new Error('Previous node must be a member of the Node class');
    }
  }
 
  getNextNode() {
    return this.next;
  }
 
  getPreviousNode() {
    return this.previous;
  }
}
 
module.exports = Node;

Test the Node Class:

Test Node Class
const Node = require('./Node');
 
const firstNode = new Node('I am an instance of a Node!');
const secondNode = new Node('I am second Node');
 
// link secondNode to firstNode
firstNode.setNextNode(secondNode);
console.log(firstNode);
console.log(firstNode.getNextNode());

Example 1: Ice Cream Flavors

Imagine we are working at an ice cream shop that sells three flavors: strawberry, vanilla, and coconut.

The signature sundae is made of these three flavors in order. We can use Javascript Nodes for this.

class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
 
  setNextNode(node) {
    if (node instanceof Node || node === null) {
      this.next = node;
    } else {
      throw new Error('Next node must be a member of the Node class.');
    }
  }
 
  getNextNode() {
    return this.next;
  }
}
 
const strawberryNode = new Node('Berry Tasty');
const vanillaNode = new Node('Vanilla');
const coconutNode = new Node('Coconuts for Coconut');
 
vanillaNode.setNextNode(strawberryNode);
strawberryNode.setNextNode(coconutNode);
 
let currentNode = vanillaNode;
 
while (currentNode !== null) {
  console.log(currentNode.data);
  currentNode = currentNode.next;
}
 
module.exports = Node;

Example 2: Siblings

Link together the 3 siblings nodes: youngest -> middle -> oldest.

Then, iterate through the nodes, starting at youngest to get oldest‘s name.

const oldest = new Node('John');
const middle = new Node('Jacob');
const youngest = new Node('Jingleheimer');
 
youngest.setNextNode(middle);
middle.setNextNode(oldest);
 
let currentSibling = youngest;
let oldestName = '';
while (currentSibling !== null) {
  oldestName = currentSibling.data;
  currentSibling = currentSibling.getNextNode();
}
 
console.log(`There goes ${oldestName} Schmidt!`);