The Problem: You are going to be given a word. Your job is to return the middle character of the word. If the word’s length is odd, return the middle character. If the word’s length is even, return the middle 2 characters.
My Solution
JavaScript
x
14
14
1
function isOdd(num) {
2
return num % 2;
3
}
4
5
function getMiddle(str) {
6
const middleDigit = (str.length + 1) / 2;
7
if (isOdd(middleDigit) === 1) {
8
return str[middleDigit];
9
} else {
10
return str[middleDigit - 0.5] + str[middleDigit + 0.5];
11
}
12
}
13
console.log(getMiddle(`the`));
14
But i’m receiving a NaN
output, rather than h
, where has str[input] deviated from the my intention?
Thanks in advance!
Advertisement
Answer
Your execution was a little bit off!
- I changed your isOdd function to return a boolean value, instead of a number.
- After every calculation of the middle digit I subtracted 1 from the result, as we are working with indexes (and they start the count of the positions at 0, instead of 1).
- For the second middle digit when the word length is even, you just have to do “str.length/2”, no need for adding or subtracting 1.
JavaScript
1
13
13
1
function isOdd(num) {
2
return num % 2 === 1;
3
}
4
5
function getMiddle(str) {
6
if (isOdd(str.length)) {
7
return str[((str.length + 1) / 2) - 1];
8
} else {
9
return str[(str.length / 2) - 1] + str[str.length / 2];
10
}
11
}
12
console.log(getMiddle(`the`));
13
console.log(getMiddle(`root`));