JSFiddle - React, Tailwind, and code Playground

by Erik East

JavaScript

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

function DoublyList() {
	this._length = 0;
	this.head = null;
	this.tail = null;
}//DoublyList

DoublyList.prototype.add = function(value) {
	var node = new Node(value);
	
	if (this._length) {
		this.tail.next = node;
		node.previous = this.tail;
		this.tail = node;
	}//if this._length
	else {
		this.head = node;
		this.tail = node;
	}//else
	
	this._length++;
	
	return node;
}//prototype.add

DoublyList.prototype.searchNodeAt = function(position) {
	var currentNode = this.head,
	length = this._length,
	count = 1,
	message = {failure: "Failure: non-existent node in this list."};
	
	if (length === 0 || position < 1 || position > length) {
		throw new Error(message.failure);
	}//if invalid
	
	while (count < position) {
		currentNode = currentNode.next;
		count++;
	}//while valid
	
	return currentNode;
};//prototype.searchNodeAt

DoublyList.prototype.remove = function(position) {
	var currentNode = this.head,
	length = this._length,
	count = 1,
	message = {failure: "Failure: non-existent node in this list."},
	beforeNodeToDelete = null,
	nodeToDelete = null,
	deletedNode = null;
	
	if (length === 0 || position < 1 || position > length) {
	throw new Error(message.failure);
	}//if invalid
	
	if (position === 1){
		this.head = currentNode.next;
		
		if (!this.head){
		this.head.previous = null;
		}//if there is a second node

		else {
			this.tail = null;
		}//if there is no second node
	
	}//if first node is removed
	
	else if (position === this._length) {
		this.tail = this.tail.previous;
		this.tail.next = null;
	}//if the last node is removed
	else {
		while (count < position) {
			currentNode = currentNode.next;
			count++;
		}//while count < position
		
		beforeNodeToDelete = currentNode.previous;
		nodeToDelete = currentNode;
		afterNodeToDelete = currentNode.next;
		
		beforeNodeToDelete.next = afterNodeToDelete;
		afterNodeToDelete.previous =...