-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
39 lines (35 loc) · 1.04 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
35
36
37
38
39
'use strict'
const getTokens = require('hanzi-tokenizer')
const processToken = (token, segmented) => {
if (segmented) {
return Object.values(token.definitions).map(v => v.zhuyin.replace(/\s/, ''))
} else {
return Object.values(token.definitions).map(v => v.zhuyin)
}
}
const convert = async (text, opts = {}) => {
const tokens = await getTokens(text, Object.assign(opts, { spaces: true }))
const list = []
for (let i = 0; i < tokens.length; i++) {
if (typeof tokens[i] === 'string') {
if (typeof list[list.length - 1] === 'string') {
list[list.length - 1] += tokens[i]
} else {
list.push(tokens[i])
}
} else {
if (Object.keys(tokens[i].definitions).length === 1) {
if (typeof list[list.length - 1] === 'string') {
list[list.length - 1] += processToken(tokens[i], opts.segmented)[0]
} else {
list.push(processToken(tokens[i], opts.segmented)[0])
}
} else {
list.push(processToken(tokens[i], opts.segmented))
}
}
}
return list
}
module.exports = convert
module.exports.init = getTokens.init