Created
September 16, 2018 03:17
-
-
Save pixelsnob/d2e200bb60c03f28a8553e300b9a2be1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Node = function(value, next) { | |
this.value = value; | |
this.next = next; | |
}; | |
const List = function() { | |
this.length = 0; | |
this.head = null; | |
}; | |
List.prototype.add = function(value) { | |
if (!this.head) { | |
this.head = new Node(value); | |
} else { | |
let curr = this.head; | |
while (curr.next) { | |
curr = curr.next; | |
} | |
curr.next = new Node(value); | |
} | |
this.length++; | |
}; | |
List.prototype.remove = function(value) { | |
let current = this.head; | |
let previous; | |
if (current.value === value){ | |
this.head = current.next; | |
} else { | |
while (current.value !== value) { | |
previous = current; | |
current = current.next; | |
} | |
previous.next = current.next; | |
} | |
this.length--; | |
}; | |
List.prototype.getAt = function(i) { | |
let current = this.head; | |
for (let c = 0; c < i; c++) { | |
current = current.next; | |
} | |
return current.value; | |
}; | |
List.prototype.removeAt = function(i) { | |
let current = this.head; | |
let previous; | |
for (let c = 0; c < i; c++) { | |
previous = current; | |
current = current.next; | |
} | |
previous.next = current.next; | |
this.length--; | |
}; | |
List.prototype[Symbol.iterator] = function* () { | |
let current = this.head; | |
while (current) { | |
yield current.value; | |
current = current.next; | |
} | |
}; | |
const list = new List; | |
list.add(55); | |
list.add(20); | |
list.add(11); | |
list.add(22); | |
console.log('iterator:'); | |
for (let el of list) { | |
console.log(el); | |
} | |
console.log('getAt():'); | |
console.log(0, list.getAt(0)); | |
console.log(1, list.getAt(1)); | |
console.log(3, list.getAt(3)); | |
list.removeAt(1); | |
console.log('removing index 1'); | |
for (let el of list) { | |
console.log(el); | |
} | |
console.log('removing value 55'); | |
list.remove(55); | |
for (let el of list) { | |
console.log(el); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment