eleventy-plugin-time-to-read
Version:
11ty plugin for estimating the time to read a given text. Supports multiple languages
56 lines (48 loc) • 1.24 kB
JavaScript
const regEx = require('./regular-expressions.js');
module.exports = function(customOptions) {
let options = {};
customOptions.forEach(option => {
if(isSpeed(option)) {
options.speed = option;
}
else if(isLanguage(option)) {
options.language = option;
}
else if(isHandlebarsHelper(option)) {
return;
}
else if(isJSArgument(option)) {
Object.assign(options, option);
}
else {
throw new Error(`Time-to-read encountered an unrecognised option: ${JSON.stringify(option)}`);
}
})
return options;
}
function isSpeed(option) {
return new RegExp(regEx.speed,'i').test(option);
}
function isLanguage(option) {
if(typeof option !== 'string') { return false; }
try {
Intl.getCanonicalLocales(option);
return true;
}
catch {
return false;
}
}
function isHandlebarsHelper(option) {
if(typeof option !== 'object') { return false; }
const optionKeys = Object.keys(option);
const handlebarKeys = ['lookupProperty', 'name', 'hash', 'data', 'loc'];
return handlebarKeys.every(key => {
return optionKeys.includes(key);
})
}
function isJSArgument(option) {
if(typeof option === 'object' && !Array.isArray(option)) {
return true;
}
}