-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathread-n-characters-given-read4.js
71 lines (63 loc) · 1.61 KB
/
read-n-characters-given-read4.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Read N Characters Given Read4
*
* The API: int read4(char *buf) reads 4 characters at a time from a file.
*
* 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.
*
* By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from
* the file.
*
* Example 1:
*
* Input: buf = "abc", n = 4
* Output: "abc"
* Explanation: The actual number of characters read is 3, which is "abc".
*
* Example 2:
*
* Input: buf = "abcde", n = 5
* Output: "abcde"
*
* Note:
* The read function will only be called once for each test case.
*/
/**
* Definition for read4()
*
* @param {character[]} buf Destination buffer
* @return {number} The number of characters read
* read4 = function(buf) {
* ...
* };
*/
/**
* @param {function} read4()
* @return {function}
*/
const solution = read4 => {
/**
* @param {character[]} buf Destination buffer
* @param {number} n Maximum number of characters to read
* @return {number} The number of characters read
*/
return (buf, n) => {
let eof = false; // end of file flag
let total = 0; // total bytes have read
const buffer = Array(4); // temp buffer
while (!eof && total < n) {
const size = read4(buffer);
// Check if it's the end of the file
eof = size < 4;
// Get the actual count
const count = Math.min(size, n - total);
// Copy from temp buffer to buf
for (let i = 0; i < count; i++) {
buf[total++] = buffer[i];
}
}
return total;
};
};
export { solution };