forked from earthchie/jquery.Thailand.js
/
finder.js
62 lines (57 loc) · 1.48 KB
/
finder.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
// @flow
const JQL = require('jqljs');
const fieldsEnum = {
DISTRICT: 'd',
AMPHOE: 'a',
PROVINCE: 'p',
ZIPCODE: 'z',
};
/**
* From jquery.Thailand.js line 30 - 128
* Search result by FieldsType
*/
const preprocess = (data) => {
if (!data[0].length) {
// non-compacted database
return data;
}
// compacted database in hierarchical form of:
// [["province",[["amphur",[["district",["zip"...]]...]]...]]...]
const expanded = [];
data.forEach((provinceEntry) => {
const province = provinceEntry[0];
const amphurList = provinceEntry[1];
amphurList.forEach((amphurEntry) => {
const amphur = amphurEntry[0];
const districtList = amphurEntry[1];
districtList.forEach((districtEntry) => {
const district = districtEntry[0];
const zipCodeList = districtEntry[1];
zipCodeList.forEach((zipCode) => {
expanded.push({
d: district,
a: amphur,
p: province,
z: zipCode,
});
});
});
});
});
return expanded;
};
const DB = new JQL(preprocess(require('../jquery.Thailand.js/data.json')));
const resolveResultbyField = (type: string, searchStr: string) => {
let possibles = [];
try {
possibles = DB.select('*').where(type)
.match(`^${searchStr}`)
.orderBy(type)
.fetch();
} catch (e) {
throw e;
}
return possibles;
};
exports.resolveResultbyField = resolveResultbyField;
exports.fieldsEnum = fieldsEnum;