HTTP Range Header Parser (JavaScript)

Parse a single-range HTTP Range header, resolve open ends against a resource size and return a satisfiable byte range.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
export function parseRange(header, size) {
  if (!header || typeof header !== 'string') return null;
  const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
  if (!match) return { unsatisfiable: true };
  const [, startRaw, endRaw] = match;
  if (startRaw === '' && endRaw === '') return { unsatisfiable: true };
  let start;
  let end;
  if (startRaw === '') {
    const suffix = Number(endRaw);
    if (suffix === 0) return { unsatisfiable: true };
    start = Math.max(size - suffix, 0);
    end = size - 1;
  } else {
    start = Number(startRaw);
    end = endRaw === '' ? size - 1 : Number(endRaw);
  }
  if (start > end || start >= size) return { unsatisfiable: true };
  return { start, end: Math.min(end, size - 1), length: Math.min(end, size - 1) - start + 1 };
}

How the snippet works

HTTP Range Header Parser (JavaScript) comes down to the function parseRange.

Returns a newly built value, leaving the inputs as they were.

Points of care

  • The guard !header || typeof header !== 'string' short-circuits the flow with an early return when its condition holds.

Applying it

The main signature reads export function parseRange(header, size)

Treat parseRange as the API: import it, and ignore the supporting code.

Statements that matter

return { start, end: Math.min(end, size - 1), length: Math.min(end, size - 1) - start + 1 };
if (startRaw === '' && endRaw === '') return { unsatisfiable: true };
if (start > end || start >= size) return { unsatisfiable: true };

Interactive Tools for This Topic

FAQ

Does `parseRange` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. The file defines `parseRange` at load time.