Hi there, I’m trying to solve this algorithm without using any regex. What I would like to do is something like this:
function spinalCase(str) {
var arr = str.split('');
for (var i = 0; i < arr.length - 1; i++){
//if the char is a " " or "_" replace with "-"
if (arr[i] === " " || arr[i] === "_"){
arr[i] = "-";
} else {
//otherwise, check if the next char is upper and the current char is lower,
//if true splice appropriately
if (isUpper(arr[i+1]) && isLower(arr[i])){
arr.splice(i+1, 0, "-");
}
}
}
return arr.join('').toLowerCase();
}
function isUpper(x){
return x === x.toUpperCase();
}
function isLower(x){
return x === x.toLowerCase();
}
spinalCase('AllThe-small Things');
When I try to run this code I actually get an infinite loop warning and the program will not run. I’m not sure why this is so if someone could explain that would be gret. Is this because I am changing the length of the array during the loop? When the loop is first executed and arr.length - 1 is calculated is it a fixed value for the duration of the entire loop? Or is it recalculated with every iteration?
@Swoodend, since you’re splicing with a delete count of 0, it’s constantly increasing the length of arr.
So your i variable will never reach the end of your array.
Hm. Could you explain why it will not reach the end of the loop. I understand that I am increasing the length off arr, but isn’t the stop condition (arr.length -1) in the for loop tested every iteration?
For instance, if I increase the length of arr by 3, wont (arr.length - 1) also increase by 3, and, instead of being an infinite loop it will just iterate 3 more times? I dont understand why this isn’t the case.