Skip to content

Commit

Permalink
Make List iterable
Browse files Browse the repository at this point in the history
  • Loading branch information
cronokirby committed Jun 10, 2019
1 parent 536e624 commit b8aad3a
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
12 changes: 10 additions & 2 deletions src/List.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ test('List.singleton is not Empty', () => {
expect(singleton.isEmpty()).toBe(false);
});

test('List.equals', () => {
test('List.equals works', () => {
const empty: List<number> = List.empty();
const single1 = List.from(1);
const single2 = List.from(2);
Expand All @@ -20,9 +20,17 @@ test('List.equals', () => {
expect(single1.equals(single1)).toBe(true);
});

test('List.prepend', () => {
test('List.prepend works', () => {
const single1 = List.from(1);
const prepend1 = List.empty().prepend(1);
expect(prepend1.equals(single1)).toBe(true);
expect(single1.prepend(1).equals(single1)).toBe(false);
});

test('List is iterable', () => {
const array = [1, 2, 3];
const list = List.from(...array);
expect(Array.from(list)).toEqual(array);
expect(Array.from(List.empty())).toEqual([]);
expect(List.from(...list).equals(list)).toBe(true);
});
10 changes: 9 additions & 1 deletion src/List.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ type Node<T> = { empty: true } | { empty: false; value: T; next: Node<T> };
// We can share a single empty node between all lists.
const EMPTY_NODE = { empty: true };

class List<T> {
class List<T> implements Iterable<T> {
private constructor(private readonly _node: Node<T>) {}

public static empty<T>(): List<T> {
Expand All @@ -25,6 +25,14 @@ class List<T> {
return new List({ empty: false, value, next: this._node });
}

public *[Symbol.iterator]() {
let node = this._node;
while (!node.empty) {
yield node.value;
node = node.next;
}
}

public equals(that: List<T>): boolean {
let thisNode = this._node;
let thatNode = that._node;
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"target": "es6",
"strictNullChecks": true,
"declaration": true,
"outDir": "./dist"
Expand Down

0 comments on commit b8aad3a

Please sign in to comment.