-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.js
More file actions
70 lines (57 loc) · 1.45 KB
/
index.js
File metadata and controls
70 lines (57 loc) · 1.45 KB
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
const itemsById = require('./data/itemsById.json')
const itemsByName = require('./data/itemsByName.json')
const format = {
num: /^\d+$/,
incompleteId: /^\d+:$/,
id: /^\d+:\d+$/
}
const isNumeric = key => typeof key === 'number' || format.num.test(key)
const isIncompleteId = key => format.incompleteId.test(key)
const isId = key => format.id.test(key)
const get = (key) => {
if (isNumeric(key)) {
key = `${key}:0`
return itemsById[key]
}
if (isId(key)) {
return itemsById[key]
}
return itemsByName[key.toLowerCase()]
}
const getAll = ({ by = 'id' } = {}) => {
if (by === 'name') {
return itemsByName
}
return itemsById
}
const filterAndMapKeysById = (key, keyFormat) => {
const keys = Object.keys(itemsById).filter(k => keyFormat.test(k))
return keys.map(key => itemsById[key])
}
const findByNumber = (key) => {
const keyFormat = new RegExp(`^${key}:`)
return filterAndMapKeysById(key, keyFormat)
}
const findById = (key) => {
const keyFormat = new RegExp(`^${key}`)
return filterAndMapKeysById(key, keyFormat)
}
const findByName = (key) => {
const keyFormat = new RegExp(`${key}`)
const keys = Object.keys(itemsByName).filter(k => keyFormat.test(k))
return keys.map(key => itemsByName[key])
}
const find = (key) => {
if (isNumeric(key)) {
return findByNumber(key)
}
if (isIncompleteId(key) || isId(key)) {
return findById(key)
}
return findByName(key)
}
module.exports = {
get,
getAll,
find
}