forked from geolonia/normalize-japanese-addresses
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.mjs
120 lines (105 loc) · 2.57 KB
/
utils.mjs
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import oldJapaneseNumerics from './oldJapaneseNumerics.mjs'
import japaneseNumerics from './japaneseNumerics.mjs'
export const largeNumbers = { '兆': 1000000000000, '億': 100000000, '万': 10000 }
export const smallNumbers = { '千': 1000, '百': 100, '十': 10 }
export function normalize(japanese) {
for (const key in oldJapaneseNumerics) {
const reg = new RegExp(key, 'g')
japanese = japanese.replace(reg, oldJapaneseNumerics[key])
}
return japanese
}
/**
* 漢数字を兆、億、万単位に分割する
*/
export function splitLargeNumber(japanese) {
let kanji = japanese
const numbers = {}
for (const key in largeNumbers) {
const reg = new RegExp(`(.+)${key}`)
const match = kanji.match(reg)
if (match) {
numbers[key] = kan2n(match[1])
kanji = kanji.replace(match[0], '')
} else {
numbers[key] = 0
}
}
if (kanji) {
numbers['千'] = kan2n(kanji)
} else {
numbers['千'] = 0
}
return numbers
}
/**
* 千単位以下の漢数字を数字に変換する(例: 三千 => 3000)
*
* @param japanese
*/
export function kan2n(japanese) {
if (japanese.match(/^[0-9]+$/)) {
return Number(japanese)
}
let kanji = zen2han(japanese)
let number = 0
for (const key in smallNumbers) {
const reg = new RegExp(`(.*)${key}`)
const match = kanji.match(reg)
if (match) {
let n = 1
if (match[1]) {
if (match[1].match(/^[0-9]+$/)) {
n = Number(match[1])
} else {
n = japaneseNumerics[match[1]]
}
}
number = number + (n * smallNumbers[key])
kanji = kanji.replace(match[0], '')
}
}
if (kanji) {
if (kanji.match(/^[0-9]+$/)) {
number = number + Number(kanji)
} else {
number = number + japaneseNumerics[kanji]
}
}
return number
}
/**
* Converts number less than 10000 to kanji.
*
* @param num
*/
export function n2kan(num) {
const kanjiNumbers = Object.keys(japaneseNumerics)
let number = num
let kanji = ''
for (const key in smallNumbers) {
const n = Math.floor(number / smallNumbers[key])
if (n) {
number = number - (n * smallNumbers[key])
if (1 === n) {
kanji = `${kanji}${key}`
} else {
kanji = `${kanji}${kanjiNumbers[n]}${key}`
}
}
}
if (number) {
kanji = `${kanji}${kanjiNumbers[number]}`
}
return kanji
}
/**
* Converts double-width number to number as string.
*
* @param num
*/
export function zen2han(str) {
return str.replace(/[0-9]/g, (s) => {
return String.fromCharCode(s.charCodeAt(0) - 0xFEE0);
});
}