From 51546fe49cf14c443f1c87b15c6975f2da95eae4 Mon Sep 17 00:00:00 2001 From: Flavio Silva <55815265+201flaviosilva@users.noreply.github.com> Date: Tue, 23 May 2023 00:42:21 +0100 Subject: [PATCH] feat: created shift linkedlist method --- src/DataStructures/LinkedList.js | 11 ++++- tests/DataStructures/LinkedList.test.js | 55 +++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/src/DataStructures/LinkedList.js b/src/DataStructures/LinkedList.js index 67d2da7..5c29f9d 100644 --- a/src/DataStructures/LinkedList.js +++ b/src/DataStructures/LinkedList.js @@ -93,7 +93,16 @@ export class LinkedList { // REMOVE a value to the START of the list shift() { - return this; + if (!this.size) return undefined; + + const removedValue = this.head.value; + + this.head = this.head.next; + + this.size--; + + if (this.size === 0) this.clear(); + return removedValue; } // REMOVE a value in the given index of the list diff --git a/tests/DataStructures/LinkedList.test.js b/tests/DataStructures/LinkedList.test.js index 8426abb..e662bf0 100644 --- a/tests/DataStructures/LinkedList.test.js +++ b/tests/DataStructures/LinkedList.test.js @@ -141,6 +141,42 @@ describe("LinkedList.js", () => { }); }); + describe("shift()", () => { + it("remove the first element from the linked list", () => { + const ll = new LinkedList(100); + ll.push(50); + ll.push(25); + ll.push(13); + + expect(ll.shift()).toBe(100); + expect(ll.size).toBe(3); + expect(ll.head.value).toBe(50); + expect(ll.tail.value).toBe(13); + expect(ll.tail.next).toBe(null); + expect(ll.toArray()).toEqual([50, 25, 13]); + + expect(ll.shift()).toBe(50); + expect(ll.size).toBe(2); + expect(ll.head.value).toBe(25); + expect(ll.tail.value).toBe(13); + expect(ll.tail.next).toBe(null); + expect(ll.toArray()).toEqual([25, 13]); + + expect(ll.shift()).toBe(25); + expect(ll.size).toBe(1); + expect(ll.head.value).toBe(13); + expect(ll.tail.value).toBe(13); + expect(ll.tail.next).toBe(null); + expect(ll.toArray()).toEqual([13]); + + expect(ll.pop()).toBe(13); + expect(ll.size).toBe(0); + expect(ll.head).toBe(null); + expect(ll.tail).toBe(null); + expect(ll.toArray()).toEqual([]); + }); + }); + describe("toArray()", () => { it("should return an array with the values of the linked list", () => { const ll = new LinkedList(0); @@ -154,5 +190,24 @@ describe("LinkedList.js", () => { expect(result).toEqual([0, 10, 20, 30]); }); }); + + describe("End To End tests", () => { + test("all function of the linked list", () => { + const ll = new LinkedList(); + expect(ll.toArray()).toEqual([]); + + ll.push(100); + expect(ll.toArray()).toEqual([100]); + + ll.pop(); + expect(ll.toArray()).toEqual([]); + + ll.unshift(50); + expect(ll.toArray()).toEqual([50]); + + ll.shift(); + expect(ll.toArray()).toEqual([]); + }); + }); }); });