I am training on kata from CodeWars that can be found here https://www.codewars.com/kata/56747fd5cb988479af000028/train/javascript
I could not understand other solutions. My try is it:
const getMiddle = (s) => {
let middle = ""
for(let i = 0; i < s.length; i++) {
if(s.length % 2 === 1) {middle = s[s.length-1/2]}
if(s.length % 2 === 0) {middle = s[s.length-1/2-1] + s[s.length-1/2]}
} return middle
}
You're making this far more complicated than it needs to be.
You don't need a loop, since the length is not dependent on i.
Instead of checking whether the length is odd or even, you can just divide by 2 and round down.
function getMiddle(s) {
return Math.floor(s.length / 2);
}
s.length / 2 will return number in floating point if the s length's is odd
console.log(5 / 2);
console.log(6 / 2);
You have to parse it to int either using parseInt, or there is a shortcut that you can use as
(s.length / 2 - 1) | 0
const a = 5 / 2;
console.log(parseInt(a));
console.log(a | 0);
const getMiddle = (s) => {
let middle = "";
if (s.length % 2 === 1) middle = [s[(s.length / 2) | 0]];
else middle = [s[(s.length / 2 - 1) | 0], s[(s.length / 2) | 0]];
return middle.join("");
};
console.log(getMiddle("A"));
console.log(getMiddle("HELMO"));
console.log(getMiddle("HELLO0"));
Do not iterate letters. You can simply do it for the even and odd lengths of strings.
const getMiddle = (s) => {
return s[Math.floor(s.length/2)]
}
console.log(getMiddle("abc"));
console.log(getMiddle("abcd"));
console.log(getMiddle("abcde"));
console.log(getMiddle("abcdef"));
console.log(getMiddle("abcdefg"));