Skip to Content
Learning JavaScript Data Structures and Algorithms - Third Edition
book

Learning JavaScript Data Structures and Algorithms - Third Edition

by Loiane Avancini
April 2018
Beginner to intermediate content levelBeginner to intermediate
426 pages
10h 19m
English
Packt Publishing
Content preview from Learning JavaScript Data Structures and Algorithms - Third Edition

Inserting an element at any position

Next, we are going to implement the insert method. This method provides you with the capability to insert an element at any position. Let's take a look at its implementation:

insert(element, index) {  if (index >= 0 && index <= this.count) { // {1}    const node = new Node(element);    if (index === 0) { // add on first position      const current = this.head;      node.next = current; // {2}      this.head = node;    } else {      const previous = this.getElementAt(index - 1); // {3}      const current = previous.next; // {4}      node.next = current; // {5}      previous.next = node; // {6}    }    this.count++; // update size of list    return true;  }  return false; // {7}}

As we are handling positions (indexes), we need to check the out-of-bound values ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning JavaScript Data Structures and Algorithms

Learning JavaScript Data Structures and Algorithms

Loiane Avancini

Publisher Resources

ISBN: 9781788623872Supplemental Content