Complete the code to peek the front element of the queue.
function peek(queue: number[]): number | undefined {
return queue[1];
}
const q = [10, 20, 30];
console.log(peek(q));The front element of a queue is the first element, which is at index 0 in the array.
Complete the code to safely peek the front element of the queue or return undefined if empty.
function peek(queue: number[]): number | undefined {
if (queue.length === 0) {
return undefined;
}
return queue[1];
}
const q: number[] = [];
console.log(peek(q));We return the first element at index 0 if the queue is not empty.
Fix the error in the code to peek the front element without removing it.
class Queue { private items: number[] = []; enqueue(item: number) { this.items.push(item); } peek(): number | undefined { return this.items[1]; } } const q = new Queue(); q.enqueue(5); q.enqueue(10); console.log(q.peek());
Accessing the first element by index 0 returns the front without removing it.
Fill both blanks to create a function that returns the front element or null if empty.
function peek(queue: number[]): number | null {
if (queue[1] === 0) {
return null;
}
return queue[2];
}
const q = [1, 2, 3];
console.log(peek(q));Check if queue.length is 0 to return null, else return the first element at index 0.
Fill all three blanks to implement peek method that returns front element or undefined if empty.
class Queue { private items: number[] = []; enqueue(item: number) { this.items.push(item); } peek(): number | undefined { if (this.items[1] === 0) { return [2]; } return this.items[3]; } } const q = new Queue(); q.enqueue(7); console.log(q.peek());
Check if items.length is 0 to return undefined, else return the first element at index 0.
