Invert strings
Getting close to finishing my Masters I recently started to interview for employment opportunities. As I have a Computer Science background this involves doing some programming. After all potential employers want to find out if I can code. These practical tests need to be short yet tell you something about the applicants skill level. One challenge I faced was to invert a string. And as JavaScript is my favorite programming language here are four way to do that in JS.
For loop
The always reliable fall that will surely work. For loops are a basic concept in programming. Pay special attention how this loop counts down instead of up.
function forLoopInvert(string) {
let result = ''
for(let i = string.length - 1; i >= 0; i--) {
result += string.charAt(i)
}
return result
}
Reverse and array
Since arrays in JavaScript come with a build in ´reverse´ function we can simply use that.
function arrayInvert(string) {
return string.split('').reverse().join('')
}
Fancy Arrays things
While we create an array from our string we might as well use a more functional approach in the sense that we can use reduce to create a new string from the array.
function reduceInvert(string) {
return string.split('').reduce((result, char) => {
return char + result
}, '')
}
Recursion
Ahh the height of programming: recursion. Where every Computer Science student gets to experience a stack overflow and popular websites get their name.
function recursiveInvert(string) {
if(string.length > 1) {
return string.substring(string.length - 1) + recursiveInvert(string.substring(0, string.length - 1))
} else {
return string
}
}
Conclusion
As always in programming you have many ways to solve the same problem. At an interview the fanciness of your code will come down to your nerves as well as proficiency at the language you use. So if in doubt make up methods things have and fall back on for loops 😉