嗨,我正试图使用TS构建一个不可变堆栈,但出现问题
在我的推送函数中,我试图创建一个当前head设置为next的新节点,并将其传递给Stack构造函数,但每次我这样做时,它都会说head为null。
我所有的其他函数,head
是正确的,但在我的推送函数中不是。
type Node<T> = { value: T; next: Node<T> | null };
export default class Stack<T> {
constructor(head: Node<T> | null = null) {
let size = 0;
let nextNode = head;
while (nextNode) {
size++;
nextNode = nextNode.next;
}
Object.defineProperty(this, 'peak', {
get: () => (head ? head.value : undefined),
});
Object.defineProperty(this, 'size', { get: () => size });
this.push = (value: T) => {
return new Stack({ value, next: head });
};
this.pop = () => new Stack(head ? head.next : null);
this[Symbol.iterator] = function* () {
let nextNode = head;
while (nextNode) {
yield nextNode.value;
nextNode = nextNode.next;
}
};
}
push: (value: T) => Stack<T>;
pop: () => Stack<T>;
get peak() {
return void 0;
}
get size() {
return void 0;
}
[Symbol.iterator]: any;
}
我无法重现问题:
import Stack from "../stack";
describe(Stack, () => {
test("empty",
() => {
const empty = new Stack();
expect(empty).toBeDefined();
expect(empty).toBeInstanceOf(Stack);
}
);
test("one element",
() => {
const one = new Stack({ "value": 1, "next": null });
expect(one).toBeDefined();
expect(one).toBeInstanceOf(Stack);
expect(one.peak).toEqual(1);
expect(one.pop()).not.toThrow;
const empty = one.pop();
expect(empty).toBeDefined();
expect(empty).toBeInstanceOf(Stack);
expect(empty.peak).toBeUndefined;
}
);
test("push once",
() => {
const empty = new Stack<number>();
const one = empty.push(1);
expect(one).toBeDefined();
expect(one).toBeInstanceOf(Stack);
expect(one.peak).toEqual(1);
expect(one.pop()).not.toThrow;
}
);
test("push twice",
() => {
const empty = new Stack<number>();
const two = empty.push(1).push(2);
expect(two).toBeDefined();
expect(two).toBeInstanceOf(Stack);
expect(two.peak).toEqual(2);
expect(two.pop()).not.toThrow;
const one = two.pop();
expect(one).toBeDefined();
expect(one).toBeInstanceOf(Stack);
expect(one.peak).toEqual(1);
expect(one.pop()).not.toThrow;
}
);
test("iterator",
() => {
const stack = new Stack({ "value": 0, "next": { "value": 1, "next": { "value": 2, "next": null } } });
const array = Array.from(stack);
const expected = Array.from({ "length": 3 }, (_, i) => i);
expect(array).toEqual(expected);
}
);
});
PASS tests/stack.spec.ts
Stack
✓ empty (2ms)
✓ one element (1ms)
✓ push once
✓ push twice (1ms)
✓ iterator (1ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 85.71 | 80 | 62.5 | 89.47 |
stack.ts | 85.71 | 80 | 62.5 | 89.47 | 39-43
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 5 passed, 5 total
Snapshots: 0 total
Time: 1.383s, estimated 2s
Ran all test suites.