conjugator.js (1717B)
1 import { Conjugator } from "../vendor/korean_conjugation/conjugator.js"; 2 import "./types.js"; 3 4 /** @type {Conjugator} */ 5 const conjugator = new Conjugator(); 6 7 /** 8 * @param {string} word 9 * @returns {boolean} 10 */ 11 export function isValidVerb(word) { 12 if (word.endsWith("하다")) return true; 13 if (word.endsWith("다니다")) return true; 14 if (word.endsWith("니다")) return false; 15 if (word.endsWith("이다")) return true; 16 if (word.endsWith("다")) return true; 17 18 return false; 19 } 20 21 /** 22 * @param {number} count 23 * @param {Tense[]} tenses 24 * @param {DB[]} dbs 25 * @returns {Conjugation[]} conjugations 26 */ 27 export function getRandomConjugations(count, tenses, dbs) { 28 /** @type {WordConjugation[]} */ 29 const conjugations = []; 30 31 /** @type {Word[]} */ 32 const wordPool = dbs.map(db => db.words).flat(); 33 /** @type {DB} */ 34 const db = { words: wordPool } 35 36 if (db.words.length === 0) throw new Error("Empty DB"); 37 if (tenses.length === 0) throw new Error("No tense(s) selected"); 38 39 for (let i = 0; i < count; i++) { 40 conjugations.push(getRandomConjugation(db, tenses)); 41 } 42 43 return conjugations; 44 } 45 46 /** 47 * @param {DB} db 48 * @param {Tense[]} filters 49 * @returns {WordConjugation} conjugation 50 */ 51 function getRandomConjugation(db, filters) { 52 const word = db.words[Math.floor(Math.random() * db.words.length)]; 53 54 /** @type {Conjugation[]} */ 55 const conjugations = conjugator.perform(word.text); 56 57 /** @type {Conjugation[]} */ 58 const filtered = conjugations.filter(conjugation => filters.includes(conjugation.tense)); 59 if (filtered.length === 0) throw new Error(`No conjugations found for "${word.text}" with selected tenses`); 60 61 return { 62 conjugation: filtered[Math.floor(Math.random() * filtered.length)], 63 word, 64 }; 65 }