Skip to content

Instantly share code, notes, and snippets.

@LukeTully
Last active September 12, 2016 11:48
Show Gist options
  • Save LukeTully/263dca7ec37fac5067726b627b4eb4c3 to your computer and use it in GitHub Desktop.
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
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