forked from geolonia/normalize-japanese-addresses
-
Notifications
You must be signed in to change notification settings - Fork 0
/
japaneseNumeral.mjs
77 lines (64 loc) · 2.43 KB
/
japaneseNumeral.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
import { normalize, splitLargeNumber, largeNumbers, n2kan } from './utils.mjs'
import japaneseNumerics from './japaneseNumerics.mjs'
export function kanji2number(japanese/*: string*/) {
japanese = normalize(japanese)
if (japanese.match('〇') || japanese.match(/^[〇一二三四五六七八九]+$/)) {
for (const key in japaneseNumerics) {
const reg = new RegExp(key, 'g')
japanese = japanese.replace(reg, japaneseNumerics[key].toString())
}
return Number(japanese)
} else {
let number = 0
const numbers = splitLargeNumber(japanese)
// 万以上の数字を数値に変換
for (const key in largeNumbers) {
if (numbers[key]) {
const n = largeNumbers[key] * numbers[key]
number = number + n
}
}
if (!Number.isInteger(number) || !Number.isInteger(numbers['千'])) {
throw new TypeError('The attribute of kanji2number() must be a Japanese numeral as integer.')
}
// 千以下の数字を足す
return number + numbers['千']
}
}
export function number2kanji(num/*: number*/) {
if (!num.toString().match(/^[0-9]+$/)) {
throw new TypeError('The attribute of number2kanji() must be integer.')
}
const kanjiNumbers = Object.keys(japaneseNumerics)
let number = num
let kanji = ''
// 万以上の数字を漢字に変換
for (const key in largeNumbers) {
const n = Math.floor(number / largeNumbers[key])
if (n) {
number = number - (n * largeNumbers[key])
kanji = `${kanji}${n2kan(n)}${key}`
}
}
if (number) {
kanji = `${kanji}${n2kan(number)}`
}
return kanji
}
export function findKanjiNumbers(text/*: string*/) {
const basePattern = '([0-90-9一二三四五六七八九壱壹弐貳貮参參肆伍陸漆捌玖]*(千|阡|仟))?([0-90-9一二三四五六七八九壱壹弐貳貮参參肆伍陸漆捌玖]*(百|陌|佰))?([0-90-9一二三四五六七八九壱壹弐貳貮参參肆伍陸漆捌玖]*(十|拾))?([0-90-9〇一二三四五六七八九壱壹弐貳貮参參肆伍陸漆捌玖]+)?'
const pattern = `(${basePattern}兆)?(${basePattern}億)?(${basePattern}(万|萬))?${basePattern}`
const regex = new RegExp(pattern, 'g')
const match = text.match(regex)
if (match) {
return match.filter((item) => {
if (item.length && '兆' !== item && '億' !== item && '万' !== item && '萬' !== item) {
return true
} else {
return false
}
})
} else {
return []
}
}