Skip to content

Commit

Permalink
feat: created shift linkedlist method
Browse files Browse the repository at this point in the history
  • Loading branch information
201flaviosilva committed May 22, 2023
1 parent fe1a0a4 commit 51546fe
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/DataStructures/LinkedList.js
Expand Up @@ -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
Expand Down
55 changes: 55 additions & 0 deletions tests/DataStructures/LinkedList.test.js
Expand Up @@ -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);
Expand All @@ -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([]);
});
});
});
});

0 comments on commit 51546fe

Please sign in to comment.