1
0
mirror of https://github.com/robonen/tools.git synced 2026-03-20 10:54:44 +00:00

refactor(packages/stdlib): stack return undefined on peek if it empty

This commit is contained in:
2024-10-26 06:37:27 +07:00
parent 8080e7eafe
commit c96213137e
2 changed files with 5 additions and 3 deletions

View File

@@ -79,9 +79,11 @@ describe('stack', () => {
expect(stack.length).toBe(3); expect(stack.length).toBe(3);
}); });
it('throw an error if the stack is empty', () => { it('return undefined if the stack is empty', () => {
const stack = new Stack<number>(); const stack = new Stack<number>();
expect(() => stack.peek()).toThrow(new RangeError('Stack is empty')); const topElement = stack.peek();
expect(topElement).toBeUndefined();
}); });
}); });

View File

@@ -96,7 +96,7 @@ export class Stack<T> implements Iterable<T>, AsyncIterable<T> {
*/ */
public peek() { public peek() {
if (this.isEmpty) if (this.isEmpty)
throw new RangeError('Stack is empty'); return undefined;
return last(this.stack); return last(this.stack);
} }