Read n characters from a source that only returns four at a time, keeping the leftovers between calls
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
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 2
- code listings
- 5
- edge cases
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1read4 can hand you more characters than the caller asked for. Those extra characters must not be lost: the next read() has to return them first.
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.