I’m stuck on the “Implement a Stack” lab. Tests 2, 6, and 16 keep failing even though my code seems correct.
Tests failing:
-
- push function should add an element to the top of the stack
-
- pop function should return falsy values correctly
-
- clear function should remove all elements from the stack
My code:
function initStack() {
return [];
}
function push(stack, item) {
stack[stack.length] = item;
}
function pop(stack) {
if (stack.length === 0) return undefined;
const removed = stack[stack.length - 1];
stack.length--;
return removed;
}
function peek(stack) {
if (stack.length === 0) return undefined;
return stack[stack.length - 1];
}
function isEmpty(stack) {
return stack.length === 0;
}
function clear(stack) {
while (stack.length > 0) {
pop(stack);
}
}
What I’ve tried:
Using stack.push(item) and stack.pop() directly
Using a class with a collection array
Returning undefined vs not returning anything
Different ways to clear the stack
What happens:
All other tests pass except these three. The code works correctly when I test it manually.
Has anyone else encountered this issue with this lab? Is there something specific the validator is looking for that I’m missing?
Thanks in advance for any help!