Back to Freecodecamp

Challenge 73: Speak Wisely, You Must

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d2ba1468508398389487ce.md

latest2.6 KB
Original Source

--description--

Given a sentence, return a version of it that sounds like advice from a wise teacher using the following rules:

  • Words are separated by a single space.
  • Find the first occurrence of one of the following words in the sentence: "have", "must", "are", "will", "can".
  • Move all words before and including that word to the end of the sentence and:
    • Preserve the order of the words when you move them.
    • Make them all lowercase.
    • And add a comma and space before them.
  • Capitalize the first letter of the new first word of the sentence.
  • All given sentences will end with a single punctuation mark. Keep the original punctuation of the sentence and move it to the end of the new sentence.
  • Return the new sentence, make sure there's a single space between each word and no spaces at the beginning or end of the sentence.

For example, given "You must speak wisely." return "Speak wisely, you must."

--hints--

wiseSpeak("You must speak wisely.") should return "Speak wisely, you must."

js
assert.equal(wiseSpeak("You must speak wisely."), "Speak wisely, you must.");

wiseSpeak("You can do it!") should return "Do it, you can!"

js
assert.equal(wiseSpeak("You can do it!"), "Do it, you can!");

wiseSpeak("Do you think you will complete this?") should return "Complete this, do you think you will?"

js
assert.equal(wiseSpeak("Do you think you will complete this?"), "Complete this, do you think you will?");

wiseSpeak("All your base are belong to us.") should return "Belong to us, all your base are."

js
assert.equal(wiseSpeak("All your base are belong to us."), "Belong to us, all your base are.");

wiseSpeak("You have much to learn.") should return "Much to learn, you have."

js
assert.equal(wiseSpeak("You have much to learn."), "Much to learn, you have.");

--seed--

--seed-contents--

js
function wiseSpeak(sentence) {

  return sentence;
}

--solutions--

js
function wiseSpeak(sentence) {
  const triggers = ["have", "must", "are", "will", "can"];
  const punctuation = sentence[sentence.length - 1];
  const words = sentence.split(" ");

  const triggerIndex = words.findIndex(w => triggers.includes(w));

  const toMove = words.slice(0, triggerIndex + 1).map(w => w.toLowerCase());
  const remaining = words.slice(triggerIndex + 1);

  const newStart = remaining.map((w, i) => {
    return i === 0 ? w[0].toUpperCase() + w.slice(1) :
      i === remaining.length - 1 ? w.slice(0, w.length - 1) : w;
  })

  return newStart.join(" ") + ", " + toMove.join(" ") + punctuation;
}