@janekolszak/poland 1.0.3 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/compute.ts CHANGED
@@ -1,22 +1,43 @@
1
- import { Region } from "./csvparse"
1
+ import { LocalityType, Region, Locality } from "./csvparse"
2
+ import { MultiKeyMap } from "./map"
2
3
 
3
4
  export interface NamesMap {
4
5
  [postcode: string]: Array<string>
5
6
  };
6
7
 
8
+ export interface NamesMapTwoKeys {
9
+ [postcode: string]: NamesMap
10
+ };
11
+
12
+ export interface NamesMapThreeKeys {
13
+ [postcode: string]: NamesMapTwoKeys
14
+ };
15
+ export interface NamesMapFourKeys {
16
+ [postcode: string]: NamesMapThreeKeys
17
+ };
18
+
7
19
  export interface Computed {
8
20
  voivodeships: string[]
9
21
  counties: NamesMap
10
- municipalities: NamesMap
22
+ municipalities: MultiKeyMap
23
+ localities: MultiKeyMap
24
+ districts: MultiKeyMap
11
25
  }
12
26
 
13
- export function compute(regions: Array<Region>): Computed {
27
+ export function compute(regions: Array<Region>, localities: Array<Locality>, localityTypes: Array<LocalityType>): Computed {
14
28
  let out: Computed = {
15
29
  voivodeships: [],
16
30
  counties: {},
17
- municipalities: {},
31
+ municipalities: new MultiKeyMap(),
32
+ localities: new MultiKeyMap(),
33
+ districts: new MultiKeyMap()
18
34
  }
19
35
 
36
+ const locTypeIdMap: Map<string, string> = new Map(localityTypes.map(r => [r.name, r.id]))
37
+
38
+ const countyIdMap = new MultiKeyMap();
39
+ const municipalityIdMap = new MultiKeyMap();
40
+
20
41
  // Województwa
21
42
  out.voivodeships = regions.filter(r => r.type === "województwo").map(r => r.name)
22
43
 
@@ -28,32 +49,141 @@ export function compute(regions: Array<Region>): Computed {
28
49
  let d = out.counties[v!]
29
50
  d = d ? d : []
30
51
  out.counties[v!] = [...d, r.name]
52
+
53
+ countyIdMap.set([r.voivodeship, r.county], r.name)
31
54
  })
32
55
 
33
56
  // Gminy
34
- out.voivodeships.forEach(voivodeship => {
35
- const countiesIdMap: Map<string, string> = new Map(
36
- regions
37
- .filter(r => vivIdMap.get(r.voivodeship) === voivodeship)
38
- .filter(r => r.type === "powiat" || r.type.indexOf("na prawach powiatu") >= 0)
39
- .map(r => [r.county, r.name])
40
- )
41
- regions
42
- .filter(r => vivIdMap.get(r.voivodeship) === voivodeship)
43
- .filter(r => r.municipality !== "")
44
- .filter(r => r.type !== "województwo")
45
- .filter(r => r.type !== "powiat")
46
- .filter(r => r.type.indexOf("na prawach powiatu") === -1)
47
- .forEach(r => {
48
- const v = countiesIdMap.get(r.county)
49
- let d = out.municipalities[v!]
50
- d = d ? d : []
51
- if (d.includes(r.name)) {
52
- return
53
- }
54
- out.municipalities[v!] = [...d, r.name]
55
- })
56
- })
57
+ regions
58
+ .filter(r => r.voivodeship !== "")
59
+ .filter(r => r.county !== "")
60
+ .filter(r => r.municipality !== "")
61
+ .filter(r => r.type.startsWith("gmina"))
62
+ .forEach(r => {
63
+ const v = vivIdMap.get(r.voivodeship)
64
+ const c = countyIdMap.get([r.voivodeship, r.county])
65
+
66
+ let d = out.municipalities.get([v, c]) as Array<string>
67
+ d = d ? d : []
68
+ if (!d.includes(r.name)) {
69
+ out.municipalities.set([v, c], [...d, r.name])
70
+ }
71
+
72
+ municipalityIdMap.set([r.voivodeship, r.county, r.municipality], r.name)
73
+ })
74
+
75
+
76
+ // Miejscowosci
77
+ let localityTypeIds = [
78
+ locTypeIdMap.get("wieś"),
79
+ locTypeIdMap.get("kolonia"),
80
+ locTypeIdMap.get("osada"),
81
+ locTypeIdMap.get("osada leśna"),
82
+ locTypeIdMap.get("miasto")
83
+ ]
84
+
85
+ localities
86
+ .filter(r => localityTypeIds.includes(r.localityTypeId))
87
+ .forEach(r => {
88
+ const v = vivIdMap.get(r.voivodeship)
89
+ const c = countyIdMap.get([r.voivodeship, r.county])
90
+ const m = municipalityIdMap.get([r.voivodeship, r.county, r.municipality])
91
+
92
+ if (!v || !c || !m) {
93
+ console.error("Missing voivodeship, county or municipality for locality: " + r.name + " (" + r.voivodeship + ", " + r.county + ", " + r.municipality + ")")
94
+ return
95
+ }
96
+
97
+ let d = out.localities.get([v, c, m]) as Array<string>
98
+ d = d ? d : []
99
+ if (!d.includes(r.name)) {
100
+ out.localities.set([v, c, m], [...d, r.name])
101
+ out.districts.set([v, c, m, r.name], [])
102
+ }
103
+ })
104
+
105
+ // Dzielnice
106
+ const allLocalitiesIdMap = new Map(localities.map(r => [r.localityId, r.name]))
107
+
108
+ let districtIds = [
109
+ locTypeIdMap.get("dzielnica"),
110
+ locTypeIdMap.get("delegatura"),
111
+ locTypeIdMap.get("część miasta"),
112
+ ]
113
+
114
+ // let a = new Map(localities.map(r => [r.localityTypeId, true]))
115
+ // console.log(a)
116
+
117
+ localities
118
+ .filter(r => districtIds.includes(r.localityTypeId))
119
+ .forEach(r => {
120
+ const v = vivIdMap.get(r.voivodeship)
121
+ const c = countyIdMap.get([r.voivodeship, r.county])
122
+ const m = municipalityIdMap.get([r.voivodeship, r.county, r.municipality])
123
+ const l = allLocalitiesIdMap.get(r.baseLocalityId)
124
+
125
+ if (!v || !c || !m || !l) {
126
+ // console.error("Missing voivodeship, county, municipality or base locality for district: " + r.name + " (" + v + ", " + c + ", " + m + ", " + l + ")")
127
+ // console.error(r.voivodeship, r.county, r.municipality)
128
+ return
129
+ }
130
+
131
+ let d = out.districts.get([v, c, m, l]) as Array<string>
132
+ d = d ? d : []
133
+ if (r.baseLocalityId === r.localityId) {
134
+ out.districts.set([v, c, m, l], [...d])
135
+ } else if (!d.includes(r.name)) {
136
+ out.districts.set([v, c, m, l], [...d, r.name])
137
+ }
138
+ })
139
+
140
+ // Dzielnice Warszawy
141
+ regions
142
+ .filter(r => r.typeId === "8")
143
+ .forEach(r => {
144
+ const v = vivIdMap.get(r.voivodeship)
145
+ const c = countyIdMap.get([r.voivodeship, r.county])
146
+ const m = "Warszawa"
147
+ const l = "Warszawa"
148
+
149
+ if (!v || !c || !m || !l) {
150
+ console.error("4 Missing voivodeship, county, municipality or base locality for district: " + r.name + " (" + v + ", " + c + ", " + m + ", " + l + ")")
151
+ console.error(r.voivodeship, r.county, r.municipality)
152
+ return
153
+ }
154
+
155
+ let d = out.districts.get([v, c, m, l]) as Array<string>
156
+ d = d ? d : []
157
+ out.districts.set([v, c, m, l], [...d, r.name])
158
+ })
159
+
160
+
161
+ // 9 - delegatury miast: Kraków, Łódź, Poznań i Wrocław
162
+ regions
163
+ .filter(r => r.typeId === "9")
164
+ .forEach(r => {
165
+ const v = vivIdMap.get(r.voivodeship)
166
+ const c = countyIdMap.get([r.voivodeship, r.county])
167
+ const m = r.name.substring(0, r.name.indexOf('-'))
168
+ const l = r.name.substring(0, r.name.indexOf('-'))
169
+ const name = r.name.substring(r.name.indexOf('-') + 1)
170
+
171
+ if (!v || !c || !m || !l) {
172
+ console.error("4 Missing voivodeship, county, municipality or base locality for district: " + r.name + " (" + v + ", " + c + ", " + m + ", " + l + ")")
173
+ console.error(r.voivodeship, r.county, r.municipality)
174
+ return
175
+ }
176
+
177
+ let d = out.districts.get([v, c, m, l]) as Array<string>
178
+ d = d ? d : []
179
+ out.districts.set([v, c, m, l], [...d, name])
180
+ })
181
+ // console.log(out.districts)
182
+
183
+
184
+ out.municipalities.sortValues()
185
+ out.localities.sortValues()
186
+ out.districts.sortValues()
57
187
 
58
188
  return out
59
189
  }
package/src/csvparse.ts CHANGED
@@ -8,9 +8,29 @@ export type Region = {
8
8
  county: string;
9
9
  municipality: string;
10
10
  type: string;
11
- typeId: number;
11
+ typeId: string;
12
12
  name: string;
13
13
  date: string;
14
+ localityId: string;
15
+ baseLocalityId: string;
16
+ };
17
+
18
+ export type Locality = {
19
+ voivodeship: string
20
+ county: string;
21
+ municipality: string;
22
+ municipalityTypeId: string;
23
+ localityTypeId: string;
24
+ isLocalName: string;
25
+ name: string;
26
+ localityId: string;
27
+ baseLocalityId: string;
28
+ date: string;
29
+ };
30
+
31
+ export type LocalityType = {
32
+ id: string;
33
+ name: string;
14
34
  };
15
35
 
16
36
  function toTitleCase(str: String) {
@@ -44,3 +64,51 @@ export async function parseCsv() {
44
64
  await finished(parser);
45
65
  return records;
46
66
  };
67
+
68
+ export async function parseLocalityCsv() {
69
+ const records: Locality[] = [];
70
+ const parser = fs
71
+ .createReadStream(args.localities)
72
+ .pipe(parse({
73
+ relax_quotes: true,
74
+ delimiter: ';',
75
+ skip_empty_lines: true,
76
+ record_delimiter: '\r\n',
77
+ columns: () => {
78
+ return ["voivodeship", "county", "municipality", "municipalityTypeId", "localityTypeId", "isLocalName", "name", "localityId", "baseLocalityId", "date"]
79
+ },
80
+ }))
81
+ .on('readable', function () {
82
+ let record; while ((record = parser.read()) !== null) {
83
+ // Work with each record
84
+ record.name = toTitleCase(record.name)
85
+ records.push(record);
86
+ }
87
+ });
88
+ await finished(parser);
89
+ return records;
90
+ };
91
+
92
+ export async function parseLocalityTypeCsv() {
93
+ const records: LocalityType[] = [];
94
+ const parser = fs
95
+ .createReadStream(args.types)
96
+ .pipe(parse({
97
+ relax_quotes: true,
98
+ delimiter: ';',
99
+ skip_empty_lines: true,
100
+ record_delimiter: '\r\n',
101
+ columns: () => {
102
+ return ["id", "name", "date"]
103
+ },
104
+ }))
105
+ .on('readable', function () {
106
+ let record; while ((record = parser.read()) !== null) {
107
+ // Work with each record
108
+ // record.name = toTitleCase(record.name)
109
+ records.push(record);
110
+ }
111
+ });
112
+ await finished(parser);
113
+ return records;
114
+ };
package/src/generate.ts CHANGED
@@ -5,33 +5,36 @@ import fs from 'fs';
5
5
  function genJson(c: Computed) {
6
6
  fs.writeFileSync(args.output + "/json/voivodeships.json", JSON.stringify(c.voivodeships))
7
7
  fs.writeFileSync(args.output + "/json/counties.json", JSON.stringify(c.counties))
8
- fs.writeFileSync(args.output + "/json/municipalities.json", JSON.stringify(c.municipalities))
8
+ fs.writeFileSync(args.output + "/json/municipalities.json", JSON.stringify(c.municipalities.Get2Deep()))
9
+ fs.writeFileSync(args.output + "/json/localities.json", JSON.stringify(c.localities.Get3Deep()))
10
+ fs.writeFileSync(args.output + "/json/districts.json", JSON.stringify(c.districts.Get4Deep()))
11
+
9
12
  }
10
13
 
11
14
  function genGo(c: Computed) {
12
- const voivodeships = c.voivodeships.map(v => `"${v}"`).join(",")
13
- const counties = JSON.stringify(c.counties).replace(/[\[]+/g, "{").replace(/[\]']+/g, "}")
14
- const municipalities = JSON.stringify(c.municipalities).replace(/[\[]+/g, "{").replace(/[\]']+/g, "}")
15
-
15
+ fs.copyFileSync(args.output + "/json/voivodeships.json", args.output + "/go/voivodeships.json")
16
+ fs.copyFileSync(args.output + "/json/counties.json", args.output + "/go/counties.json")
17
+ fs.copyFileSync(args.output + "/json/municipalities.json", args.output + "/go/municipalities.json")
18
+ fs.copyFileSync(args.output + "/json/localities.json", args.output + "/go/localities.json")
19
+ fs.copyFileSync(args.output + "/json/districts.json", args.output + "/go/districts.json")
16
20
  const data = `package poland
17
-
18
- var (
19
- Voivodeships = []string{${voivodeships}}
20
- Counties = map[string][]string${counties}
21
- Municipalities = map[string][]string${municipalities}
22
- )`
23
- fs.writeFileSync(args.output + "/go/data.go", data)
21
+ import (
22
+ "embed"
23
+ )
24
+
25
+ //go:embed *.json
26
+ var FS embed.FS
27
+ `
28
+ fs.writeFileSync(args.output + "/go/root.go", data)
24
29
  }
25
30
 
26
31
  function genTypescript(c: Computed) {
27
32
  const voivodeships = JSON.stringify(c.voivodeships)
28
33
  const counties = Object.entries(c.counties).map(data => `["${data[0]}", ${JSON.stringify(data[1])}]`).join(",")
29
- const municipalities = Object.entries(c.municipalities).map(data => `["${data[0]}", ${JSON.stringify(data[1])}]`).join(",")
30
34
 
31
35
  const data = `
32
36
  export const voivodeships: Array<string> = ${voivodeships}
33
37
  export const counties = new Map<string,Array<string>>([${counties}])
34
- export const municipalities = new Map<string,Array<string>>([${municipalities}])
35
38
  `
36
39
  fs.writeFileSync(args.output + "/typescript/data.ts", data)
37
40
  }
package/src/map.ts ADDED
@@ -0,0 +1,112 @@
1
+ import { NamesMapThreeKeys, NamesMapFourKeys, NamesMapTwoKeys } from "./compute";
2
+
3
+ export class MultiKeyMap {
4
+ private map: Record<string, any> = {};
5
+
6
+ private getKey(key: string[]): string {
7
+ return key.join('|');
8
+ }
9
+
10
+ set(key: string[], value: any): void {
11
+ const strKey = this.getKey(key);
12
+ this.map[strKey] = value;
13
+ }
14
+
15
+ get(key: string[]): any | undefined {
16
+ const strKey = this.getKey(key);
17
+ return this.map[strKey];
18
+ }
19
+
20
+ delete(key: string[]): boolean {
21
+ const strKey = this.getKey(key);
22
+
23
+ if (strKey in this.map) {
24
+ delete this.map[strKey];
25
+ return true;
26
+ }
27
+
28
+ return false;
29
+ }
30
+
31
+ has(key: string[]): boolean {
32
+ const strKey = this.getKey(key);
33
+ return strKey in this.map;
34
+ }
35
+
36
+ get size(): number {
37
+ return Object.keys(this.map).length;
38
+ }
39
+
40
+ clear(): void {
41
+ this.map = {};
42
+ }
43
+
44
+ sortValues(): void {
45
+ for (const strKey in this.map) {
46
+ let value = this.map[strKey];
47
+ value.sort()
48
+ }
49
+ }
50
+
51
+ forEach(callbackfn: (keys: string[], value: any, map: MultiKeyMap) => void): void {
52
+ for (const strKey in this.map) {
53
+ const value = this.map[strKey];
54
+ const keys = strKey.split('|');
55
+ callbackfn(keys, value, this);
56
+ }
57
+ }
58
+
59
+ Get2Deep(): NamesMapTwoKeys {
60
+ var out: NamesMapTwoKeys = {}
61
+ this.forEach((keys, value) => {
62
+ const [v, c] = keys
63
+ if (!out[v]) {
64
+ out[v] = {}
65
+ }
66
+ if (!out[v][c]) {
67
+ out[v][c] = []
68
+ }
69
+ out[v][c].push(value)
70
+ })
71
+ return out
72
+ }
73
+
74
+ Get3Deep(): NamesMapThreeKeys {
75
+ var out: NamesMapThreeKeys = {}
76
+ this.forEach((keys, value) => {
77
+ const [v, c, m] = keys
78
+ if (!out[v]) {
79
+ out[v] = {}
80
+ }
81
+ if (!out[v][c]) {
82
+ out[v][c] = {}
83
+ }
84
+ if (!out[v][c][m]) {
85
+ out[v][c][m] = []
86
+ }
87
+ out[v][c][m].push(value)
88
+ })
89
+ return out
90
+ }
91
+
92
+ Get4Deep(): NamesMapFourKeys {
93
+ var out: NamesMapFourKeys = {}
94
+ this.forEach((keys, value) => {
95
+ const [v, c, m, l] = keys
96
+ if (!out[v]) {
97
+ out[v] = {}
98
+ }
99
+ if (!out[v][c]) {
100
+ out[v][c] = {}
101
+ }
102
+ if (!out[v][c][m]) {
103
+ out[v][c][m] = {}
104
+ }
105
+ if (!out[v][c][m][l]) {
106
+ out[v][c][m][l] = []
107
+ }
108
+ out[v][c][m][l].push(value)
109
+ })
110
+ return out
111
+ }
112
+ }
package/tsconfig.json CHANGED
@@ -11,7 +11,7 @@
11
11
  // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
12
 
13
13
  /* Language and Environment */
14
- "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
14
+ "target": "ES6", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
15
  // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
16
  // "jsx": "preserve", /* Specify what JSX code is generated. */
17
17
  // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
@@ -27,7 +27,7 @@
27
27
  /* Modules */
28
28
  "module": "CommonJS", /* Specify what module code is generated. */
29
29
  // "rootDir": "./", /* Specify the root folder within your source files. */
30
- // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
30
+ "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
31
31
  // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
32
  // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
33
  // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
@@ -48,8 +48,8 @@
48
48
  // "declarationMap": true, /* Create sourcemaps for d.ts files. */
49
49
  // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
50
50
  "sourceMap": true, /* Create source map files for emitted JavaScript files. */
51
- // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
52
- // "outDir": "./", /* Specify an output folder for all emitted files. */
51
+ // "outFile": "./out.js", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
52
+ "outDir": "./dist", /* Specify an output folder for all emitted files. */
53
53
  // "removeComments": true, /* Disable emitting comments. */
54
54
  // "noEmit": true, /* Disable emitting files from a compilation. */
55
55
  // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */