-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
66 lines (54 loc) · 2.1 KB
/
index.js
File metadata and controls
66 lines (54 loc) · 2.1 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const readingTime = require('reading-time');
const defaultOptions = {
output: function (stats) {
return `${stats.words} words, ${stats.text}`;
},
wordsPerMinute: 200,
wordBound: null,
};
const measureTime = (content, options) => {
const html = content.templateContent || content;
if (typeof html !== 'string') {
throw new Error('Word-Stats input must be a string.');
}
let readingTimeOptions = {};
if (options.wordsPerMinute) {
readingTimeOptions.wordsPerMinute = options.wordsPerMinute;
}
if (options.wordBound) {
readingTimeOptions.wordBound = options.wordBound;
}
return options.output(readingTime(html, readingTimeOptions));
};
const validateOptions = (options) => {
let validated = {};
for (let [key, value] of Object.entries(options)) {
key = key.toLowerCase();
if (key === 'output' && typeof value !== 'function') {
throw new Error(`Word-Stats output option must be a function. Received ${typeof value}: ${JSON.stringify(options)}`);
}
if (key === 'wordsperminute') {
if (typeof value !== 'number') {
throw new Error(`Word-Stats wordsPerMinute option must be a number. Received ${typeof value}: ${JSON.stringify(options)}`);
}
if (value <= 0) {
throw new Error(`Word-Stats wordsPerMinute option must be greater than zero. Received ${value}: ${JSON.stringify(options)}`);
}
}
if (key === 'wordbound' && typeof value !== 'function') {
throw new Error(`Word-Stats wordBound option must be a function. Received ${typeof value}: ${JSON.stringify(options)}`);
}
validated[key] = value;
}
return validated;
};
module.exports = function (eleventyConfig, customOptions = {}) {
const globalOptions = Object.assign({}, defaultOptions, validateOptions(customOptions));
eleventyConfig.addFilter(
'wordStats',
(input, ...instanceOptions) => measureTime(
input,
Object.assign({}, globalOptions, instanceOptions)
)
);
};