Skip to content

Commit

Permalink
feat: get method
Browse files Browse the repository at this point in the history
  • Loading branch information
201flaviosilva committed May 23, 2023
1 parent 51546fe commit dfb0845
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/DataStructures/LinkedList.js
@@ -1,5 +1,3 @@
import { isValidNumber } from "../Maths";

export class Node {
constructor(value) {
this.value = value;
Expand All @@ -9,7 +7,7 @@ export class Node {

export class LinkedList {
constructor(value) {
if (isValidNumber(value)) {
if (value !== undefined) {
const newNode = new Node(value);
this.head = newNode;
this.tail = newNode;
Expand Down Expand Up @@ -37,6 +35,20 @@ export class LinkedList {
return this;
}

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

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

return temp; // Should never reach here
}

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

describe("get()", () => {
it("should return value by the passed index", () => {
const ll = new LinkedList(100);
ll.push(20);
ll.push(30);

expect(ll.get(0)).toBe(100);
expect(ll.get(1)).toBe(20);
expect(ll.get(2)).toBe(30);
});

it("should return undefined in a empty list", () => {
const ll = new LinkedList();
expect(ll.get(0)).toBe(undefined);
expect(ll.get(1)).toBe(undefined);
expect(ll.get(10)).toBe(undefined);
});

it("should return undefined in a empty list", () => {
const ll = new LinkedList();
expect(ll.get(0)).toBe(undefined);
expect(ll.get(1)).toBe(undefined);
expect(ll.get(10)).toBe(undefined);
});

it("should return undefined if try to get a index less than 0 or greater than the list size", () => {
const ll = new LinkedList();
expect(ll.get(-1)).toBe(undefined);
expect(ll.get(-10)).toBe(undefined);
});

it("should return undefined if try to get a index greater than the list size", () => {
const ll = new LinkedList(10);
expect(ll.get(0)).toBe(10);
expect(ll.get(1)).toBe(undefined);
expect(ll.get(2)).toBe(undefined);

ll.push(25);
expect(ll.get(1)).toBe(25);
expect(ll.get(2)).toBe(undefined);
expect(ll.get(10)).toBe(undefined);
});
});

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

0 comments on commit dfb0845

Please sign in to comment.