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 */
const {fetchKanjiFromTxt, fetchJishoBufferData, fetchKanjiFromJisho} = require('./src/dataFetching.js');
const {getKanjiTexData} = require('./src/texConversion.js');
const {kanjiTable} = require('./src/kanjiTables.js');
const {chapterTabular} = require('./src/kanjiTables.js');
function log(message, jlptLevel) {
const jlptLevelCaps = jlptLevel.toUpperCase();
@ -20,7 +20,7 @@ async function main(jlptLevel) {
const texData = getKanjiTexData(jishoResults);
log('Generating chapter table page', jlptLevel);
const resultTable = kanjiTable(kanjiArray);
const chapterTable = chapterTabular(kanjiArray, 16);
let resultPage = '';
for (kanji of texData) {
@ -32,7 +32,7 @@ async function main(jlptLevel) {
\\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)});
}

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()];
numberRow = numberRow.map((number) => (number + 1).toString());
numberRow = numberRow.map((number) => `{\\large ${number}}`);
numberRow = [' ', ...numberRow];
tableString += `${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] : '');
return `${numberRow.join(' & ')} \\\\\n\\hline\n\\endhead\n`;
}
tableString += `${lineArray.join(' & ')} \\\\\n`;
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;
}
return `\\begin{kanjiTable}{ ${'l | ' + 'l '.repeat(xLength)}}
${tableString}\\end{kanjiTable}`
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`;
}
exports.kanjiTable = kanjiTable;
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')
/* Process result array into object with LaTeX strings */
function getKanjiTexData(kanjiArray) {
return kanjiArray.map(kanji => {
const makeFirstLetterUppercase = (string) => string.charAt(0).toUpperCase() + string.slice(1);
const meaning = textFiltration.convertMeaning(kanji);
const kunyomi = textFiltration.convertKunyomi(kanji);
const onyomi = textFiltration.convertOnyomi(kanji);
/**
* Generate TeX strings from Jisho data
* @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 ?
kanji.taughtIn.charAt(0).toUpperCase() + kanji.taughtIn.slice(1)
: '';
const meaning = textFiltration.convertMeaning(jishoResult);
const kunyomi = textFiltration.convertKunyomi(jishoResult);
const onyomi = textFiltration.convertOnyomi(jishoResult);
jishoResult.taughtIn = jishoResult.taughtIn ? makeFirstLetterUppercase(jishoResult.taughtIn) : '';
return {
kanji: kanji.query,
kanjiPageHeader: `\\kanjiPageHeader{${kanji.query}}{${kanji.taughtIn}}{${kanji.jlptLevel}}{${kanji.strokeCount}}{${kanji.radical.symbol}}`,
kanjiPageHeader: `\\kanjiPageHeader{${jishoResult.query}}{${jishoResult.taughtIn}}{${jishoResult.jlptLevel}}{${jishoResult.strokeCount}}{${jishoResult.radical.symbol}}`,
kanjiMeaning: meaning ? `\\kanjiMeaning{${meaning}}` : '',
kunyomi: kunyomi ? `\\kunyomi{${kunyomi}}` : '',
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 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, '\\%')
@ -20,41 +44,32 @@ function convertKunyomi(res) {
//TODO: Apply combinated logic here
}
else if (instance.includes('.')) {
const words = instance.split('.');
words[0] = yomiBrackets[0] + words[0] + yomiBrackets[1];
kunyomi[i] = words.join('');
kunyomi[i] = styleCharactersBeforeDot(instance);
}
else if (instance.includes('-')) {
const words = instance.split(/(?<=\-)/);
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('');
kunyomi[i] = styleEverythingExceptDash(instance);
}
else {
kunyomi[i] = yomiBrackets[0] + instance + yomiBrackets[1];
kunyomi[i] = styleText(instance);
}
}
return kunyomi.join(yomiConnector);
}
function convertOnyomi(res) {
return JSON.stringify(res.onyomi)
function convertOnyomi(jishoResult) {
return JSON.stringify(jishoResult.onyomi)
.replace(/"|\[|\]/g, '')
.replace(/\\/g, '\\\\')
.replace(/%/g, '\\%')
.replace(/,/g, yomiConnector)
.replace(/&/g, '\\&');
//TODO: Style only the words, and not the yomiConnector inbetween
}
function convertMeaning(res) {
return res.meaning
function convertMeaning(jishoResult) {
return jishoResult.meaning
.replace(/\\/g, '\\\\')
.replace(/%/g, '\\%')
.replace(/&/g, '\\&');

View File

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