Refactor code

This commit is contained in:
Oystein Kristoffer Tveit 2020-06-09 15:19:20 +02:00
parent 1616c30131
commit c0b32b4175
5 changed files with 106 additions and 68 deletions

View File

@ -3,7 +3,7 @@ const fs = require('fs');
/* Import local files */ /* Import local files */
const {fetchKanjiFromTxt, fetchJishoBufferData, fetchKanjiFromJisho} = require('./src/dataFetching.js'); const {fetchKanjiFromTxt, fetchJishoBufferData, fetchKanjiFromJisho} = require('./src/dataFetching.js');
const {getKanjiTexData} = require('./src/texConversion.js'); const {getKanjiTexData} = require('./src/texConversion.js');
const {kanjiTable} = require('./src/kanjiTables.js'); const {chapterTabular} = require('./src/kanjiTables.js');
function log(message, jlptLevel) { function log(message, jlptLevel) {
const jlptLevelCaps = jlptLevel.toUpperCase(); const jlptLevelCaps = jlptLevel.toUpperCase();
@ -20,7 +20,7 @@ async function main(jlptLevel) {
const texData = getKanjiTexData(jishoResults); const texData = getKanjiTexData(jishoResults);
log('Generating chapter table page', jlptLevel); log('Generating chapter table page', jlptLevel);
const resultTable = kanjiTable(kanjiArray); const chapterTable = chapterTabular(kanjiArray, 16);
let resultPage = ''; let resultPage = '';
for (kanji of texData) { for (kanji of texData) {
@ -32,7 +32,7 @@ async function main(jlptLevel) {
\\newpage\n`; \\newpage\n`;
} }
fs.writeFile(`./data/tables/${jlptLevel}.tex`, resultTable, (err) => {if (err) console.error(err)}); fs.writeFile(`./data/tables/${jlptLevel}.tex`, chapterTable, (err) => {if (err) console.error(err)});
fs.writeFile(`./data/pages/${jlptLevel}.tex`, resultPage, (err) => {if (err) console.error(err)}); fs.writeFile(`./data/pages/${jlptLevel}.tex`, resultPage, (err) => {if (err) console.error(err)});
} }

View File

@ -1,37 +1,57 @@
/**
* Turns an array of kanji into a tabular for a chapter overview
* @param {string[]} kanjiArray A list of kanji to put into the table
* @returns {string} A tex tabular.
*/
function kanjiTable(kanjiArray) {
const xLength = 16;
const yLength = Math.ceil(kanjiArray.length/xLength);
const sideLength = Math.ceil(Math.sqrt(kanjiArray.length));
let tableString = '';
function makeNumberRow(xLength) {
let numberRow = [...Array(xLength).keys()]; let numberRow = [...Array(xLength).keys()];
numberRow = numberRow.map((number) => (number + 1).toString()); numberRow = numberRow.map((number) => (number + 1).toString());
numberRow = numberRow.map((number) => `{\\large ${number}}`); numberRow = numberRow.map((number) => `{\\large ${number}}`);
numberRow = [' ', ...numberRow]; numberRow = [' ', ...numberRow];
tableString += `${numberRow.join(' & ')} \\\\\n\\hline\n\\endhead\n`; return `${numberRow.join(' & ')} \\\\\n\\hline\n\\endhead\n`;
for (let y_index = 0; y_index < yLength; y_index++) {
const lineArray = new Array;
lineArray.push(`{\\large ${y_index*xLength}}`);
for (let x_index = 0; x_index < xLength; x_index++) {
const indexNumber = y_index * xLength + x_index;
lineArray.push(kanjiArray[indexNumber] ? kanjiArray[indexNumber] : '');
}
tableString += `${lineArray.join(' & ')} \\\\\n`;
}
return `\\begin{kanjiTable}{ ${'l | ' + 'l '.repeat(xLength)}}
${tableString}\\end{kanjiTable}`
} }
exports.kanjiTable = kanjiTable; function kanjiRow(index, kanjiArray) {
let result = [];
for (let rowIndex = 0; rowIndex < rowLength; rowIndex++) {
const currentIndex = index + rowIndex;
result.push(kanjiArray[currentIndex] ? kanjiArray[currentIndex] : '');
}
return result;
}
function makeRows(rowLength, columnLength, kanjiArray) {
let result = '';
for (let columnIndex = 0; columnIndex < columnLength; columnIndex++) {
const line = new Array;
const index = columnIndex * rowLength;
// Add the number of current character
line.push(`{\\large ${index}}`);
// Concatenate the number with the rest of the row
line = [line, kanjiRow(index, kanjiArray)];
// Convert the line array into a tex row and add it to result.
result += `${line.join(' & ')} \\\\\n`;
}
return result;
}
/**
* Turns an array of kanji into a tabular for a chapter overview
* @param {string[]} kanjiArray An array of kanji characters to put into the tabular
* @returns {string} A tex tabular
*/
function chapterTabular(kanjiArray, rowLength) {
const columnLength = Math.ceil(kanjiArray.length/rowLength);
let tabularString = '';
tabularString += makeNumberRow(rowLength);
tabularString += makeRows(rowLength, columnLength, kanjiArray);
return `\\begin{chapterTabular}{ ${'l | ' + 'l '.repeat(rowLength)}}
${tabularString}\\end{chapterTabular}`
}
exports.chapterTabular = chapterTabular;

View File

@ -1,24 +1,27 @@
const textFiltration = require('./textFiltration.js') const textFiltration = require('./textFiltration.js')
/* Process result array into object with LaTeX strings */ const makeFirstLetterUppercase = (string) => string.charAt(0).toUpperCase() + string.slice(1);
function getKanjiTexData(kanjiArray) {
return kanjiArray.map(kanji => {
const meaning = textFiltration.convertMeaning(kanji); /**
const kunyomi = textFiltration.convertKunyomi(kanji); * Generate TeX strings from Jisho data
const onyomi = textFiltration.convertOnyomi(kanji); * @param {object[]} jishoResults Array of results fetched from Jisho
* @returns {object} An object containg TeX strings
*/
function getKanjiTexData(jishoResults) {
return jishoResults.map(jishoResult => {
kanji.taughtIn = kanji.taughtIn ? const meaning = textFiltration.convertMeaning(jishoResult);
kanji.taughtIn.charAt(0).toUpperCase() + kanji.taughtIn.slice(1) const kunyomi = textFiltration.convertKunyomi(jishoResult);
: ''; const onyomi = textFiltration.convertOnyomi(jishoResult);
jishoResult.taughtIn = jishoResult.taughtIn ? makeFirstLetterUppercase(jishoResult.taughtIn) : '';
return { return {
kanji: kanji.query, kanjiPageHeader: `\\kanjiPageHeader{${jishoResult.query}}{${jishoResult.taughtIn}}{${jishoResult.jlptLevel}}{${jishoResult.strokeCount}}{${jishoResult.radical.symbol}}`,
kanjiPageHeader: `\\kanjiPageHeader{${kanji.query}}{${kanji.taughtIn}}{${kanji.jlptLevel}}{${kanji.strokeCount}}{${kanji.radical.symbol}}`,
kanjiMeaning: meaning ? `\\kanjiMeaning{${meaning}}` : '', kanjiMeaning: meaning ? `\\kanjiMeaning{${meaning}}` : '',
kunyomi: kunyomi ? `\\kunyomi{${kunyomi}}` : '', kunyomi: kunyomi ? `\\kunyomi{${kunyomi}}` : '',
onyomi: onyomi ? `\\onyomi{${onyomi}}` : '', onyomi: onyomi ? `\\onyomi{${onyomi}}` : '',
kanjiRow: `\\kanjiRow{${kanji.query}}` kanjiRow: `\\kanjiRow{${jishoResult.query}}`
} }
}); });

View File

@ -1,12 +1,36 @@
const yomiBrackets = ['\\textbf{\\textcolor{kanjiColor!80!black}{', '}}']; const stylingBrackets = {
"start": '\\textbf{\\textcolor{kanjiColor!80!black}{',
"end": '}}'
};
const yomiConnector = '、 '; const yomiConnector = '、 ';
const yomiDash = '—'; const yomiDash = '—';
function convertKunyomi(res) { const styleText = (string) => stylingBrackets.start + string + stylingBrackets.end;
if (res.kunyomi.length === 0) return ''; function styleCharactersBeforeDot(string) {
const words = string.split('.');
words[0] = styleText(words[0]);
return words.join('');
}
const kunyomi = JSON.stringify(res.kunyomi) function styleEverythingExceptDash(string) {
const words = string.split(/(?<=\-)/);
if (words[0] === '-') { // ['-', 'word']
words[0] = yomiDash;
words[1] = styleText(words[1]);
} else { // ['Word-', '']
words[1] = yomiDash;
words[0] = words[0].slice(0, words[0].length-1);
words[0] = styleText(words[0]);
}
return words.join('');
}
function convertKunyomi(jishoResult) {
if (jishoResult.kunyomi.length === 0) return '';
const kunyomi = JSON.stringify(jishoResult.kunyomi)
.replace(/"|\[|\]/g, '') .replace(/"|\[|\]/g, '')
.replace(/\\/g, '\\\\') .replace(/\\/g, '\\\\')
.replace(/%/g, '\\%') .replace(/%/g, '\\%')
@ -20,41 +44,32 @@ function convertKunyomi(res) {
//TODO: Apply combinated logic here //TODO: Apply combinated logic here
} }
else if (instance.includes('.')) { else if (instance.includes('.')) {
const words = instance.split('.'); kunyomi[i] = styleCharactersBeforeDot(instance);
words[0] = yomiBrackets[0] + words[0] + yomiBrackets[1];
kunyomi[i] = words.join('');
} }
else if (instance.includes('-')) { else if (instance.includes('-')) {
const words = instance.split(/(?<=\-)/); kunyomi[i] = styleEverythingExceptDash(instance);
if (words[0] == '-') { // ['-', 'word']
words[0] = yomiDash;
words[1] = yomiBrackets[0] + words[1] + yomiBrackets[1];
} else { // ['Word-', '']
words[1] = yomiDash;
words[0] = words[0].slice(0, words[0].length-1);
words[0] = yomiBrackets[0] + words[0] + yomiBrackets[1];
}
kunyomi[i] = words.join('');
} }
else { else {
kunyomi[i] = yomiBrackets[0] + instance + yomiBrackets[1]; kunyomi[i] = styleText(instance);
} }
} }
return kunyomi.join(yomiConnector); return kunyomi.join(yomiConnector);
} }
function convertOnyomi(res) { function convertOnyomi(jishoResult) {
return JSON.stringify(res.onyomi) return JSON.stringify(jishoResult.onyomi)
.replace(/"|\[|\]/g, '') .replace(/"|\[|\]/g, '')
.replace(/\\/g, '\\\\') .replace(/\\/g, '\\\\')
.replace(/%/g, '\\%') .replace(/%/g, '\\%')
.replace(/,/g, yomiConnector) .replace(/,/g, yomiConnector)
.replace(/&/g, '\\&'); .replace(/&/g, '\\&');
//TODO: Style only the words, and not the yomiConnector inbetween
} }
function convertMeaning(res) { function convertMeaning(jishoResult) {
return res.meaning return jishoResult.meaning
.replace(/\\/g, '\\\\') .replace(/\\/g, '\\\\')
.replace(/%/g, '\\%') .replace(/%/g, '\\%')
.replace(/&/g, '\\&'); .replace(/&/g, '\\&');

View File

@ -35,7 +35,7 @@
% Kanji Table % % Kanji Table %
% ---------------------------------------------------------------------------- % % ---------------------------------------------------------------------------- %
\newenvironment{kanjiTable}[1] \newenvironment{chapterTabular}[1]
{ {
\begin{longtable}{#1} \begin{longtable}{#1}
} }