JSFiddle - React, Tailwind, and code Playground

by austinmillett

HTML

<div "output">

</div>

JavaScript

var Node = function(data) {
  this.data = data;
  this.previous = null;
  this.next = null;
};

/***
 * The doubly-linked list
 */
var DoublyLinkedList = function() {
  this._length = 0;
  this.head = null;
  this.tail = null;
}

/***
 * Add a value to the list
 * @param {object} data
 * @return {Node}
 */
DoublyLinkedList.prototype.add = function(data) {
  var node = new Node(data);
  
  // If there are already nodes then set the previous node
  if (this._length) {
    this.tail.next = node;
    node.previous = this.tail;
    this.tail = node;
  } else {
    this.head = node;
    this.tail = node;
  }
  
  this._length++;
  return node;
};

/***
 * Search for a value by index
 * @param {int} index
 * @param {Node}
 */
DoublyLinkedList.prototype.searchNodeAt = function(index) {
  var currentNode = this.head;
  var length = this._length;
  var count = 0;
  var message = {failure: 'Failure: node not at position ' + index};
  
  // If the index is invalid throw an error
  if (length === 0 || index < 0 || index >= length) {
    throw new Error(message.failure);
  }
  
  // Otherwise do normal stuff
  while (count < index) {
    currentNode = currentNode.next;
    count++;
  }
  
  return currentNode;
}

/***
 * Remove a node by index
 * @param {int} index
 * @return {Node}
 */
DoublyLinkedList.prototype.remove = function(index) {
  // TODO: finish this
  var deletedNode = null;
  return deletedNode;
}