-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
54 lines (46 loc) · 1.34 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
'use strict'
const {Parser, Grammar} = require('nearley')
const grammar = require('./lib/grammar')
const parseVbbStationName = (name) => {
if ('string' !== typeof name) throw new TypeError('name must be a string')
// todo: optimize this
const parser = new Parser(Grammar.fromCompiled(grammar))
// parser.restore()
// parser.save()
try {
parser.feed(name.trim())
parser.finish()
} catch (err) {
err.isParseError = true
err.input = name
throw err
}
if (parser.results.length === 0) {
const err = new Error(`no parse results with "${name}"`)
err.isParseError = true
err.input = name
err.results = parser.results
throw err
}
if (parser.results.length > 1) {
const err = new Error(`grammar is ambiguous with "${name}"`)
err.isParseError = true
err.input = name
err.results = parser.results
throw err
}
const res = parser.results[0]
// remove group name from name
// (not sure if this messes some names up)
const g = res.group
const n = res.name
if (g && g.text && n && n.text && n.text.slice(0, g.text.length + 1) === g.text + ' ') {
n.text = n.text.slice(g.text.length + 1)
}
// this assumes that .value works just like .text
if (g && g.value && n && n.value && n.value.slice(0, g.value.length + 1) === g.value + ' ') {
n.value = n.value.slice(g.value.length + 1)
}
return res
}
module.exports = parseVbbStationName