Skip to content

Commit

Permalink
feat(dcons): add ISeqable impl (seq()) & tests
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Nov 15, 2019
1 parent d94df57 commit 1cfb02a
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 3 deletions.
20 changes: 20 additions & 0 deletions packages/dcons/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
IEquiv,
ILength,
IRelease,
ISeq,
ISeqable,
IStack,
Predicate
} from "@thi.ng/api";
Expand All @@ -32,6 +34,7 @@ export class DCons<T>
ILength,
IReducible<any, T>,
IRelease,
ISeqable<T>,
IStack<T, T, DCons<T>> {
head: ConsCell<T> | undefined;
tail: ConsCell<T> | undefined;
Expand Down Expand Up @@ -124,12 +127,29 @@ export class DCons<T>
}
}

/** {@inheritDoc @thi.ng/api#ISeqable.seq} */
seq(start = 0, end = this.length) {
if (start >= end || start < 0) return;
let cell = this.nthCell(start);
const last = this.nthCell(end - 1);
const $seq = (cell: ConsCell<T>): ISeq<T> => ({
first() {
return cell.value;
},
next() {
return cell !== last && cell.next ? $seq(cell.next) : undefined;
}
});
return cell ? $seq(cell) : undefined;
}

*cycle() {
while (true) {
yield* this;
}
}

/** {@inheritDoc @thi.ng/transducers#IReducible.$reduce} */
$reduce(rfn: ReductionFn<any, T>, acc: any) {
let cell = this.head;
while (cell && !isReduced(acc)) {
Expand Down
33 changes: 30 additions & 3 deletions packages/dcons/test/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import * as assert from "assert";
import { DCons } from "../src/index";


describe("DCons", () => {
let a: DCons<any>, src: number[];
beforeEach(() => {
Expand All @@ -23,7 +22,35 @@ describe("DCons", () => {
assert.deepEqual([...a], src);
});

it("works as stack");
it("is seqable", () => {
assert.equal(a.seq()!.first(), 1);
// prettier-ignore
assert.equal(a.seq()!.next()!.first(), 2);
// prettier-ignore
assert.equal(a.seq(3)!.first(), 4);
// prettier-ignore
assert.equal(a.seq(3)!.next()!.first(), 5);
// prettier-ignore
assert.equal(a.seq(3)!.next()!.next(), undefined);
assert.equal(a.seq(2, 2), undefined);
assert.equal(a.seq(2, 3)!.first(), 3);
assert.equal(a.seq(2, 3)!.next(), undefined);
});

it("works as stack", () => {
assert.equal(a.push(10).pop(), 10);
assert.equal(a.pop(), 5);
a = new DCons();
assert.equal(a.pop(), undefined);
});

it("works as queue");
it("works as queue", () => {
assert.equal(a.push(10).drop(), 1);
assert.equal(a.drop(), 2);
assert.equal(a.drop(), 3);
assert.equal(a.drop(), 4);
assert.equal(a.drop(), 5);
assert.equal(a.drop(), 10);
assert.equal(a.drop(), undefined);
});
});

0 comments on commit 1cfb02a

Please sign in to comment.