-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (40 loc) · 1.13 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
const path = require('path');
const esql = require('sql-extra');
const REPLACE = /((\w\s+|\w\.\s*|\w\-\s*|\w$)+)|\w+/g;
var corpus = null;
var match = null;
function createRegex(lst) {
var a = '(^|\\W+)(';
for (var v of lst)
a += v.length>1? `${v}|`:`${v}\\.|`;
a = a.substring(0, a.length-1);
a += `)(\\W+|$)`;
return new RegExp(a, 'i');
}
function load() {
if (corpus) return corpus;
corpus = require('./corpus');
match = createRegex(corpus.keys());
return corpus;
}
function csv() {
return path.join(__dirname, 'index.csv');
}
function sql(tab='languages', opt={}) {
return esql.setupTable(tab, {abbr: 'TEXT', lang: 'TEXT'}, load().values(),
Object.assign({pk: 'abbr', index: true, tsvector: {abbr: 'A', lang: 'B'}}, opt));
}
function languages(txt) {
if (!corpus) load();
var txt = txt.replace(REPLACE, m => {
var v = m.replace(/\W/g, '');
return v.length===1? m.trim()+' ' : v+' ';
}).toLowerCase();
var m = txt.match(match);
if (m==null) return null;
return corpus.get(m[2].replace('.', ''));
}
languages.load = load;
languages.csv = csv;
languages.sql = sql;
module.exports = languages;