merger, changedataversion, motd refactor

This commit is contained in:
YourFriendlyNeighborhoodDealer 2019-08-14 10:34:55 +02:00
parent 9cacee321c
commit 50a1dd91eb
3 changed files with 364 additions and 398 deletions

View file

@ -1,32 +1,31 @@
const utils = require('./utils.js'); const utils = require('../utils/utils.js')
const dataFile = "public/data.json"; const dataFile = '../public/data.json'
const versionFile = "public/version"; const versionFile = '../public/version'
var p = GetParams(); var p = GetParams()
if (p.length <= 0) { if (p.length <= 0) {
console.log("no params!"); console.log('no params!')
process.exit(0); process.exit(0)
} }
var param = p.join(' ')
var param = p.join(" "); console.log('param: ' + param)
console.log("param: " + param); var d = utils.ReadFile(dataFile)
var parsed = JSON.parse(d)
var d = utils.ReadFile(dataFile); console.log('Old version:')
var parsed = JSON.parse(d); console.log(parsed.version)
console.log("Old version:"); parsed.version = param
console.log(parsed.version);
parsed.version = param; console.log('New version:')
console.log(parsed.version)
console.log("New version:"); utils.WriteFile(JSON.stringify(parsed), dataFile)
console.log(parsed.version); utils.WriteFile(parsed.version, versionFile)
utils.WriteFile(JSON.stringify(parsed), dataFile); function GetParams () {
utils.WriteFile(parsed.version, versionFile); return process.argv.splice(2)
function GetParams() {
return process.argv.splice(2);
} }

View file

@ -22,280 +22,256 @@
// join json datas, or raw datas // join json datas, or raw datas
// or something else // or something else
const minMatchAmmount = 55; const minMatchAmmount = 55
const minResultMatchPercent = 99; const minResultMatchPercent = 99
const lengthDiffMultiplier = 10; const lengthDiffMultiplier = 10
class Question { class Question {
constructor(q, a, i) { constructor (q, a, i) {
this.Q = q; this.Q = q
this.A = a; this.A = a
this.I = i; this.I = i
} }
toString() { toString () {
var r = "?" + this.Q + "\n!" + this.A; var r = '?' + this.Q + '\n!' + this.A
if (this.I) if (this.I) { r += '\n>' + this.I }
r += "\n>" + this.I; return r
return r; }
} HasQuestion () {
HasQuestion() { return this.Q != undefined
return this.Q != undefined; }
} HasAnswer () {
HasAnswer() { return this.A != undefined
return this.A != undefined; }
} HasImage () {
HasImage() { return this.I != undefined
return this.I != undefined; }
} IsComplete () {
IsComplete() { return this.HasQuestion() && this.HasAnswer()
return this.HasQuestion() && this.HasAnswer(); }
} // TODO: TEST DIS
// TODO: TEST DIS Compare (q2, i) {
Compare(q2, i) { if (typeof q2 === 'string') {
if (typeof q2 == 'string') { var qmatchpercent = Question.CompareString(this.Q, q2)
var qmatchpercent = Question.CompareString(this.Q, q2);
if (i == undefined || i.length == 0) if (i == undefined || i.length == 0) { return qmatchpercent } else {
return qmatchpercent; if (this.HasImage()) {
else { const imatchpercent = this.HasImage() ? Question.CompareString(this.I.join(' '), i.join(' '))
if (this.HasImage()) { : 0
const imatchpercent = this.HasImage() ? Question.CompareString(this.I.join(" "), i.join(" ")) : return (qmatchpercent + imatchpercent) / 2
0; } else {
return (qmatchpercent + imatchpercent) / 2; qmatchpercent -= 30
} else { if (qmatchpercent < 0) { return 0 } else { return qmatchpercent }
qmatchpercent -= 30; }
if (qmatchpercent < 0) }
return 0; } else {
else const qmatchpercent = Question.CompareString(this.Q, q2.Q)
return qmatchpercent; const amatchpercent = Question.CompareString(this.A, q2.A)
} if (this.I != undefined) {
} const imatchpercent = this.I == undefined ? Question.CompareString(this.I.join(' '), q2.I.join(
} else { ' ')) : 0
const qmatchpercent = Question.CompareString(this.Q, q2.Q); return (qmatchpercent + amatchpercent + imatchpercent) / 3
const amatchpercent = Question.CompareString(this.A, q2.A); } else {
if (this.I != undefined) { return (qmatchpercent + amatchpercent) / 2
const imatchpercent = this.I == undefined ? Question.CompareString(this.I.join(" "), q2.I.join( }
" ")) : 0; }
return (qmatchpercent + amatchpercent + imatchpercent) / 3; }
} else { static CompareString (s1, s2) {
return (qmatchpercent + amatchpercent) / 2; s1 = SimplifyStringForComparison(s1).split(' ')
} s2 = SimplifyStringForComparison(s2).split(' ')
} var match = 0
} for (var i = 0; i < s1.length; i++) {
static CompareString(s1, s2) { if (s2.includes(s1[i])) { match++ }
s1 = SimplifyStringForComparison(s1).split(" "); }
s2 = SimplifyStringForComparison(s2).split(" "); var percent = Math.round(((match / s1.length) * 100).toFixed(2)) // matched words percent
var match = 0; var lengthDifference = Math.abs(s2.length - s1.length)
for (var i = 0; i < s1.length; i++) percent -= lengthDifference * lengthDiffMultiplier
if (s2.includes(s1[i])) if (percent < 0) { percent = 0 }
match++; return percent
var percent = Math.round(((match / s1.length) * 100).toFixed(2)); // matched words percent }
var lengthDifference = Math.abs(s2.length - s1.length);
percent -= lengthDifference * lengthDiffMultiplier;
if (percent < 0)
percent = 0;
return percent;
}
} }
class Subject { class Subject {
constructor(n) { constructor (n) {
this.Name = n; this.Name = n
this.Questions = []; this.Questions = []
} }
get length() { get length () {
return this.Questions.length; return this.Questions.length
} }
AddQuestion(q) { AddQuestion (q) {
this.Questions.push(q); this.Questions.push(q)
} }
toString() { toString () {
var r = []; var r = []
for (var i = 0; i < this.Questions.length; i++) for (var i = 0; i < this.Questions.length; i++) { r.push(this.Questions[i].toString()) }
r.push(this.Questions[i].toString()); return '+' + this.Name + '\n' + r.join('\n')
return "+" + this.Name + "\n" + r.join("\n"); }
}
} }
class QuestionDB { class QuestionDB {
constructor() { constructor () {
this.Subjects = []; this.Subjects = []
} }
get length() { get length () {
return this.Subjects.length; return this.Subjects.length
} }
AddQuestion(subj, q) { AddQuestion (subj, q) {
var i = 0; var i = 0
while (i < this.Subjects.length && this.Subjects[i].Name != subj) while (i < this.Subjects.length && this.Subjects[i].Name != subj) { i++ }
i++; if (i < this.Subjects.length) { this.Subjects[i].AddQuestion(q) } else {
if (i < this.Subjects.length) const n = new Subject(subj)
this.Subjects[i].AddQuestion(q); n.AddQuestion(q)
else { this.Subjects.push(n)
const n = new Subject(subj); }
n.AddQuestion(q); }
this.Subjects.push(n); AddSubject (subj) {
} var i = 0
} while (i < this.length && subj.Name != this.Subjects[i].Name) { i++ }
AddSubject(subj) {
var i = 0;
while (i < this.length && subj.Name != this.Subjects[i].Name)
i++;
if (i < this.length) { if (i < this.length) {
this.Subjects.concat(subj.Questions); this.Subjects.concat(subj.Questions)
} else { } else {
this.Subjects.push(subj); this.Subjects.push(subj)
} }
} }
toString() { toString () {
var r = []; var r = []
for (var i = 0; i < this.Subjects.length; i++) for (var i = 0; i < this.Subjects.length; i++) { r.push(this.Subjects[i].toString()) }
r.push(this.Subjects[i].toString()); return r.join('\n\n')
return r.join("\n\n"); }
}
} }
var utils = require('./utils.js'); var utils = require('./utils.js')
var actions = require('./actions.js'); var actions = require('./actions.js')
Main(); Main()
function Main() { function Main () {
console.clear(); console.clear()
const params = GetParams(); const params = GetParams()
console.log(params); console.log(params)
var dbs = []; var dbs = []
for (var i = 0; i < params.length; i++) {
PrintLN()
console.log(params[i] + ': ')
try {
dbs.push(ParseJSONData(utils.ReadFile(params[i])))
console.log('JSON data added')
} catch (e) {
console.log(e)
console.log('Trying with old format...')
dbs.push(ReadData(utils.ReadFile(params[i])).result)
}
}
PrintLN()
for (var i = 0; i < params.length; i++) { dbs.forEach((item) => {
PrintLN(); PrintDB(item)
console.log(params[i] + ": "); })
try {
dbs.push(ParseJSONData(utils.ReadFile(params[i])));
console.log("JSON data added");
} catch (e) {
console.log(e);
console.log("Trying with old format...");
dbs.push(ReadData(utils.ReadFile(params[i])).result);
}
}
PrintLN();
dbs.forEach((item) => { var olds = []
PrintDB(item); if (dbs.length == 1) {
}); for (let i = 0; i < dbs[0].length; i++) { olds.push(dbs[0].Subjects[i].length) }
}
var olds = []; console.log('Parsed data count: ' + dbs.length)
if (dbs.length == 1) { PrintLN()
for ( let i = 0; i < dbs[0].length; i++)
olds.push(dbs[0].Subjects[i].length);
}
console.log("Parsed data count: " + dbs.length); console.log('Merging databases...')
PrintLN(); var db = MergeDatabases(dbs)
console.log("Merging databases..."); console.log('Removing duplicates...')
var db = MergeDatabases(dbs); var r = RemoveDuplicates(db)
console.log("Removing duplicates..."); console.log('RESULT:')
var r = RemoveDuplicates(db); PrintDB(r, olds)
console.log("RESULT:"); utils.WriteFile(JSON.stringify(r), 'newData')
PrintDB(r, olds); console.log('File written!')
utils.WriteFile(JSON.stringify(r), "newData");
console.log("File written!");
} }
function PrintLN() { function PrintLN () {
console.log("------------------------------------------------------"); console.log('------------------------------------------------------')
} }
function PrintDB(r, olds) { function PrintDB (r, olds) {
console.log("Data subject count: " + r.length); console.log('Data subject count: ' + r.length)
var maxLength = 0; var maxLength = 0
for (var i = 0; i < r.length; i++) { for (var i = 0; i < r.length; i++) {
if (maxLength < r.Subjects[i].Name.length) if (maxLength < r.Subjects[i].Name.length) { maxLength = r.Subjects[i].Name.length }
maxLength = r.Subjects[i].Name.length; }
}
let qcount = 0; let qcount = 0
for (var i = 0; i < r.length; i++) { for (var i = 0; i < r.length; i++) {
let line = i; let line = i
if (line < 10) if (line < 10) { line += ' ' }
line += ' ';
line += ": "; line += ': '
var currLength = line.length + maxLength + 4; var currLength = line.length + maxLength + 4
line += r.Subjects[i].Name; line += r.Subjects[i].Name
while (line.length < currLength) { while (line.length < currLength) {
if (i % 4 == 0) if (i % 4 == 0) { line += '.' } else { line += ' ' }
line += "."; }
else
line += " ";
}
if (olds && olds.length > 0) { if (olds && olds.length > 0) {
// TODO: check if correct row! should be now, but well... // TODO: check if correct row! should be now, but well...
if (olds[i] < 10) if (olds[i] < 10) { line += ' ' }
line += " "; if (olds[i] < 100) { line += ' ' }
if (olds[i] < 100)
line += " ";
line += olds[i]; line += olds[i]
line += " -> "; line += ' -> '
} }
if (r.Subjects[i].length < 10) if (r.Subjects[i].length < 10) { line += ' ' }
line += " "; if (r.Subjects[i].length < 100) { line += ' ' }
if (r.Subjects[i].length < 100)
line += " ";
line += r.Subjects[i].length; line += r.Subjects[i].length
qcount += r.Subjects[i].length; qcount += r.Subjects[i].length
line += " db"; line += ' db'
console.log(line); console.log(line)
} }
console.log("Total questions: " + qcount); console.log('Total questions: ' + qcount)
PrintLN(); PrintLN()
} }
function GetParams() { function GetParams () {
return process.argv.splice(2); return process.argv.splice(2)
} }
function ParseJSONData(data) { function ParseJSONData (data) {
var d = JSON.parse(data); var d = JSON.parse(data)
var r = new QuestionDB(); var r = new QuestionDB()
var rt = []; var rt = []
for (var i = 0; i < d.Subjects.length; i++) { for (var i = 0; i < d.Subjects.length; i++) {
let s = new Subject(d.Subjects[i].Name); let s = new Subject(d.Subjects[i].Name)
var j = 0; var j = 0
for (j = 0; j < d.Subjects[i].Questions.length; j++) { for (j = 0; j < d.Subjects[i].Questions.length; j++) {
var currQ = d.Subjects[i].Questions[j]; var currQ = d.Subjects[i].Questions[j]
s.AddQuestion(new Question(currQ.Q, currQ.A, currQ.I)); s.AddQuestion(new Question(currQ.Q, currQ.A, currQ.I))
} }
rt.push({ rt.push({
name: d.Subjects[i].Name, name: d.Subjects[i].Name,
count: j count: j
}); })
r.AddSubject(s); r.AddSubject(s)
} }
return r; return r
} }
function MergeDatabases(dbs) { function MergeDatabases (dbs) {
var db = new QuestionDB(); var db = new QuestionDB()
for (var i = 0; i < dbs.length; i++) for (var i = 0; i < dbs.length; i++) {
for (var j = 0; j < dbs[i].length; j++) for (var j = 0; j < dbs[i].length; j++) { db.AddSubject(dbs[i].Subjects[j]) }
db.AddSubject(dbs[i].Subjects[j]); }
return db; return db
} }
/* /*
@ -303,150 +279,142 @@ function MergeDatabases(dbs) {
* Parameter should be raw read file in string with "\n"-s * Parameter should be raw read file in string with "\n"-s
* TODO: ??? -s are not listed as errors, tho works correctly * TODO: ??? -s are not listed as errors, tho works correctly
* */ * */
function ReadData(data) { function ReadData (data) {
const d = data.split('\n')
const r = new QuestionDB()
var logs = []
var currSubj = '' // the current subjects name
var ExpectedIdentifier = ['+', '?']
let currQuestion = new Question()
const d = data.split("\n"); var i = -1
const r = new QuestionDB(); while (i < d.length) {
var logs = []; let currIdentifier
var currSubj = ""; // the current subjects name let skipped = 0
var ExpectedIdentifier = ['+', '?']; do {
let currQuestion = new Question(); if (skipped >= 1) { logs.push(i + ': ' + d[i]) }
i++
if (i >= d.length) {
if (currQuestion.IsComplete()) { r.AddQuestion(currSubj, currQuestion) }
return {
result: r,
logs: logs
}
}
currIdentifier = d[i][0]
skipped++
} while (!ExpectedIdentifier.includes(currIdentifier) && i < d.length)
var i = -1; let currData = d[i].substring(1).trim()
while (i < d.length) {
let currIdentifier;
let skipped = 0;
do {
if (skipped >= 1)
logs.push(i + ": " + d[i]);
i++;
if (i >= d.length) {
if (currQuestion.IsComplete())
r.AddQuestion(currSubj, currQuestion);
return {
result: r,
logs: logs
};
}
currIdentifier = d[i][0];
skipped++;
} while (!ExpectedIdentifier.includes(currIdentifier) && i < d.length);
let currData = d[i].substring(1).trim(); if (currIdentifier == '+') {
if (currQuestion.IsComplete()) { r.AddQuestion(currSubj, currQuestion) }
currQuestion = new Question()
currSubj = currData
ExpectedIdentifier = ['?']
continue
}
if (currIdentifier == '+') { if (currIdentifier == '?') {
if (currQuestion.IsComplete()) if (currQuestion.IsComplete()) {
r.AddQuestion(currSubj, currQuestion); r.AddQuestion(currSubj, currQuestion)
currQuestion = new Question(); currQuestion = new Question()
currSubj = currData; }
ExpectedIdentifier = ['?']; // overwriting is allowed here, bcus:
continue; // ?????!>
} currQuestion.Q = currData
ExpectedIdentifier = ['!', '?']
continue
}
if (currIdentifier == '?') { if (currIdentifier == '!') {
if (currQuestion.IsComplete()) { // if dont have question continue
r.AddQuestion(currSubj, currQuestion); if (!currQuestion.HasQuestion()) { throw 'No question! (A)' }
currQuestion = new Question(); // dont allow overwriting
} // ?!!!!
// overwriting is allowed here, bcus: if (!currQuestion.HasAnswer()) {
// ?????!> currData = currData.replace('A helyes válaszok: ', '')
currQuestion.Q = currData; currData = currData.replace('A helyes válasz: ', '')
ExpectedIdentifier = ['!', '?'];
continue;
}
if (currIdentifier == '!') { currQuestion.A = currData
// if dont have question continue }
if (!currQuestion.HasQuestion()) ExpectedIdentifier = ['?', '>', '+']
throw "No question! (A)"; continue
// dont allow overwriting }
// ?!!!!
if (!currQuestion.HasAnswer()) {
currData = currData.replace("A helyes válaszok: ", "");
currData = currData.replace("A helyes válasz: ", "");
currQuestion.A = currData; if (currIdentifier == '>') {
} // if dont have question or answer continue
ExpectedIdentifier = ['?', '>', '+']; if (!currQuestion.HasQuestion()) { throw 'No question! (I)' }
continue; if (!currQuestion.HasAnswer()) { throw 'No asnwer! (I)' }
} // dont allow overwriting
// ?!>>>
if (!currQuestion.HasImage()) {
try {
currQuestion.I = JSON.parse(currData)
} catch (e) {
currQuestion.I = currData.split(',')
}
}
ExpectedIdentifier = ['?', '+']
continue
}
}
if (currIdentifier == '>') { return {
// if dont have question or answer continue result: r,
if (!currQuestion.HasQuestion()) logs: logs
throw "No question! (I)"; }
if (!currQuestion.HasAnswer())
throw "No asnwer! (I)";
// dont allow overwriting
// ?!>>>
if (!currQuestion.HasImage()) {
try {
currQuestion.I = JSON.parse(currData);
} catch (e) {
currQuestion.I = currData.split(',');
}
}
ExpectedIdentifier = ['?', '+'];
continue;
}
}
return {
result: r,
logs: logs
};
} }
function RemoveDuplicates(dataObj) { function RemoveDuplicates (dataObj) {
for (var i = 0; i < dataObj.length; i++) for (var i = 0; i < dataObj.length; i++) { RemoveDuplFromSubject(dataObj.Subjects[i]) }
RemoveDuplFromSubject(dataObj.Subjects[i]); return dataObj
return dataObj;
} }
function RemoveDuplFromSubject(subj) { function RemoveDuplFromSubject (subj) {
var cp = subj.Questions; var cp = subj.Questions
subj.Questions = []; subj.Questions = []
for (var i = 0; i < cp.length; i++) { for (var i = 0; i < cp.length; i++) {
var j = 0; var j = 0
// Only removes 100% match! // Only removes 100% match!
while (j < subj.length && cp[i].Compare(subj.Questions[j]) != 100) { while (j < subj.length && cp[i].Compare(subj.Questions[j]) != 100) {
j++; j++
} }
if (j < subj.length) { if (j < subj.length) {
//console.log("----------------------------------------------------------"); // console.log("----------------------------------------------------------");
//console.log(cp[i].toString()); // console.log(cp[i].toString());
//console.log(" VS "); // console.log(" VS ");
//console.log(subj.Questions[j].toString()); // console.log(subj.Questions[j].toString());
//console.log(cp[i].Compare(subj.Questions[j])); // console.log(cp[i].Compare(subj.Questions[j]));
//console.log(j); // console.log(j);
//console.log("removed:"); // console.log("removed:");
//console.log(subj.Questions.splice(j, 1).toString()); // console.log(subj.Questions.splice(j, 1).toString());
//console.log("----------------------------------------------------------"); // console.log("----------------------------------------------------------");
} else { } else {
subj.AddQuestion(cp[i]); subj.AddQuestion(cp[i])
} }
} }
} }
function SimplifyStringForComparison(value) { function SimplifyStringForComparison (value) {
value = RemoveUnnecesarySpaces(value).toLowerCase(); value = RemoveUnnecesarySpaces(value).toLowerCase()
var removableChars = [",", ".", ":", "!"]; var removableChars = [',', '.', ':', '!']
for (var i = 0; i < removableChars.length; i++) { for (var i = 0; i < removableChars.length; i++) {
var regex = new RegExp(removableChars[i], "g"); var regex = new RegExp(removableChars[i], 'g')
value.replace(regex, ""); value.replace(regex, '')
} }
return value; return value
} }
function RemoveUnnecesarySpaces(toremove) { function RemoveUnnecesarySpaces (toremove) {
toremove = NormalizeSpaces(toremove); toremove = NormalizeSpaces(toremove)
while (toremove.includes(" ")) // while the text includes double spaces replaces all of them with a single one while (toremove.includes(' ')) // while the text includes double spaces replaces all of them with a single one
{ {
toremove = toremove.replace(/ /g, " "); toremove = toremove.replace(/ {2}/g, ' ')
} }
return toremove.trim(); return toremove.trim()
} }
function NormalizeSpaces(input) { function NormalizeSpaces (input) {
return input.replace(/\s/g, ' '); return input.replace(/\s/g, ' ')
} }

View file

@ -1,24 +1,23 @@
const utils = require('./utils.js'); const utils = require('../utils/utils.js')
const dataFile = "public/data.json"; const dataFile = '../public/data.json'
const versionFile = "public/version"; const versionFile = '../public/version'
const motdFile = "public/motd"; const motdFile = '../public/motd'
var p = GetParams(); var p = GetParams()
if (p.length <= 0) { if (p.length <= 0) {
console.log("no params!"); console.log('no params!')
process.exit(0); process.exit(0)
} }
var param = p.join(' ')
console.log('param: ' + param)
var d = utils.ReadFile(dataFile)
var parsed = JSON.parse(d)
parsed.motd = param
utils.WriteFile(JSON.stringify(parsed), dataFile)
var param = p.join(" "); utils.WriteFile(parsed.motd, motdFile)
console.log("param: " + param);
var d = utils.ReadFile(dataFile);
var parsed = JSON.parse(d);
parsed.motd = param;
utils.WriteFile(JSON.stringify(parsed), dataFile);
utils.WriteFile(parsed.motd, motdFile); function GetParams () {
return process.argv.splice(2)
function GetParams() {
return process.argv.splice(2);
} }