refactor(parser): helper to get paragraph content (#56326)

This commit is contained in:
Oliver Eyton-Williams
2024-10-04 16:42:41 +02:00
committed by GitHub
parent ea44135808
commit 321915cbe9
3 changed files with 31 additions and 7 deletions
@@ -3,6 +3,7 @@ const find = require('unist-util-find');
const { getSection } = require('./utils/get-section');
const getAllBefore = require('./utils/before-heading');
const mdastToHtml = require('./utils/mdast-to-html');
const { getParagraphContent } = require('./utils/get-paragraph-content');
const { splitOnThematicBreak } = require('./utils/split-on-thematic-break');
@@ -80,13 +81,7 @@ function getAnswers(answersNodes) {
function getSolution(solutionNodes) {
let solution;
try {
if (solutionNodes.length > 1) throw Error('Too many nodes');
if (solutionNodes[0].children.length > 1)
throw Error('Too many child nodes');
const solutionString = solutionNodes[0].children[0].value;
if (solutionString === '') throw Error('Non-empty string required');
solution = Number(solutionString);
solution = Number(getParagraphContent(solutionNodes[0]));
if (Number.isNaN(solution)) throw Error('Not a number');
if (solution < 1) throw Error('Not positive number');
} catch (e) {
@@ -0,0 +1,7 @@
const mdastToHtml = require('./mdast-to-html');
function getParagraphContent(node) {
return node.type === 'paragraph' ? mdastToHtml(node.children) : null;
}
module.exports.getParagraphContent = getParagraphContent;
@@ -0,0 +1,22 @@
const parseFixture = require('../../__fixtures__/parse-fixture');
const { getParagraphContent } = require('./get-paragraph-content');
describe('getParagraphContent', () => {
let simpleAST;
beforeAll(async () => {
simpleAST = await parseFixture('simple.md');
});
it('should return the content of a paragraph node', () => {
const paragraphNode = simpleAST.children[1];
expect(paragraphNode.type).toBe('paragraph');
expect(getParagraphContent(paragraphNode)).toEqual('Paragraph 1');
});
it('should return null if the node is not a paragraph', () => {
const headingNode = simpleAST.children[0];
expect(headingNode.type).toBe('heading');
expect(getParagraphContent(headingNode)).toBeNull();
});
});