From c96213137ef8bd48ba3b06c609fca6d005fe8c6b Mon Sep 17 00:00:00 2001 From: robonen Date: Sat, 26 Oct 2024 06:37:27 +0700 Subject: [PATCH] refactor(packages/stdlib): stack return undefined on peek if it empty --- packages/stdlib/src/structs/stack/index.test.ts | 6 ++++-- packages/stdlib/src/structs/stack/index.ts | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/stdlib/src/structs/stack/index.test.ts b/packages/stdlib/src/structs/stack/index.test.ts index e67522a..7d3920a 100644 --- a/packages/stdlib/src/structs/stack/index.test.ts +++ b/packages/stdlib/src/structs/stack/index.test.ts @@ -79,9 +79,11 @@ describe('stack', () => { 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(); - expect(() => stack.peek()).toThrow(new RangeError('Stack is empty')); + const topElement = stack.peek(); + + expect(topElement).toBeUndefined(); }); }); diff --git a/packages/stdlib/src/structs/stack/index.ts b/packages/stdlib/src/structs/stack/index.ts index db48251..6a6d1af 100644 --- a/packages/stdlib/src/structs/stack/index.ts +++ b/packages/stdlib/src/structs/stack/index.ts @@ -96,7 +96,7 @@ export class Stack implements Iterable, AsyncIterable { */ public peek() { if (this.isEmpty) - throw new RangeError('Stack is empty'); + return undefined; return last(this.stack); }