@@ -74,19 +74,16 @@ class LinkedList {
74
74
return this.addLast(value);
75
75
}
76
76
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;
90
87
}
91
88
92
89
return undefined; // out of bound index
@@ -147,14 +144,12 @@ class LinkedList {
147
144
* @returns {number} return index or undefined
148
145
*/
149
146
indexOf(value) {
150
- for (let current = this.first, index = 0;
151
- current;
152
- index += 1, current = current.next) {
147
+ return this.find((current, position) => {
153
148
if (current.value === value) {
154
- return index ;
149
+ return position ;
155
150
}
156
- }
157
- return undefined; // not found
151
+ return undefined;
152
+ });
158
153
}
159
154
160
155
/**
@@ -164,11 +159,26 @@ class LinkedList {
164
159
* @returns {Node} element at the specified position in this list.
165
160
*/
166
161
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) {
167
176
for (let current = this.first, position = 0;
168
177
current;
169
178
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;
172
182
}
173
183
}
174
184
return undefined; // not found
0 commit comments