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

Queue #95

Closed jsartisan closed 3 months ago

jsartisan commented 3 months ago

Info

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

Question

Implement a queue data structure in JavaScript. A queue follows the First-In-First-Out (FIFO) principle. Your queue should have the following methods:

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

class Queue {
  // Your implementation here
}

const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
console.log(queue.front()); // 1
console.log(queue.dequeue()); // 1
console.log(queue.size()); // 1
console.log(queue.isEmpty()); // false
queue.dequeue();
console.log(queue.isEmpty()); // true

Template

index.js

class Queue {

}

export { Queue }

index.test.js

import { Queue } from './index';

describe('Queue class', () => {
  let queue;

  beforeEach(() => {
    queue = new Queue();
  });

  test('should enqueue elements to the queue', () => {
    queue.enqueue(1);
    queue.enqueue(2);
    expect(queue.size()).toBe(2);
    expect(queue.front()).toBe(1);
  });

  test('should dequeue elements from the queue', () => {
    queue.enqueue(1);
    queue.enqueue(2);
    expect(queue.dequeue()).toBe(1);
    expect(queue.size()).toBe(1);
    expect(queue.dequeue()).toBe(2);
    expect(queue.size()).toBe(0);
  });

  test('should return undefined when dequeuing from an empty queue', () => {
    expect(queue.dequeue()).toBe(undefined);
  });

  test('should return the front element without removing it', () => {
    queue.enqueue(1);
    queue.enqueue(2);
    expect(queue.front()).toBe(1);
    expect(queue.size()).toBe(2);
  });

  test('should return undefined when peeking the front element of an empty queue', () => {
    expect(queue.front()).toBe(undefined);
  });

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

  test('should return the correct size of the queue', () => {
    expect(queue.size()).toBe(0);
    queue.enqueue(1);
    queue.enqueue(2);
    expect(queue.size()).toBe(2);
  });
});

package.json

{
  "dependencies": {},
  "main": "/index.js",
  "devDependencies": {}
}
github-actions[bot] commented 3 months ago

96 - Pull Request updated.