function defaultEquals(a, b) {
return a === b;
}
class Node {
constructor(element) {
this.element = element;
this.next = null;
}
}
class LinkList {
constructor(equalsFn = defaultEquals) {
this.count = 0;
this.head = null;
this.equalsFn = equalsFn;
}
push(element) {
const node = new Node(element);
let current;
if (this.head === null) {
this.head = node;
} else {
current = this.head;
while (current.next !== null) {
current = current.next;
}
current.next = node;
}
this.count++;
}
insert(element, index) {
if (index < 0 || index > this.count) {
return false;
}
const node = new Node(element);
if (index === 0) {
node.next = this.head;
this.head = node;
} else {
const previous = this.getElementAt(index - 1);
node.next = previous.next;
previous.next = node;
}
this.count++;
}
getElementAt(index) {
if (index >= 0 && index <= this.count) {
let node = this.head;
for (let i = 0; i < index && node !== null; i++) {
node = node.next;
}
return node;
}
return;
}
remove(element) {
const index = this.indexOf(element);
return this.removeAt(index);
}
indexOf(element) {
let current = this.head;
for (let i = 0; i < this.count && current !== null; i++) {
if (this.equalsFn(element, current.element)) {
return i;
}
current = current.next;
}
return -1;
}
removeAt(index) {
if (index < 0 || index >= this.count) {
return;
}
let current = this.head;
if (index === 0) {
this.head = current.next;
} else {
let previous = this.getElementAt(index - 1);
current = previous.next;
previous.next = current.next;
}
this.count--;
return current.element;
}
isEmpty() {
return this.size() === 0;
}
size() {
return this.count;
}
toString() {
if (this.head === null) {
return "";
}
let objString = `${this.head.element}`;
let current = this.head.next;
for (let i = 0; i < this.count && current != null; i++) {
objString = `${objString}, ${current.element}`;
current = current.next;
}
return objString;
}
}