Last active
January 29, 2025 07:08
-
-
Save sandrabosk/53ccfb1641831309b19cc33877355b3d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ************************************************************************************ | |
// https://www.codewars.com/kata/56747fd5cb988479af000028/train/javascript | |
// 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. | |
// Examples: | |
// getMiddle("test") should return "es" | |
// getMiddle("testing") should return "t" | |
// getMiddle("middle") should return "dd" | |
// getMiddle("A") should return "A" | |
// ************************************************************************************ | |
// Solution 1 | |
function getMiddle(string) { | |
let middleIndex = string.length / 2; | |
if (string.length % 2 == 0) { | |
// if the string is even | |
return string.slice(middleIndex - 1, middleIndex + 1); | |
} else { | |
// if the string is odd | |
return string.charAt(middleIndex); | |
} | |
} | |
// Solution 2 | |
function getMiddle(string) { | |
let middleIndex = string.length / 2; | |
if (string.length % 2) { | |
// if its odd you will always get a remainder of 1 | |
return string.charAt(middleIndex); | |
} else { | |
// otherwise the string is even | |
return string.slice(middleIndex - 1, middleIndex + 1); | |
} | |
} | |
// Solution 3 | |
function getMiddle(s) { | |
let position; | |
let length; | |
if (s.length % 2) { | |
position = s.length / 2; | |
length = 1; | |
} else { | |
position = s.length / 2 - 1; | |
length = 2; | |
} | |
return s.substring(position, position + length); | |
} | |
// Solution 4 | |
function getMiddle(s) { | |
return s.substr(Math.ceil(s.length / 2 - 1), s.length % 2 === 0 ? 2 : 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment