Skip to content

Commit

Permalink
Merge pull request #8 from truck-js/feature/to-array-callback
Browse files Browse the repository at this point in the history
feat: add callback to `toArray` method
  • Loading branch information
hvolschenk committed Dec 12, 2018
2 parents 699d328 + 533856d commit 2a610c0
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 12 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ determine whether the `value` matches.

**O(n)**. Converts the _Singly Linked-List_'s values to an array.

### `toArray(callback: (node: Node) => any): any[]`

**O(n)**. Converts the _Singly Linked-List_ to an array, the `callback` receives the `Node` with
each iteration.

## Properties

### `.length: number`
Expand Down
5 changes: 3 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import isFunction from 'lodash.isfunction';

import Node from './node';

const defaultCallback = a => a.value;
const defaultComparator = a => b => a === b;

class SinglyLinkedList {
Expand Down Expand Up @@ -106,11 +107,11 @@ class SinglyLinkedList {
return undefined;
}

toArray() {
toArray(callback = defaultCallback) {
const returnArray = [];
let current = this.head;
while (current) {
returnArray.push(current.value);
returnArray.push(callback(current));
current = current.next;
}
return returnArray;
Expand Down
29 changes: 19 additions & 10 deletions src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -357,17 +357,26 @@ describe('.toArray()', () => {
expect(singlyLinkedList.toArray()).toEqual([]);
});

test('Returns an array of items inside the SinglyLinkedList', () => {
const VALUE_A = 'VALUE_A';
const VALUE_B = 'VALUE_B';
const VALUE_C = 'VALUE_C';
const expected = [VALUE_A, VALUE_B, VALUE_C];
describe('After values have been inserted', () => {
beforeAll(() => {
singlyLinkedList.insert(1);
singlyLinkedList.insert(2);
singlyLinkedList.insert(3);
singlyLinkedList.insert(4);
singlyLinkedList.insert(5);
});

singlyLinkedList.insert(VALUE_C);
singlyLinkedList.insert(VALUE_B);
singlyLinkedList.insert(VALUE_A);
const actual = singlyLinkedList.toArray();
test('Returns an array of items inside the SinglyLinkedList', () => {
expect(singlyLinkedList.toArray()).toEqual([5, 4, 3, 2, 1]);
});

expect(actual).toEqual(expected);
test('Can be used as a \'map\' method if passed a callback', () => {
const callback = node => (node.value + ((node.next && node.next.value) || 0));
const expected = [9, 7, 5, 3, 1];

const actual = singlyLinkedList.toArray(callback);

expect(actual).toEqual(expected);
});
});
});

0 comments on commit 2a610c0

Please sign in to comment.