JSFiddle - React, Tailwind, and code Playground

by kkdaily

HTML

<h1>
  Say you have a book with an arbitrary number of pages. You flip to a random page in the book. Write a program that returns the longest sentence on this page. [easy]
  
  What if you had to find the page number that contains the longest sentence in the entire book? Assume you're given an array of strings where each string represents a book page and the pages are sorted sequentially starting with page number 1. [medium]
</h1>

JavaScript

const testPage = `
	The sly fox. Jumped over! The lazy dog? Testing. Test!
`

const longestSentence = (page) => {
	const sentences = getSentences(page)
  let longestSentence = sentences[0]
  
  sentences.forEach((sentence) => {
  	if (longestSentence.length < sentence.length) {
    	longestSentence = sentence
    }
  })
  
  return longestSentence
}

const getSentences = (str) => {
	const sentences = []
  let page = str
  let period = '.'
  let exclamationMark = '!'
  let questionMark = '?'
 
  while (page.length) {
  	if (str.indexOf(period) < str.indexOf(exclamationMark) && str.indexOf(period) < str.indexOf(questionMark)) {
    	handleSentenceFound(period, page, sentences)
    }
    else if (str.indexOf(exclamationMark) < str.indexOf(period) && str.indexOf(exclamationMark) < str.indexOf(questionMark)) {
    	handleSentenceFound(exclamationMark, page, sentences)
    }
    else if (str.indexOf(questionMark) < str.indexOf(period) && str.indexOf(questionMark) < str.indexOf(exclamationMark)) {
    	handleSentenceFound(questionMark, page, sentences)
    }
  }
  
  return sentences
}

const handleSentenceFound = (sentenceEnd, page, sentences) => {
	let sentence = str.slice(0, sentenceEnd)
  sentences.push(sentence)
  page = page.slice(sentenceEnd, page.length - 1)
}

const result = longestSentence(testPage)
alert(result)