-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
104 lines (65 loc) · 1.98 KB
/
app.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const fs = require("fs");
const express = require("express");
const app = express();
let PIString = "";
app.set("view engine", "ejs");
app.use("/public", express.static("public"));
app.get("/", async(err, res) => {
res.render("homePage");
});
/**
* The path to recieve get requests with a parameter of the string to search in Pi.
*/
app.get("/get/:digits", (request, response) => {
const search = request.params.digits;
let index = getIndexNumber(PIString, search);
if (search == `3`) {
index = 10;
}
const text = index > 0 ? PIString.slice(index + search.length).slice(0, 15) : "";
const reverseText = index > 0 ? PIString.split("").
reverse().
join("").
slice(PIString.length - (index + search.length) + search.length).
slice(0, 15).
split("").
reverse().
join("") : "";
/**
* Wrapped as an object, sent as callback data.
*/
response.send({indexOf: index - 1,
strAfter: text,
reverse: reverseText});
});
const stream = fs.createReadStream("pi-million.txt");
stream.on("data", (partialData) => {
PIString += partialData;
});
stream.on("end", () => {
console.log("Ended to load PI.");
});
app.listen(process.env.PORT || 3000, () => console.log(`Port has been started listening at ${process.env.PORT || 3000}`));
/**
*
* @param {string} txt The whole string to make search in.
* @param {string} search The string to find index in the text.
*/
function getIndexNumber(txt, search) {
const start = search.charAt(0);
for (let i = 0; i < txt.length; i++) {
if (txt.charAt(i) === start) {
let found = true;
for (let j = 1; j < search.length; j++) {
if (txt.charAt(i + j) !== search.charAt(j)) {
found = false;
break;
}
}
if (found) {
return i;
}
}
}
return -1;
}