-
-
Notifications
You must be signed in to change notification settings - Fork 84
/
index.js
71 lines (54 loc) · 1.56 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
'use strict';
const uniqueRandomArray = require('unique-random-array');
const pokemon = require('./data/en.json');
const repositoryUrl = 'https://github.com/sindresorhus/pokemon';
const reportText = `Please report to ${repositoryUrl}/issues if we missed something.`;
const languages = new Set([
'de',
'en',
'fr',
'es',
'ja',
'ko',
'ru',
'th',
'zh-Hans',
'zh-Hant',
]);
const randomNameGenerators = new Map();
function getLocalizedList(language = 'en') {
if (language === 'en') {
return pokemon;
}
if (!languages.has(language)) {
throw new Error(`Localized list for language code '${language}' does not exist. Pull request welcome: ${repositoryUrl}`);
}
return require(`./data/${language.toLowerCase()}.json`);
}
exports.all = getLocalizedList;
exports.random = (language = 'en') => {
if (randomNameGenerators.has(language)) {
return randomNameGenerators.get(language)();
}
const list = getLocalizedList(language);
const random = uniqueRandomArray(list);
randomNameGenerators.set(language, random);
return random();
};
exports.getName = (id, language = 'en') => {
const list = getLocalizedList(language);
const name = list[id - 1];
if (!name) {
throw new Error(`Pokémon with ID '${id}' does not exist. ${reportText}`);
}
return name;
};
exports.getId = (name, language = 'en') => {
const list = getLocalizedList(language);
const index = list.indexOf(name);
if (index === -1) {
throw new Error(`Pokémon with name '${name}' does not exist for language code '${language}'. ${reportText}`);
}
return index + 1;
};
exports.languages = languages;