@@ -74,19 +74,16 @@ class LinkedList {
7474 return this . addLast ( value ) ;
7575 }
7676
77- for ( let current = this . first , index = 0 ;
78- index <= this . size ;
79- index += 1 , current = ( current && current . next ) ) {
80- if ( index === position ) {
81- const newNode = new Node ( value ) ;
82- newNode . previous = current . previous ;
83- newNode . next = current ;
84-
85- current . previous . next = newNode ;
86- if ( current . next ) { current . next . previous = newNode ; }
87- this . size += 1 ;
88- return newNode ;
89- }
77+ const current = this . get ( position ) ;
78+ if ( current ) {
79+ const newNode = new Node ( value ) ;
80+ newNode . previous = current . previous ;
81+ newNode . next = current ;
82+
83+ current . previous . next = newNode ;
84+ if ( current . next ) { current . next . previous = newNode ; }
85+ this . size += 1 ;
86+ return newNode ;
9087 }
9188
9289 return undefined ; // out of bound index
@@ -147,14 +144,12 @@ class LinkedList {
147144 * @returns {number } return index or undefined
148145 */
149146 indexOf ( value ) {
150- for ( let current = this . first , index = 0 ;
151- current ;
152- index += 1 , current = current . next ) {
147+ return this . find ( ( current , position ) => {
153148 if ( current . value === value ) {
154- return index ;
149+ return position ;
155150 }
156- }
157- return undefined ; // not found
151+ return undefined ;
152+ } ) ;
158153 }
159154
160155 /**
@@ -164,11 +159,26 @@ class LinkedList {
164159 * @returns {Node } element at the specified position in this list.
165160 */
166161 get ( index = 0 ) {
162+ return this . find ( ( current , position ) => {
163+ if ( position === index ) {
164+ return current ;
165+ }
166+ return undefined ;
167+ } ) ;
168+ }
169+
170+ /**
171+ * Iterate through the list until callback returns thruthy
172+ * @param {Function } callback evaluates node and index
173+ * @returns {any } callbacks's return value
174+ */
175+ find ( callback ) {
167176 for ( let current = this . first , position = 0 ;
168177 current ;
169178 position += 1 , current = current . next ) {
170- if ( position === index ) {
171- return current ;
179+ const result = callback ( current , position ) ;
180+ if ( result !== undefined ) {
181+ return result ;
172182 }
173183 }
174184 return undefined ; // not found
0 commit comments