Add fromArray() methods to LinkedList and DoublyLinkedList.

This commit is contained in:
Oleksii Trekhleb 2018-08-06 16:12:31 +03:00
parent 0ea24230d4
commit 88bbfdc470
4 changed files with 26 additions and 18 deletions

View File

@ -214,11 +214,12 @@ export default class DoublyLinkedList {
}
/**
* @param {DoublyLinkedListNode[]} array - Array of nodes
* @return {DoublyLinkedListNode[]}
* @param {*[]} values - Array of values that need to be converted to linked list.
* @return {DoublyLinkedList}
*/
fromArray(arr = []) {
arr.forEach(node => this.append(node.value));
fromArray(values) {
values.forEach(value => this.append(value));
return this;
}

View File

@ -36,21 +36,11 @@ describe('DoublyLinkedList', () => {
expect(linkedList.toString()).toBe('3,2,1');
});
it('should append new nodes from array', () => {
const linkedList1 = new DoublyLinkedList();
linkedList1.append(1);
linkedList1.append(1);
linkedList1.append(2);
linkedList1.append(3);
linkedList1.append(3);
linkedList1.append(3);
linkedList1.append(4);
linkedList1.append(5);
const array = linkedList1.toArray();
it('should create linked list from array', () => {
const linkedList = new DoublyLinkedList();
linkedList.fromArray([1, 1, 2, 3, 3, 3, 4, 5]);
const linkedList2 = new DoublyLinkedList();
linkedList2.fromArray(array);
expect(linkedList2.toString()).toBe('1,1,2,3,3,3,4,5');
expect(linkedList.toString()).toBe('1,1,2,3,3,3,4,5');
});
it('should delete node by value from linked list', () => {

View File

@ -175,6 +175,16 @@ export default class LinkedList {
return deletedHead;
}
/**
* @param {*[]} values - Array of values that need to be converted to linked list.
* @return {LinkedList}
*/
fromArray(values) {
values.forEach(value => this.append(value));
return this;
}
/**
* @return {LinkedListNode[]}
*/

View File

@ -184,6 +184,13 @@ describe('LinkedList', () => {
expect(linkedList.find({ callback: value => value.key === 'test5' })).toBeNull();
});
it('should create linked list from array', () => {
const linkedList = new LinkedList();
linkedList.fromArray([1, 1, 2, 3, 3, 3, 4, 5]);
expect(linkedList.toString()).toBe('1,1,2,3,3,3,4,5');
});
it('should find node by means of custom compare function', () => {
const comparatorFunction = (a, b) => {
if (a.customValue === b.customValue) {