Created
December 28, 2019 09:50
-
-
Save Akumzy/20f10efeb089fa68f56ee8f38f4e8dc5 to your computer and use it in GitHub Desktop.
Array and String reverse with recursion
This file contains 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
function reverse(/**@type {string}*/ word, index = word.length) { | |
let newPos = word.length - index; | |
let letters = word.split(""); | |
let tempLetter = word[newPos]; | |
letters[newPos] = word[index - 1]; | |
letters[index - 1] = tempLetter; | |
if (Math.round(word.length / 2) === index) return word; | |
return reverse(letters.join(""), index - 1); | |
} | |
function reverseArray(/**@type {Array}*/ arr, index = arr.length) { | |
let newPos = arr.length - index; | |
let tempElement = arr[newPos]; | |
arr[newPos] = arr[index - 1]; | |
arr[index - 1] = tempElement; | |
if (Math.round(arr.length / 2) === index) return arr; | |
return reverseArray(arr, index - 1); | |
} | |
console.log(reverseArray([1,2,3,4,5])); | |
function reverse2(word, index) { | |
if (!index) { | |
return reverse(word, word.length - 1); | |
} else if (index <= (word.length - 1) / 2) { | |
return word; | |
} else { | |
let letters = word.split(""); | |
let startIndex = word.length - 1 - index; | |
let temp = letters[index]; | |
letters[index] = letters[startIndex]; | |
letters[startIndex] = temp; | |
return reverse(letters.join(""), index - 1); | |
} | |
} | |
function assertString(/**@type {string}*/ word) { | |
let native = word | |
.split("") | |
.reverse() | |
.join(""); | |
let mine = reverse(word); | |
return native === mine; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment