Last active
September 12, 2016 11:48
-
-
Save LukeTully/263dca7ec37fac5067726b627b4eb4c3 to your computer and use it in GitHub Desktop.
Example implementation of basic algorithm to reverse the characters of words in a sentence and return it as a string
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
var exampleString = "This is an example String"; | |
var words = parseWords(exampleString); | |
var reversedWords = []; | |
var finishedString = ''; | |
for(var i = 0; i < words.length; i++){ | |
// Reverse each word and push it into the final list | |
reversedWords.push(quickSwap(words[i])); | |
} | |
finishedString = reversedWords.join(' '); | |
console.log(finishedString); | |
function quickSwap (word) { | |
var i = 0, j = word.length - 1, | |
charArray = word.split(''); | |
while (i < j) { | |
swap(charArray, i, j); | |
i++; | |
j--; | |
} | |
return charArray.join(''); | |
} | |
function swap(items, first, second) { | |
var temp = items[second]; | |
items[second] = items[first]; | |
items[first] = temp; | |
} | |
function parseWords (sentence){ | |
var _sentence = sentence, | |
words = []; | |
// Minimal check to see if this string contains space characters indicating a sentence | |
if (_sentence.indexOf(' ') !== -1) { | |
words = _sentence.split(' '); | |
} | |
return words; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment