-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhitokoto.js
More file actions
47 lines (40 loc) · 1.96 KB
/
Copy pathhitokoto.js
File metadata and controls
47 lines (40 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* This module provides a function to retrieve a random sentence (hitokoto)
* from a collection of poetry objects.
*/
// Project: gaokao-poetry https://github.com/clover-yan/gaokao-poetry
// Author: Clover Yan https://www.khyan.top
// gaokao-poetry © 2025 by Clover Yan is licensed under CC BY-SA 4.0. To view a copy of this license, visit https://creativecommons.org/licenses/by-sa/4.0/
/**
* Retrieves a random sentence (hitokoto) from a collection of poetry objects.
*
* @async
* @function getHitokoto
* @param {Array<Object>} poetryObjects - An array of poetry objects, where each object contains a title, author, and an array of sentences.
* @returns {Promise<Object>} A promise that resolves to an object containing:
* - `from` {string}: The title of the poetry article.
* - `from_who` {string}: The author of the poetry article.
* - `hitokoto` {string}: A randomly selected sentence from the poetry article.
* @throws {Error} Throws an error if:
* - The input is not a valid array of poetry objects.
* - The poetry objects or their properties are invalid or missing.
* - The sentences array is empty or contains invalid data.
*/
export async function getHitokoto(poetryObjects) {
if (!Array.isArray(poetryObjects) || poetryObjects.length === 0) {
throw new Error('Invalid or empty sentences.json file');
}
const randomArticle = poetryObjects[Math.floor(Math.random() * poetryObjects.length)];
if (!typeof randomArticle === 'object' || randomArticle === null) {
throw new Error('Invalid sentences.json file');
}
const sentences = randomArticle.content;
if (!Array.isArray(sentences) || sentences.length === 0) {
throw new Error('Invalid sentences.json file');
}
const randomSentence = sentences[Math.floor(Math.random() * sentences.length)];
if (typeof randomSentence !== 'string') {
throw new Error('Invalid sentences.json file');
}
return { 'from': randomArticle.title, 'from_who': randomArticle.author, 'hitokoto': randomSentence };
}