utils.js
View source code here on GitHub!
- utils.get_data_file(name, encoding)
Grab the contents of a file from the _data directory at root of this repository. Valid encodings are the same as those passed to Node.JS's fs.ReadFileSync(). 'utf8' (the default) will return a string. 'buffer' will return a raw bytestring.
- Arguments:
name (string)
encoding (string)
- Returns:
string|Buffer --
1/**
2 * Grab the contents of a file from the _data directory at root of this repository. Valid encodings are the same as
3 * those passed to Node.JS's fs.ReadFileSync(). 'utf8' (the default) will return a string. 'buffer' will return a raw
4 * bytestring.
5 * @param {string} name
6 * @param {string} encoding
7 * @return {string | Buffer}
8 */
9exports.get_data_file = function(name, encoding = 'utf8') {
10 if (process.env.APP_ENV === 'browser') {
11 const data = require(`./fallbacks/${name}.js`).value;
12 const result = Buffer.from(data, 'base64');
13 if (encoding !== 'buffer') {
14 return result.toString(encoding);
15 }
16 return result;
17 } else {
18 const fs = require('fs');
19 const path = require('path');
20
21 const filename = path.normalize(path.join(
22 __filename,
23 '..',
24 '..',
25 '..',
26 '..',
27 '_data',
28 name
29 ));
30 try {
31 return fs.readFileSync(filename, encoding);
32 } catch (e) {
33 if (e instanceof TypeError) {
34 return Buffer.from(fs.readFileSync(filename, 'utf8'), 'utf8');
35 }
36 throw e;
37 }
38 }
39};
40
41/**
42 * @param {number} n
43 * @return {number | string}
44 */
45exports.get_answer = function(n) {
46 const strN = String(n);
47 for (const line of exports.get_data_file('answers.tsv').split(new RegExp('\\r?\\n'))) {
48 const [id_, type, _, value] = line.split('\t');
49 if (id_ !== strN) {
50 continue;
51 }
52 if (type === 'str') {
53 return value;
54 }
55 return Number(value);
56 }
57 throw new Error('Answer not found');
58};