Initial commit
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
class LinkedListNode {
|
||||
constructor(key, value) {
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
this.next = null;
|
||||
};
|
||||
};
|
||||
|
||||
class LinkedList {
|
||||
constructor() {
|
||||
this.map = new Map();
|
||||
this.head = null;
|
||||
this.tail = null;
|
||||
};
|
||||
|
||||
getElement(id) {
|
||||
const element = this.map.get(id);
|
||||
if (!element) return;
|
||||
|
||||
return element.value;
|
||||
}
|
||||
|
||||
hasElement(id) {
|
||||
return this.map.has(id);
|
||||
}
|
||||
|
||||
isEmpty() {
|
||||
return this.head === null;
|
||||
}
|
||||
|
||||
addItem(key, value) {
|
||||
const temp = new LinkedListNode(key, value);
|
||||
|
||||
if (!this.head) {
|
||||
this.head = temp;
|
||||
this.tail = temp;
|
||||
} else {
|
||||
this.tail.next = temp;
|
||||
this.tail = temp;
|
||||
};
|
||||
|
||||
this.map.set(key, temp);
|
||||
}
|
||||
|
||||
each(cb) {
|
||||
if (this.isEmpty()) return;
|
||||
|
||||
let current = this.head;
|
||||
while (current) {
|
||||
cb(current.key, current.value);
|
||||
|
||||
current = current.next;
|
||||
};
|
||||
}
|
||||
|
||||
clearEach(cb) {
|
||||
if (this.isEmpty()) return;
|
||||
|
||||
let current = this.head;
|
||||
while (current) {
|
||||
cb(current.key, current.value);
|
||||
|
||||
current = current.next;
|
||||
};
|
||||
|
||||
this.head = null;
|
||||
this.tail = null;
|
||||
|
||||
this.map.clear();
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = LinkedList;
|
||||
Reference in New Issue
Block a user