From 0ea24230d4fa77bd7666bc871f1c7682a7b62795 Mon Sep 17 00:00:00 2001 From: Simon <34153549+seIncorp@users.noreply.github.com> Date: Mon, 6 Aug 2018 15:02:46 +0200 Subject: [PATCH] Patch 5 (#127) * New function 'fromArray' Function get array of Doubly Linked List Nodes, go through and append to currently list. * New Test for new function 'fromArray' * Minor changes Minor changes about coding style. --- .../doubly-linked-list/DoublyLinkedList.js | 9 +++++++++ .../__test__/DoublyLinkedList.test.js | 17 +++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/data-structures/doubly-linked-list/DoublyLinkedList.js b/src/data-structures/doubly-linked-list/DoublyLinkedList.js index 25fb0508..6b7f908e 100644 --- a/src/data-structures/doubly-linked-list/DoublyLinkedList.js +++ b/src/data-structures/doubly-linked-list/DoublyLinkedList.js @@ -213,6 +213,15 @@ export default class DoublyLinkedList { return nodes; } + /** + * @param {DoublyLinkedListNode[]} array - Array of nodes + * @return {DoublyLinkedListNode[]} + */ + fromArray(arr = []) { + arr.forEach(node => this.append(node.value)); + return this; + } + /** * @param {function} [callback] * @return {string} diff --git a/src/data-structures/doubly-linked-list/__test__/DoublyLinkedList.test.js b/src/data-structures/doubly-linked-list/__test__/DoublyLinkedList.test.js index 4490574e..d036e3f5 100644 --- a/src/data-structures/doubly-linked-list/__test__/DoublyLinkedList.test.js +++ b/src/data-structures/doubly-linked-list/__test__/DoublyLinkedList.test.js @@ -36,6 +36,23 @@ 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(); + + const linkedList2 = new DoublyLinkedList(); + linkedList2.fromArray(array); + expect(linkedList2.toString()).toBe('1,1,2,3,3,3,4,5'); + }); + it('should delete node by value from linked list', () => { const linkedList = new DoublyLinkedList();