jsartisan / frontend-challenges

FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
https://frontend-challenges.com
27 stars 4 forks source link

Stack #91

Closed jsartisan closed 3 months ago

jsartisan commented 3 months ago

Info

difficulty: easy
title: Stack
type: question
template: javascript
tags: javascript

Question

Implement a stack data structure in JavaScript. A stack is a collection that follows the Last-In-First-Out (LIFO) principle. Your stack should have the following methods:

Use the following example to understand how the stack should work:

class Stack {
  // Your implementation here
}

const stack = new Stack();
stack.push(1);
stack.push(2);
console.log(stack.peek()); // 2
console.log(stack.pop());  // 2
console.log(stack.size()); // 1
console.log(stack.isEmpty()); // false
stack.pop();
console.log(stack.isEmpty()); // true

Template

index.js

class Stack {

}

export { Stack };

index.test.js

import { Stack } from './index';

describe('Stack class', () => {
  let stack;

  beforeEach(() => {
    stack = new Stack();
  });

  test('should push elements to the stack', () => {
    stack.push(1);
    stack.push(2);
    expect(stack.size()).toBe(2);
    expect(stack.peek()).toBe(2);
  });

  test('should pop elements from the stack', () => {
    stack.push(1);
    stack.push(2);
    expect(stack.pop()).toBe(2);
    expect(stack.size()).toBe(1);
    expect(stack.pop()).toBe(1);
    expect(stack.size()).toBe(0);
  });

  test('should return undefined when popping from an empty stack', () => {
    expect(stack.pop()).toBe(undefined);
  });

  test('should peek the top element without removing it', () => {
    stack.push(1);
    stack.push(2);
    expect(stack.peek()).toBe(2);
    expect(stack.size()).toBe(2);
  });

  test('should return undefined when peeking an empty stack', () => {
    expect(stack.peek()).toBe(undefined);
  });

  test('should check if the stack is empty', () => {
    expect(stack.isEmpty()).toBe(true);
    stack.push(1);
    expect(stack.isEmpty()).toBe(false);
  });

  test('should return the correct size of the stack', () => {
    expect(stack.size()).toBe(0);
    stack.push(1);
    stack.push(2);
    expect(stack.size()).toBe(2);
  });
});
github-actions[bot] commented 3 months ago

92 - Pull Request updated.