Read n characters from a source that only returns four at a time, keeping the leftovers between calls

mediumAbout 25 minutesUpdated CodingProbufferingstreamsclosures
Not solved

Share this question

Problem

Some sources only give data in fixed chunks: a decoder that emits 4 bytes at a time, a paginated API with a fixed page size, a stream with fixed-size reads. Callers still want to ask for exactly the amount they need.

// The source is "abcdefghij".
const read = createReader(read4);
read(1);  // "a"
read(5);  // "bcdef"   ("bcd" was left over from the first chunk)
read(10); // "ghij"    (the source ended)
read(3);  // ""

Ref. UR-1427 · © UIRound · uiround.com/questions/read-n-characters-from-a-source-that-only-returns-four-at-a-time

Stuck? Take a hint

Try it in the editor

Run your code as often as you like. Submitting it to the full test suite is part of Pro.

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment