Skip to content

Instantly share code, notes, and snippets.

@belozerskiy
Created March 21, 2018 19:04
Show Gist options
  • Save belozerskiy/fc48fa5e63b61fe750f9637819617460 to your computer and use it in GitHub Desktop.
Save belozerskiy/fc48fa5e63b61fe750f9637819617460 to your computer and use it in GitHub Desktop.
Linked list for interview
class Entity {
constructor(item){
this.item = item || null;
this.next = null;
}
}
function LinkedList() {
this.head = new Entity();
//Private field
let _size = 0;
//Public Getter for private field _size
this.size = () => _size;
//Private setter
const _increment = () => _size += 1;
const _decrement = () => _size -= 1;
//Add element
this.add = (item) => {
let current = this.head;
while(current.next != null) {
current = current.next;
}
current.next = new Entity(item);
_increment()
};
//Remove element from linked list
this.remove = (item) => {
let current = this.head;
let prev = current;
while(current != null) {
if(current.item == item){
prev.next = current.next;
_decrement();
return true;
}
prev = current;
current = current.next;
}
return false;
}
//Show current linked list
this.show = () => {
console.log(`Current LinkedList: ${JSON.stringify(this.head)}`);
}
//Contains element in linked list
this.inclutes = (item) => {
let current = this.head;
while(current != null){
if (current.item == item) return true;
current = current.next
}
return false;
}
};
const list = new LinkedList()
assert = function(predicate) {
if (!predicate) {
throw new Error('assertion error');
}
}
assertNot = function(predicate) {
assert(!predicate);
}
list.add(1);
list.add(3);
list.add(4);
list.show();
console.log(`Size: ${list.size()}`);
// assert(list.remove(1));
assertNot(list.remove(2));
// assert(list.remove(3));
assert(list.remove(4));
assertNot(list.remove(4));
list.show();
console.log(`Size: ${list.size()}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment