-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
99 lines (87 loc) · 2.2 KB
/
index.ts
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
export type Span = {
text: string
mark?: number
}
export const sizes: Array<number> = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000,
6000, 7000, 8000, 9000, 10000, 20000, 30000, 40000, 50000, 60000,
70000, 80000, 90000, 100000, 200000, 300000, 400000, 500000, 600000,
700000, 800000, 900000,
]
export const sum = (array: Array<number>): number =>
array.reduce((m, x) => m + x, 0)
export const base = (number: number): number => {
let input: Array<number> = split(number)
while (true) {
const s: number = sum(input)
if (s < 10) {
return s
}
input = split(s)
}
}
export const mass = (lines: Array<Span>) => {
return sum(
lines.map(line => line.mark).filter(mark => mark) as Array<
Required<number>
>,
)
}
export const link = (lines: Array<Span>) => {
return lines
.map(line => line.mark)
.filter(x => x)
.join('')
}
export const split = (number: number) =>
String(number)
.split('')
.map(x => parseInt(x, 10))
export const buildSiteLister =
(
base: Record<string, number>,
mappings: Record<string, string> = {},
) =>
(text: string) => {
const glyphs = [...text]
const spans: Array<Span> = []
for (const glyph of glyphs) {
let key = glyph
const mapping = mappings[key]
if (mapping) {
key = mapping
}
const mark = base[key]
if (mark) {
spans.push({
mark,
text: glyph,
})
} else {
const last = spans[spans.length - 1]
if (last && !last.mark) {
last.text += glyph
} else {
spans.push({
text: glyph,
})
}
}
}
return spans
}
export const buildBaseLister =
(listSite: (text: string) => Array<Span>) => (text: string) => {
return listSite(text).map(({ text, mark }) => ({
text,
mark: mark ? base(mark) : undefined,
}))
}
export const buildSizeLister =
(listSite: (text: string) => Array<Span>) => (text: string) => {
return listSite(text).map(({ text, mark }) => ({
text,
mark: mark ? sizes[mark - 1]! : undefined,
}))
}