Data Structures: Search within a Linked List

Data Structures: Search within a Linked List
0

The challengue fails, he tells me:
Your size method should return the length of the linked list
What is the problem ?

function LinkedList() {
  var length = 0;
  var head = null;

  var Node = function (element) { // {1} 
    this.element = element;
    this.next = null;
  };

  this.size = function () {
    return length;
  };

  this.head = function () {
    return head;
  };

  this.add = function (element) {
    var node = new Node(element);
    let currentNode;
    if (head === null) {
      return head = node;
    } else {
      currentNode = head;

      while (currentNode.next) {
        currentNode = currentNode.next;
        console.log(currentNode.next);
      }

      return currentNode.next = node;
    }

    length++;
  };

  this.remove = function (element) {
    var currentNode = head;
    var previousNode;
    if (currentNode.element === element) {
      head = currentNode.next;
    } else {
      while (currentNode.element !== element) {
        previousNode = currentNode;
        currentNode = currentNode.next;
      }

      previousNode.next = currentNode.next;
    }

    length--;
  };

  // Only change code below this line
  this.indexOf = (element) => {
    let idx = 0;
    let currentNode = head;
    let previousNode;
    if (currentNode.element === element) {
      return idx;
    } else if (currentNode.element !== element) {
      while (currentNode.element !== element) {
        previousNode = currentNode;
        currentNode = currentNode.next;
        idx++;
      }
      return idx;
    } else {
      return -1;
    }
  };
  this.elementAt = (index) => {
    let currentNode = head;
    let previousNode;
    let idx = 0;
    if (index === 0) {
      return currentNode.element;
    } else {
      while (idx !== index) {
        previousNode = currentNode;
        currentNode = currentNode.next;
        idx++;
      }
      return currentNode.element;
    }
  };
  // Only change code above this line
}

let nodo = new LinkedList();
nodo.add('first');
nodo.add('dos');
console.log(nodo.elementAt(1));

Your length remains 0 if you add elements into your list. That’s the problem.

this.add = function (element) {
    var node = new Node(element);
    let currentNode;
    if (head === null) {
     // we terminate our function here, without incrementing `length`
      return head = node; 
    } else {
      currentNode = head;

      while (currentNode.next) {
        currentNode = currentNode.next;
        console.log(currentNode.next);
      }
      // we terminate our function here too, without incrementing `length`
      return currentNode.next = node;
    }
     // we increment `length` here, but we never reach here actually.
    length++;
  };

true, I didn’t check the add method, thanks.