Tonight I did the string-incrementer kata on codewars. There are many ways to do it, and many ways shorter than mine!
function incrementString (strng) {
let last=strng.split("").pop(); // // convert strng to array, grab last element
let lastNum = parseInt(last) // try to convert it to an int
if (isNaN(lastNum)) { // check if that worked
return strng+"1" // return the proper string if it doesn't end in a number
}
else {
let fullNum = (strng.match(/\d+$/)[0]); // grab all numbers at end
let numLength = fullNum.length // get the length of initial number
fullNum = parseInt(fullNum) + 1// convert from string to int (and lose leading 0's) and increment
let outBase = out.slice(0,(strng.match(/\d+$/).index)).join("")
// make a string of the chars up to where it turned into numbers
let outNum = String(fullNum) // stringify the incremented number
while (outNum.length < numLength) outNum = "0" + outNum // front-pad the number string
let output = (outBase + ((outNum))) // create output result
return output // return the desired output
}
}
// test cases
// incrementString("hello010")
// incrementString("hello")
// incrementString("hello010")
// incrementString("hello")
incrementString("foobar000")
// incrementString("foo")
// incrementString("foobar001")
// incrementString("foobar99")
// incrementString("foobar099")
// incrementString("")
I’m looking forward to refactoring it when I have an idea of how to do it faster and in fewer steps. Right now I could jam it into fewer lines, but I don’t think I could do it and maintain or increase code clarity.
I got to what I considered to be the answer pretty quickly, but then realized I had read the assignment fairly poorly (a definite area of improvement) and I needed to figure out the “leading zero problem”: when a number with leading zeros is converted to an int all of those zeros are trimmed. I ended up grabbing the start length and making sure it was padded up to there with zeros.