# Spinal Tap Case - how can I improve that code?

Spinal Tap Case - how can I improve that code?
0

#1

Hi!

Finally I’ve managed to finish Spinal Tap Case
Just in time, because it is 3:30 am. Time to bed.

My solution works, but it is far from elegant solution. I can call it “brute force” method.

Please take a look at my code and send me some feedback. If you see some formatting or logical errors don’t hesitate to point it out.

I’m new to programming and I want to learn as much as I can from you guys.

More smart/elegant solution would be appreciated as well.

Thx.

function spinalCase(str) {
var lastOne;
var newArr = [];
var specialTheory = special(str);
function special(input) {
var testRegEx = str.split(/(?=[A-Z])/);
return testRegEx;
}
for(var i = 0; i<specialTheory.length; i++) {
if(i === specialTheory.length - 1 ) {
newArr.push(specialTheory[i]);
} else {
if(specialTheory[i].match(/\s/g)) {
newArr.push(specialTheory[i]);
} else {
newArr.push(specialTheory[i] + ' ');
}
}
}
var newStr = newArr.join('').toLowerCase().replace(/\s/g, '-');
if(newStr.match(/\_-/g)) {
lastOne = newStr.replace(/\_-/g, '-');
} else {
lastOne = newStr;
}
return lastOne;
}
spinalCase("This Is Spinal Tap");//should return "this-is-spinal-tap".
//spinalCase("thisIsSpinalTap");//should return "this-is-spinal-tap".
//spinalCase("The_Andy_Griffith_Show"); //should return "the-andy-griffith-show".
//spinalCase("Teletubbies say Eh-oh");//should return "teletubbies-say-eh-oh".
//spinalCase("AllThe-small Things"); //should return "all-the-small-things".

#3

Thanks! Love it! I knew there was far better solution!

I understand all of this, except \$1 and \$2. What does it mean exactly?

It means something like this?

Find every lower case letter that is immediately followed by an upper case, than take that lower case letter (first expression ([a-z]) = \$1) put dash (-) and than put upper case (second expression ([A-Z]) = \$2) ?

#5

@P1xt

Nice! Thank you very much for this explanation! It is very helpful! Now I can go to bed, and tomorrow start with next challenge with clear mind, because I’ve fully understood this one.

#7

There seems to be a bit of a “bug” with that challenge. I mean you obviously SHOULD use RegExp but you can easily just write:

if(str === “what ever the input”){
str = "what ever the output,lol"
return str
}

Its obviously cheating, but just saying