Menu

Parse a page selection completely or not at all
📰

Parse a page selection completely or not at all

DEV Community: javascript·Yan Wang·17 days ago
#XtmORcO5
#devtojavascript#devto#dev#const#null
Reading 0:00
15s threshold

A page-selection field looks small until you ask what should happen with 1, , 2junk , or 1-1000,1 . A forgiving parser might quietly keep the part it understands. For a document operation, that can leave the user with a different selection from the one they meant.

This example takes a narrower approach: under an explicit teaching policy, it accepts the entire input or returns null . It converts displayed page numbers, which start at one, into zero-based indices. It does not open or modify a PDF.

Define the contract before parsing

The grammar accepts ASCII positive integers and inclusive ranges separated by commas. Whitespace is allowed around tokens but not inside a range. Descending ranges are valid. If a page occurs more than once, the output keeps its first occurrence, so 4-2,2,6 becomes [3,2,1,5] for a six-page document.

The policy rejects leading zeroes, full-width digits, semicolons, empty tokens, trailing text, and out-of-range pages.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.