Skip to content

Commit 15dd5ff

Browse files
authored
Create Read N Characters Given Read4 II - Call multiple times.js
1 parent bd6ee0c commit 15dd5ff

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
The API: int read4(char *buf) reads 4 characters at a time from a file.
3+
4+
The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
5+
6+
By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.
7+
8+
Note:
9+
The read function may be called multiple times.
10+
*/
11+
/**
12+
* Definition for read4()
13+
*
14+
* @param {character[]} buf Destination buffer
15+
* @return {number} The number of characters read
16+
* read4 = function(buf) {
17+
* ...
18+
* };
19+
*/
20+
21+
/**
22+
* @param {function} read4()
23+
* @return {function}
24+
*/
25+
var solution = function(read4) {
26+
let helperBuf = [];
27+
let count = 0; // how many characters read with read4
28+
let i = 0;
29+
30+
/**
31+
* @param {character[]} buf Destination buffer
32+
* @param {number} n Maximum number of characters to read
33+
* @return {number} The number of characters read
34+
*/
35+
return function(buf, n) {
36+
let pointer = 0;
37+
38+
while (pointer < n) {
39+
if (i === 0) {
40+
count = read4(helperBuf);
41+
}
42+
43+
while (i < count && pointer < n) {
44+
buf[pointer++] = helperBuf[i++];
45+
}
46+
47+
// read4 buffer used up, start over
48+
if (i === count) {
49+
i = 0;
50+
}
51+
52+
// end of file
53+
if (count < 4) {
54+
break;
55+
}
56+
}
57+
58+
return pointer;
59+
};
60+
};

0 commit comments

Comments
 (0)