Skip to content

Instantly share code, notes, and snippets.

@SevanBadal
Last active December 13, 2023 02:45
Show Gist options
  • Save SevanBadal/451983c9d02f8f1a4a9a4d870ee804dc to your computer and use it in GitHub Desktop.
Save SevanBadal/451983c9d02f8f1a4a9a4d870ee804dc to your computer and use it in GitHub Desktop.
Daily Quest reverseWords. Quest from https://daily-quest-tau.vercel.app
{
"name": "daily-quest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^29.7.0"
}
}
// using built-in methods
function reverseWords(words) {
return words.split(" ").reverse().join(" ")
}
// no built-in methods: .length, .split, .reverse, .join
function reverseWordsRaw(words) {
let index = 0
let currentCharacter = words[index]
let currentWord = ""
let wordList = []
let wordCount = 0
let outputString = ""
// loop over each character to build a word list based on " " (space char)
while (currentCharacter) {
if (currentCharacter === " ") {
wordList[wordCount] = currentWord
currentWord = ""
wordCount++
} else {
currentWord += currentCharacter
}
index++
currentCharacter = words[index]
// check for last iteration and push word
if (!currentCharacter && currentWord) {
wordList[wordCount] = currentWord
wordCount++
}
}
// clear current word and reset index count
index = wordCount - 1
// work backwords over our word list to build our output string
while (index >= 0) {
outputString += wordList[index]
// determine if space is needed
if (index - 1 >= 0) {
outputString += " "
}
index--
}
return outputString
}
module.exports = reverseWords
const reverseWords = require('./reverse-words');
describe('reverseWords', () => {
test('should reverse the words in a string', () => {
expect(reverseWords('hello world and hello mars')).toEqual('mars hello and world hello');
});
test('should return single word if only one word is given', () => {
expect(reverseWords('hello')).toEqual('hello');
});
test('should handle empty string', () => {
expect(reverseWords('')).toEqual('');
});
// Add more tests as needed
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment