I am trying to make a simple karaoke queue app to help learn the basics of JavaScript and I’m not exactly sure where I am going wrong.
I have been tweaking it to try and get around this type error (for instance the whole let queue = inputArray
bits I know it’s redundant), but the main goal is to have a queue that you can rotate and add new people while adding them after the last person to sign up, not necessarily the actual end of the qeueue. (I know I haven’t added a way to catch if someone is already in the queue yet) I am hoping someone has some insight as to where the type error is coming from… Thank you in advance!
var queueCounter = 0;
var singerQueue = [];
function rotateQueue(inputArray) {
let queue = inputArray;
let currentSinger = queue.shift();
queue.Push(currentSinger);
return queue;
}
function addNewSinger(inputArray, newSinger) {
let queue = inputArray;
if (singerQueue == undefined || singerQueue.length == 0) {
queueCounter++;
queue.push([queueCounter, newSinger]); // Here is TypeError
} else {
let lastSinger;
queue.forEach(value => {
if (value[0] == queueCounter) {
lastSinger = value;
}
});
if (lastSinger == undefined) {
return 'ERROR';
} else {
let index = queue.indexOf(lastSinger);
queueCounter++;
queue.splice(index, 0, [queueCounter, newSinger]);
return queue;
}
}
}
singerQueue = addNewSinger(singerQueue, 'Some Name');
singerQueue = addNewSinger(singerQueue, 'Another Name');
singerQueue = rotateQueue(singerQueue);
console.log(singerQueue);
// assuming this output should be:
// [[2, 'Another Name'], [1, 'Some Name']]
2
Answers
I think the issue you’re having is that you’re not returning anything from the first if block of the addNewSinger function. This would be the case if you’re assigning the returned value anywhere.
It’s actually not necessary to return anything because array operations modify the array in place.
Some other minor issues are:
Here’s your code after some minor tweaks.
It is not trivial to figure out what you wanted, but here is my guess
Note I modify the array in place. You only need to copy and return if you want the original array intact, but since it is empty to begin with, we can dispense with all the copy and return