-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
34 lines (26 loc) · 1.12 KB
/
index.js
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
import { dictionary } from 'cmu-pronouncing-dictionary';
import extractWords from 'extractwords';
export default function syllables(input, { fallbackSyllablesFunction = null } = {}) {
if (typeof input !== 'string') {
throw new TypeError(`Expected a string, got ${typeof input}`);
}
if (typeof fallbackSyllablesFunction !== 'function') {
fallbackSyllablesFunction = null;
}
const words = extractWords(input, { lowercase: true });
let syllables = 0;
for (let word of words) {
const pronounciation = dictionary[word] ?? '';
if (pronounciation) {
const stresses = pronounciation.match(/[0-2]/g) ?? [];
syllables += stresses.length;
} else if (fallbackSyllablesFunction) {
const fallbackSyllablesCount = fallbackSyllablesFunction(word);
const fallbackSyllablesReturnValid = typeof fallbackSyllablesCount === 'number' && fallbackSyllablesCount && fallbackSyllablesCount > 0;
if (fallbackSyllablesReturnValid) {
syllables += fallbackSyllablesCount;
}
}
}
return syllables;
}