Skip to content

Commit 50cd07e

Browse files
brunob15mgechev
authored andcommitted
Allow comparator function to remove complex data from LinkedList. Also, disable linebreak-style lint rule. (#155)
1 parent 30a95f2 commit 50cd07e

File tree

3 files changed

+38
-3
lines changed

3 files changed

+38
-3
lines changed

.eslintrc.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@
5050
"no-empty": 2,
5151
"no-plusplus": 2,
5252
"no-undef": 2,
53-
"linebreak-style": 2,
53+
"linebreak-style": 0,
5454
"max-depth": [
5555
2,
5656
4

src/data-structures/linked-list.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,15 +134,16 @@
134134
* @param {Object} data Data which should be removed.
135135
* @return {Boolean} Returns true if data has been removed.
136136
*/
137-
exports.LinkedList.prototype.remove = function (data) {
137+
exports.LinkedList.prototype.remove = function (data, equals) {
138138
if (this.first === null) {
139139
return false;
140140
}
141141
var temp = this.first;
142142
var next;
143143
var prev;
144144
while (temp) {
145-
if (temp.data === data) {
145+
var dataFound = equals ? equals(temp.data, data) : temp.data === data;
146+
if (dataFound) {
146147
next = temp.next;
147148
prev = temp.prev;
148149
if (next) {

test/data-structures/linked-list.spec.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,4 +140,38 @@ describe('Linked List', function () {
140140
}
141141
linkedList.inorder(callback);
142142
});
143+
it('should delete data properly', function () {
144+
var linkedList = new LinkedList();
145+
linkedList.push(1);
146+
linkedList.push(2);
147+
linkedList.push(3);
148+
linkedList.push(4);
149+
linkedList.push(5);
150+
linkedList.remove(3);
151+
expect(linkedList.first.data).toBe(1);
152+
expect(linkedList.first.next.data).toBe(2);
153+
expect(linkedList.first.next.next.data).toBe(4);
154+
expect(linkedList.first.next.next.next.data).toBe(5);
155+
expect(linkedList.last.data).toBe(5);
156+
});
157+
it('should delete complex data properly', function () {
158+
var linkedList = new LinkedList();
159+
var item1 = {id: 1};
160+
var item2 = {id: 2};
161+
var item3 = {id: 3};
162+
var item4 = {id: 4};
163+
var item5 = {id: 5};
164+
linkedList.push(item1);
165+
linkedList.push(item2);
166+
linkedList.push(item3);
167+
linkedList.push(item4);
168+
linkedList.push(item5);
169+
var equals = function(a, b) { return a.id === b.id };
170+
linkedList.remove({id: 3}, equals);
171+
expect(linkedList.first.data).toBe(item1);
172+
expect(linkedList.first.next.data).toBe(item2);
173+
expect(linkedList.first.next.next.data).toBe(item4);
174+
expect(linkedList.first.next.next.next.data).toBe(item5);
175+
expect(linkedList.last.data).toBe(item5);
176+
});
143177
});

0 commit comments

Comments
 (0)