-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathzipcode.mjs
More file actions
63 lines (61 loc) · 1.65 KB
/
zipcode.mjs
File metadata and controls
63 lines (61 loc) · 1.65 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
import IMIMojiConverter from "https://code4sabae.github.io/imi-moji-converter-es/IMIMojiConverter.mjs";
import csvutil from "https://taisukef.github.io/util/util.mjs";
const zipcache = {};
const fromZipCode = async (code) => {
let s = code;
if (typeof s === "string") {
s = IMIMojiConverter.toHalfWidth(s).replace(/[\D]/g, "");
if (s.length < 7) {
const n = parseInt(s);
s = isNaN(n) ? "0000000" : n + "0000000";
}
s = s.substring(0, 7);
} else if (typeof s === "number") {
s = s.toString();
if (s.length < 7) {
s = "0000000" + parseInt(code);
}
s = s.substring(s.length - 7);
} else {
return [];
}
const zip0 = parseInt(s.charAt(0));
let cache = zipcache[zip0];
if (!cache) {
const fn = `data/${zip0}.csv`;
let data = null;
if (
import.meta && import.meta.url && import.meta.url.startsWith("file://") &&
window.Deno
) {
const url = import.meta.url;
const path = url.substring("file://".length, url.lastIndexOf("/") + 1);
data = await Deno.readTextFile(path + fn);
} else {
const path = "https://code4sabae.github.io/zipcode-japan-es/";
data = await (await fetch(path + fn)).text();
}
const json = {};
const csv = csvutil.decodeCSV(data);
for (const d of csv) {
const n = parseInt(d[0]);
if (!json[n]) {
json[n] = [d];
} else {
json[n].push(d);
}
}
cache = zipcache[zip0] = json;
}
const d = cache[parseInt(s)];
if (!d) return [];
return d.map((d) => {
return {
zipcode: s,
lgcode: d[1],
town: d[2],
townyomi: d[3],
};
});
};
export { fromZipCode };