-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathin.js
60 lines (51 loc) · 1.39 KB
/
in.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
const path = require('path')
const fs = require('fs')
/**
* Parses a line to Integer.
* @param {string} line String representing a number
* @returns {number} The integer number
*/
const toInt = (line) => parseInt(line, 10)
/**
* In
* @classdesc JavaScript implementation of In.
* @see {@link https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/In.java.html}
*/
class In {
/**
* Constructs a new File reader.
* @param {string} fileName The name of the file to read from.
*/
constructor (fileName) {
this.fileName = path.resolve(fileName)
this.content = fs.readFileSync(this.fileName, 'utf8').toString().trim()
}
/**
* Returns if the In is empty.
*/
isEmpty () {
return this.content.length === 0
}
/**
* Parses the file's content to and
* array of strings separated by new lines and whitespace,
* then, it returns the first element of the array.
*/
readString () {
if (!this._isArrayOfStrings) {
this.content = this.content.split(/[\n\r\s]*/)
this._isArrayOfStrings = true
}
if (this.isEmpty()) throw new ReferenceError(`stream ${this.fileName} is empty`)
const string = this.content.shift()
return string
}
/**
* Parses the file's contents to Integers
* @returns {[number]} The array of parsed integers.
*/
readAllInts () {
return this.content.split('\n').map(toInt)
}
}
module.exports = In