/
ChainTemplateService.ts
86 lines (68 loc) · 2.32 KB
/
ChainTemplateService.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
import { mustExist } from '@apextoaster/js-utils';
import { BaseOptions, Inject } from 'noicejs';
import { TemplateService } from '.';
import { BaseTemplate, TemplateNumber, TemplateString } from '../../model/meta/Template';
import { INJECT_RANDOM } from '../../module';
import { JoinChain } from '../../util/template/JoinChain';
import { splitChain } from '../../util/template/SplitChain';
import { VerbMap, VerbSlot } from '../../util/types';
import { RandomGenerator } from '../random';
export interface PipeTemplateOptions extends BaseOptions {
[INJECT_RANDOM]?: RandomGenerator;
}
@Inject(INJECT_RANDOM)
export class ChainTemplateService implements TemplateService {
protected readonly joiner: JoinChain;
protected readonly random: RandomGenerator;
constructor(options: PipeTemplateOptions) {
this.random = mustExist(options[INJECT_RANDOM]);
this.joiner = new JoinChain({
joiners: [' '],
random: this.random,
});
}
public renderString(input: TemplateString): string {
const chain = splitChain(input.base, {
group: {
start: '(',
end: ')',
},
split: '|',
});
return this.joiner.render(chain);
}
public renderNumber(input: TemplateNumber): number {
return this.random.nextInt(input.max, input.min);
}
public renderNumberList(input: Array<TemplateNumber>): Array<number> {
return input.map((it) => this.renderNumber(it));
}
public renderStringList(input: Array<TemplateString>): Array<string> {
return input.map((it) => this.renderString(it));
}
public renderNumberMap(input: Map<string, TemplateNumber>): Map<string, number> {
const result = new Map();
for (const [key, value] of input) {
result.set(key, this.renderNumber(value));
}
return result;
}
public renderStringMap(input: Map<string, TemplateString>): Map<string, string> {
const result = new Map();
for (const [key, value] of input) {
result.set(key, this.renderString(value));
}
return result;
}
public renderVerbMap(input: Map<string, BaseTemplate<VerbSlot>>): VerbMap {
const result = new Map();
for (const [key, value] of input) {
const verb: VerbSlot = {
slot: this.renderString(value.slot),
data: {}, // TODO: render this stuff
};
result.set(key, verb);
}
return result;
}
}