JSFiddle - React, Tailwind, and code Playground

by Ryan Brown

HTML

<h1>Module 3 Assignment 1</h1>
<p id="demo"></p>

JavaScript

// Define the link object
function Link(_id, _value, _next) {
  this.id = _id; // The id of the current link
  this.value = _value; // The value stored 
  this.next = _next; // a pointer to next link, this is "last" if it is the last link in chain 
}

Link.prototype.asString = function () {
  return "Link ID: " + this.id + " Value: " + 
    this.value + " Points to ID: " + this.next + "<br/>";
};

// Define the Chain object
function Chain(value) { 
  this.head = new Link(0, value, null); // first link is head
  this.linkStorage = []; // place to store links
  this.linkStorage.push(this.head); // push first link into array 
}

Chain.prototype.addLink = function (_linkValue) {
  // A function to add a link to the chain
  link_id = this.linkStorage.length; //dynamically assign link id based on array length
  this.linkStorage[link_id - 1].next = link_id; //assign curr link id value to last link
  this.linkStorage.push(new Link(this.linkStorage.length, _linkValue, "End of Chain"));
}

Chain.prototype.print = function () {//to see the output    
  for (i=0; i < this.linkStorage.length; i++) {
    document.getElementById("demo").innerHTML += this.linkStorage[i].asString();
  }
}

function CreateChainWithLinks(how_many_links) {
  var chain = new Chain('Link 1');
  for (i=1; i < (how_many_links); i++) { 
    chain.addLink('Link ' + (i+1)); //plus 1 for head, 
  } return chain.print();
}

CreateChainWithLinks(5);

/*
Module 3 Assignment 1
Assignment 1 - In Javascript we are going to create a Class called Chain. If you need a little primer on creating objects and classes in Javascript see http://www.w3schools.com/js/js_object_definition.asp - if you know your object oriented code this will be relatively straightforward. Your Chain will be made up of Links. Each link will have an id, a value (String) and a pointer to the next link ( NextLink ) - which is simply a pointer to the id of the next link in the Chain. Please note that this is a very inefficient representation of...