Skip to content

Commit

Permalink
feat: set method
Browse files Browse the repository at this point in the history
  • Loading branch information
201flaviosilva committed May 23, 2023
1 parent dfb0845 commit fdf8f20
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/DataStructures/LinkedList.js
Expand Up @@ -35,20 +35,28 @@ export class LinkedList {
return this;
}

get(index) {
get(index, returnNode = false) {
if (index < 0 || index >= this.size) return undefined;

let count = 0;
let temp = this.head;
while (temp !== null) {
if (count === index) return temp.value;
if (count === index) return returnNode ? temp : temp.value;
temp = temp.next;
count++;
}

return temp; // Should never reach here
}

set(index, value) {
const node = this.get(index, true);
if (!node) return false;

node.value = value;
return true;
}

// ADD a new value to the END of the list
push(value) {
const newNode = new Node(value);
Expand Down
36 changes: 36 additions & 0 deletions tests/DataStructures/LinkedList.test.js
Expand Up @@ -84,6 +84,42 @@ describe("LinkedList.js", () => {
});
});

describe("set()", () => {
it("should change a node value by the given index and new value", () => {
const ll = new LinkedList(100);
ll.push(20);
ll.push(30);
expect(ll.toArray()).toEqual([100, 20, 30]);

expect(ll.set(0, 500)).toBe(true);
expect(ll.toArray()).toEqual([500, 20, 30]);

expect(ll.set(2, 0)).toBe(true);
expect(ll.toArray()).toEqual([500, 20, 0]);

expect(ll.set(1, -50)).toBe(true);
expect(ll.toArray()).toEqual([500, -50, 0]);
});

it("should return false if the given index is out of bounds", () => {
const ll = new LinkedList();
expect(ll.toArray()).toEqual([]);

expect(ll.set(0, 500)).toBe(false);
expect(ll.toArray()).toEqual([]);

ll.push(42);
ll.set(0, 500);
expect(ll.toArray()).toEqual([500]);

expect(ll.set(-1, 1)).toBe(false);
expect(ll.toArray()).toEqual([500]);

expect(ll.set(100, 123)).toBe(false);
expect(ll.toArray()).toEqual([500]);
});
});

describe("push()", () => {
it("adds items to the end of the linked list", () => {
const ll = new LinkedList(100);
Expand Down

0 comments on commit fdf8f20

Please sign in to comment.