From 7ed7ece4b35f13ab78060dc333feb9b9c9fd8d42 Mon Sep 17 00:00:00 2001 From: Bruno Bradach Date: Sun, 18 Aug 2019 20:46:24 -0300 Subject: [PATCH] Allow comparator function to remove complex data from LinkedList. Also, disable linebreak-style lint rule. --- .eslintrc.json | 2 +- src/data-structures/linked-list.js | 5 ++-- test/data-structures/linked-list.spec.js | 34 ++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index 82ecf768..90b26d15 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -50,7 +50,7 @@ "no-empty": 2, "no-plusplus": 2, "no-undef": 2, - "linebreak-style": 2, + "linebreak-style": 0, "max-depth": [ 2, 4 diff --git a/src/data-structures/linked-list.js b/src/data-structures/linked-list.js index c8d22db5..9027f16e 100644 --- a/src/data-structures/linked-list.js +++ b/src/data-structures/linked-list.js @@ -134,7 +134,7 @@ * @param {Object} data Data which should be removed. * @return {Boolean} Returns true if data has been removed. */ - exports.LinkedList.prototype.remove = function (data) { + exports.LinkedList.prototype.remove = function (data, equals) { if (this.first === null) { return false; } @@ -142,7 +142,8 @@ var next; var prev; while (temp) { - if (temp.data === data) { + var dataFound = equals ? equals(temp.data, data) : temp.data === data; + if (dataFound) { next = temp.next; prev = temp.prev; if (next) { diff --git a/test/data-structures/linked-list.spec.js b/test/data-structures/linked-list.spec.js index 37ee7084..eb1d0e38 100644 --- a/test/data-structures/linked-list.spec.js +++ b/test/data-structures/linked-list.spec.js @@ -140,4 +140,38 @@ describe('Linked List', function () { } linkedList.inorder(callback); }); + it('should delete data properly', function () { + var linkedList = new LinkedList(); + linkedList.push(1); + linkedList.push(2); + linkedList.push(3); + linkedList.push(4); + linkedList.push(5); + linkedList.remove(3); + expect(linkedList.first.data).toBe(1); + expect(linkedList.first.next.data).toBe(2); + expect(linkedList.first.next.next.data).toBe(4); + expect(linkedList.first.next.next.next.data).toBe(5); + expect(linkedList.last.data).toBe(5); + }); + it('should delete complex data properly', function () { + var linkedList = new LinkedList(); + var item1 = {id: 1}; + var item2 = {id: 2}; + var item3 = {id: 3}; + var item4 = {id: 4}; + var item5 = {id: 5}; + linkedList.push(item1); + linkedList.push(item2); + linkedList.push(item3); + linkedList.push(item4); + linkedList.push(item5); + var equals = function(a, b) { return a.id === b.id }; + linkedList.remove({id: 3}, equals); + expect(linkedList.first.data).toBe(item1); + expect(linkedList.first.next.data).toBe(item2); + expect(linkedList.first.next.next.data).toBe(item4); + expect(linkedList.first.next.next.next.data).toBe(item5); + expect(linkedList.last.data).toBe(item5); + }); });