Skip to content

Instantly share code, notes, and snippets.

@devsnek
Last active March 29, 2017 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devsnek/025978318a01085a2436442238f6ba9e to your computer and use it in GitHub Desktop.
Save devsnek/025978318a01085a2436442238f6ba9e to your computer and use it in GitHub Desktop.
/*
const x = new LinkedList();
x.add('meme');
x.add('dream');
x.lastValue; // 'dream'
*/
class LinkedItem {
constructor(value, next) {
if (typeof value !== 'undefined') this.value = value;
if (typeof next !== 'undefined') this.next = next;
}
get hasNext() {
return typeof this.next !== 'undefined';
}
}
class LinkedList {
constructor() {
this.first = null;
}
add(value) {
if (this.first) {
this.lastItem.next = new LinkedItem(value);
} else {
this.first = new LinkedItem(value);
}
return true;
}
remove(index) {
if (!this.first) return false;
let current = this.first;
let deleted = null;
if (index === 1) {
this.first = current.next;
deleted = current;
current = null;
} else {
let beforeDelete = getItem(index - 1);
let deleted = beforeDelete.next;
beforeDelete.next = deleted.next;
}
return deleted;
}
get lastItem() {
if (!this.first) return null;
let current = this.first;
while (current.hasNext) current = current.next;
return current;
}
get lastValue() {
if (!this.first) return null;
return this.lastItem.value;
}
get firstItem() {
return this.first;
}
get firstValue() {
if (!this.first) return null;
return this.first.value;
}
getItem(index) {
if (!this.first) return null;
let count = 0;
let current = this.first;
while (index < count) {
current = current.next;
count++;
}
return current;
}
getValue(index) {
if (!this.first) return null;
return this.getItem(index).value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment