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
type Markov = Record<string, Record<string, number>>;
export const markovPairwiseOfStrings = (strings: string[]) => {
const markov: Markov = {};
//
// Loop over `strings`
strings.forEach((input) => {
// We'll loop from the start of the string, to one before the end
for (let i = 0; i < input.length - 1; i++) {
// Instead of input[i], we'll grab two characters starting at i
const stem = input.slice(i, i + 2);
// START -->
if (i === 0) {
markov["START"] ??= {};
markov["START"][stem] ??= 0;
markov["START"][stem]++;
}
// Instead of input[i+1], we'll grab two characters starting at i+1
const next = i === input.length - 2 ? "END" : input.slice(i + 1, i + 3);
markov[stem] ??= {};
markov[stem][next] ??= 0;
markov[stem][next]++;
}
});
return markov;
};