← Back to challenges

Nearest Chapter

JavaScriptHardobjectsmathloops

Instructions

Create a function that returns which chapter is nearest to the page you're on. If two chapters are equidistant, return the chapter with the higher page number.

Examples

nearestChapter({
  "Chapter 1" : 1,
  "Chapter 2" : 15,
  "Chapter 3" : 37
}, 10) ➞ "Chapter 2"

nearestChapter({
  "New Beginnings" : 1,
  "Strange Developments" : 62,
  "The End?" : 194,
  "The True Ending" : 460
}, 200) ➞ "The End?"

nearestChapter({
  "Chapter 1a" : 1,
  "Chapter 1b" : 5
}, 3) ➞ "Chapter 1b"

Notes

  • All page numbers in the dictionary will be valid integers.
  • Return the higher page number if ever two pages are equidistant (see last test case).
javascript
Loading editor…
to run
Walks through the solution with reasoning and edge cases.