UNPKG

jp-zipcode-lookup

Version:
125 lines (124 loc) 3.41 kB
"use strict"; /** * Japan Postal Zip Code Lookup * * @see https://github.com/kawanet/jp-zipcode-lookup */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Oaza = exports.City = exports.Pref = void 0; const lazy = (fn) => { let v; return () => (v || (v = fn())); }; const cache = (fn) => { const cached = {}; return (code) => ((code in cached) ? cached[code] : (cached[code] = fn(code))); }; const loadPref = lazy(() => require("../master/pref.json").pref); const loadCity = lazy(() => require("../master/city.json").city); const loadZip5 = lazy(() => require("../master/zip5.json").zip5); const loadZip7 = lazy(() => require("../master/zip7.json").zip7); const c2 = fixedString(2); const c5 = fixedString(5); const c7 = fixedString(7); /** * 都道府県 */ class Pref { constructor(code, name, kana) { this.code = code; this.name = name; this.kana = kana; } static byZipcode(zipcode) { return Oaza.byZipcode(zipcode).map(oaza => oaza.pref).filter(uniqByCode()); } } exports.Pref = Pref; Pref.byCode = cache((code) => { code = c2(code); const master = loadPref(); const pair = master[code]; return pair && new Pref(code, pair[0], pair[1]); }); /** * 市区町村 */ class City { constructor(code, name, kana) { this.code = code; this.name = name; this.kana = kana; this.pref = Pref.byCode(code.slice(0, 2)); } static byZipcode(zipcode) { return Oaza.byZipcode(zipcode).map(oaza => oaza.city).filter(uniqByCode()); } } exports.City = City; City.byCode = cache((code) => { code = c5(code); const master = loadCity(); const pair = master[code]; return pair && new City(code, pair[0], pair[1]); }); City.byPref = cache((code) => { code = +code; const master = loadCity(); const list = Object.keys(master).filter(city => (+city.slice(0, 2) === code)).map(City.byCode); return list.length ? list : undefined; }); /** * 大字 */ class Oaza { constructor(cityCode, zipcode, name) { const city = this.city = City.byCode(cityCode); this.pref = city.pref; this.code = zipcode; this.name = name; } static byZipcode(zipcode) { const master5 = loadZip5(); const master7 = loadZip7(); const zip7 = c7(zipcode); const zip5 = zip7.slice(0, 5); const row5 = master5[zip5]; const row7 = master7[zip7]; const list = []; let city; const parse = (v) => { if ("number" === typeof v) { // 市区町村コード city = c5(v); } else { // 町域名 list.push(new Oaza(city, zip7, v)); } }; const parseRow = (row) => { if ("object" === typeof row) { row.forEach(parse); } else if (row != null) { parse(row); } }; parseRow(row5); parseRow(row7); return list; } } exports.Oaza = Oaza; /** * @private */ function uniqByCode() { const index = {}; return (item) => ((!index[item.code]) && (index[item.code] = true)); } function fixedString(length) { return (number) => (number && number.length === length) ? number : ("0000000" + (+number | 0)).slice(-length); }