Update index.js
Browse files
index.js
CHANGED
|
@@ -1,10 +1,35 @@
|
|
| 1 |
import dictionaryJs from 'https://cdn.jsdelivr.net/npm/dictionary-js@0.1.0/+esm'
|
| 2 |
import randomParagraph from 'https://cdn.jsdelivr.net/npm/random-paragraph@1.0.4/+esm'
|
| 3 |
import tokenGenerator from 'https://cdn.jsdelivr.net/npm/generate-token@1.0.1/+esm'
|
| 4 |
-
export function generate() {
|
| 5 |
-
let token = tokenGenerator.generate(20); // generate token string of length ~20 chars
|
| 6 |
-
let maxSentences = token.length; // now we can get length safely
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import dictionaryJs from 'https://cdn.jsdelivr.net/npm/dictionary-js@0.1.0/+esm'
|
| 2 |
import randomParagraph from 'https://cdn.jsdelivr.net/npm/random-paragraph@1.0.4/+esm'
|
| 3 |
import tokenGenerator from 'https://cdn.jsdelivr.net/npm/generate-token@1.0.1/+esm'
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
export async function generate(userInput) {
|
| 6 |
+
// Step 1: Generate a token to decide paragraph complexity
|
| 7 |
+
let token = tokenGenerator.generate(20);
|
| 8 |
+
let maxSentences = token.length;
|
| 9 |
+
|
| 10 |
+
// Step 2: Break user input into words
|
| 11 |
+
let words = userInput.split(/\s+/).map(w => w.toLowerCase().replace(/[^a-z]/gi, ''));
|
| 12 |
+
|
| 13 |
+
// Step 3: Lookup definitions for each word (filtering blanks or duplicates)
|
| 14 |
+
let definitions = [];
|
| 15 |
+
let seenWords = new Set();
|
| 16 |
+
|
| 17 |
+
for (let word of words) {
|
| 18 |
+
if (!seenWords.has(word) && word.length > 1) {
|
| 19 |
+
seenWords.add(word);
|
| 20 |
+
try {
|
| 21 |
+
let result = await dictionaryJs.search(word);
|
| 22 |
+
if (result && result.length > 0) {
|
| 23 |
+
definitions.push(`${word}: ${result[0].definition}`);
|
| 24 |
+
}
|
| 25 |
+
} catch (err) {
|
| 26 |
+
console.warn(`No definition found for: ${word}`);
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
// Step 4: Generate a random paragraph using maxSentences
|
| 32 |
+
let paragraph = randomParagraph({ min: 4, max: maxSentences });
|
| 33 |
+
|
| 34 |
+
console.log(paragraph);
|
| 35 |
+
}
|