-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.js
97 lines (86 loc) · 2.31 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const FS = require("fs");
const PATH = require("path");
const cache = {
parsedDict: null,
words: {}
};
const getParsedDictionary = () => {
if (!cache.parsedDict) {
let parsedDict = [];
try {
const rawDict = FS.readFileSync(`${__dirname}/dictionary.json`);
parsedDict = JSON.parse(rawDict);
} catch (e) {
console.error("Error while parsing dictionary");
console.error(e);
}
cache.parsedDict = parsedDict;
}
return cache.parsedDict;
};
const getWordsFromWordFile = path => {
if (!cache.words[path]) {
let words = [];
try {
const rawFile = FS.readFileSync(PATH.join(__dirname, path));
const parsedFile = JSON.parse(rawFile);
words = parsedFile.words;
} catch (e) {
console.error("Error while parsing word file");
console.error(e);
}
cache.words[path] = words;
}
return cache.words[path];
};
const getAllLanguageCodes = () => {
const dict = getParsedDictionary();
return dict.map(lang => lang.code);
};
const getAllLanguageNames = () => {
const dict = getParsedDictionary();
return dict.map(lang => lang.name);
};
const getAllLanguageNativeNames = () => {
const dict = getParsedDictionary();
return dict.map(lang => lang.nativeName);
};
const getWordsByLanguageCode = code => {
const dict = getParsedDictionary();
const langFilePath = dict
.filter(lang => lang.code === code)
.map(lang => lang.wordFilePath);
if (langFilePath.length > 0) {
return getWordsFromWordFile(langFilePath[0]);
}
return [];
};
const getWordsByLanguageName = name => {
const dict = getParsedDictionary();
const langFilePath = dict
.filter(lang => lang.name === name)
.map(lang => lang.wordFilePath);
if (langFilePath.length > 0) {
return getWordsFromWordFile(langFilePath[0]);
}
return [];
};
const getWordsByLanguageNativeName = nativeName => {
const dict = getParsedDictionary();
const langFilePath = dict
.filter(lang => lang.nativeName === nativeName)
.map(lang => lang.wordFilePath);
if (langFilePath.length > 0) {
return getWordsFromWordFile(langFilePath[0]);
}
return [];
};
module.exports = {
getAllLanguageCodes,
getAllLanguageNames,
getAllLanguageNativeNames,
getWordsByLanguageCode,
getWordsByLanguageName,
getWordsByLanguageNativeName
};
console.log(getAllLanguageCodes());