Add jest tests.

This commit is contained in:
Oleksii Trekhleb
2018-03-27 13:03:44 +03:00
parent eb3eadaf10
commit ad0921d05e
11 changed files with 5715 additions and 86 deletions

View File

@@ -0,0 +1,49 @@
import Node from './Node';
export default class LinkedList {
constructor() {
this.head = null;
}
append(value) {
const newNode = new Node(value);
// If there is no head yet let's make new node a head.
if (!this.head) {
this.head = newNode;
return newNode;
}
// Rewind to last node.
let currentNode = this.head;
while (currentNode.next !== null) {
currentNode = currentNode.next;
}
// Attach new node to the end of linked list.
currentNode.next = newNode;
return newNode;
}
prepend(value) {
this.head = new Node(value, this.head);
}
toArray() {
const listArray = [];
let currentNode = this.head;
while (currentNode) {
listArray.push(currentNode.value);
currentNode = currentNode.next;
}
return listArray;
}
toString() {
return this.toArray().toString();
}
}

View File

@@ -0,0 +1,6 @@
export default class Node {
constructor(value, next = null) {
this.value = value;
this.next = next;
}
}

View File

@@ -0,0 +1,23 @@
import LinkedList from '../LinkedList';
describe('LinkedList', () => {
it('should create empty linked list', () => {
const linkedList = new LinkedList();
expect(linkedList).toBeDefined();
});
it('should append node to linked list', () => {
const linkedList = new LinkedList();
linkedList.append(1);
linkedList.append(2);
expect(linkedList.toString()).toBe('1,2');
});
it('should prepend node to linked list', () => {
const linkedList = new LinkedList();
linkedList.append(1);
linkedList.append(2);
linkedList.prepend(3);
expect(linkedList.toString()).toBe('3,1,2');
});
});

View File

@@ -0,0 +1,9 @@
import Node from '../Node';
describe('Node', () => {
it('should create list node with value', () => {
const node = new Node(1);
expect(node.value).toBe(1);
expect(node.next).toBeNull();
});
});