JSFiddle - React, Tailwind, and code Playground

by kkdaily

HTML

<h3>
(CTCI 1.3) write a method to replace all spaces in a string with "%20". You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. Ex: "Mr John Smith   ", 13 => "Mr%20John%20Smith"
</h3>

<div id="message"></div>

CSS

#message {
  padding: 10px;
}

.success {
  background-color: lightgreen;
}

.failure {
  background-color: pink;
}

JavaScript

// ex: "cat dog ", 7 => "cat%20dog"
// 1. trim the whitespace off the str (str.trim())
// 2. if the length of the str is < 1, then return error
// 3. split the str by spaces (str.split(' '))
// 4. join the str by %20 (str.join('%20'))
// 5. return result

replaceSpaces = (str) => {
	const trimmedStr = str.trim()
  
  if (!trimmedStr.length) {
  	throw new Error('string must contain at least 1 character')
  }
  
  const words = trimmedStr.split(' ')
  const replacedSpaces = words.join('%20')
  
  return replacedSpaces
}

// TESTS
test = (method, inputs, expected) => {
	const messageEl = document.getElementById('message')
  let status = 'success'
  
  const actual = method(...inputs)

	if (actual !== expected) {
		messageEl.innerText = `Test failed for ${method}. Expected: ${expected}. Actual: ${actual}`
    messageEl.classList.add('failure')
    status = 'fail'
  }
  
  if (status === 'success') {
		messageEl.innerText = 'All tests passed!'
  	messageEl.classList.add('success')
	}
}

test(replaceSpaces, [' john oliver   '], 'john%20oliver')
test(replaceSpaces, ['a'], 'a')
test(replaceSpaces, ['a b b a'], 'a%20b%20b%20a')