mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-25 22:46:20 +08:00
Add fromArray() methods to LinkedList and DoublyLinkedList.
This commit is contained in:
parent
0ea24230d4
commit
88bbfdc470
@ -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;
|
||||
}
|
||||
|
||||
|
@ -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', () => {
|
||||
|
@ -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[]}
|
||||
*/
|
||||
|
@ -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) {
|
||||
|
Loading…
Reference in New Issue
Block a user