Skip to content

Commit 629ae99

Browse files
committed
Fix exception on empty document
1 parent 0648147 commit 629ae99

File tree

3 files changed

+19
-7
lines changed

3 files changed

+19
-7
lines changed

index.js

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -62,18 +62,24 @@ export function readingTime(tree, options = {}) {
6262
Math.max(firstGradeAge, Math.round(options.age || 16))
6363
)
6464
const text = toText(tree)
65-
const scores = readabilityScores(text)
66-
/** @type {number} */
67-
const readabilityAge =
68-
firstGradeAge +
69-
median([
65+
const scores = readabilityScores(text) || {}
66+
const score = median(
67+
[
7068
scores.daleChall,
7169
scores.ari,
7270
scores.colemanLiau,
7371
scores.fleschKincaid,
7472
scores.smog,
7573
scores.gunningFog
76-
])
74+
].filter((d) => d !== undefined)
75+
)
76+
77+
if (score === null) {
78+
return 0
79+
}
80+
81+
/** @type {number} */
82+
const readabilityAge = firstGradeAge + score
7783

7884
// WPM the target audience normally reads.
7985
const targetWpm = baseWpm + (targetAge - firstGradeAge) * addedWpmPerGrade

readme.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ npm install hast-util-reading-time
2525
## Use
2626

2727
Say we have the following HTML from [“Word per minute: Alphanumeric entry” on
28-
Wikipedia](https://en.wikipedia.org/wiki/Words_per_minute#Alphanumeric_entry) in
28+
Wikipedia](https://en.wikipedia.org/wiki/Words\_per\_minute#Alphanumeric\_entry) in
2929
`example.html`:
3030

3131
```html

test.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@ test('hastUtilReadingTime', (t) => {
4141
'should estimate (somewhat simple)'
4242
)
4343

44+
t.deepEqual(
45+
readingTime({type: 'root', children: []}),
46+
0,
47+
'should estimate (empty)'
48+
)
49+
4450
t.deepEqual(
4551
readingTime(tree, {age: 12}),
4652
2.437_14,

0 commit comments

Comments
 (0)