Last active
March 29, 2017 06:11
-
-
Save devsnek/025978318a01085a2436442238f6ba9e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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