-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.js
57 lines (53 loc) · 1.24 KB
/
state.js
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
function updateTimer(state) {
if (!state.start) {
state.start = Date.now();
}
if (
!state.finish &&
state.cursor === state.text.length &&
!state.text.some((c) => c.miss)
) {
state.finish = Date.now();
}
return state;
}
export function handleChar(state, key) {
if (state.cursor === state.text.length) {
state.misses++;
return updateTimer(state);
}
if (state.text[state.cursor].target === key) {
state.hits++;
} else {
state.misses++;
state.text[state.cursor].miss = key;
}
state.cursor++;
return updateTimer(state);
}
export function handleBackspace(state) {
state.cursor = Math.max(state.cursor - 1, 0);
delete state.text[state.cursor].miss;
return state;
}
export function handleBackspaceWord(state) {
const prevChar = () =>
state.text[state.cursor - 1].miss || state.text[state.cursor - 1].target;
let seenNonSpace;
while (state.cursor > 0 && (!seenNonSpace || prevChar() !== " ")) {
if (prevChar() !== " ") {
seenNonSpace = true;
}
state = handleBackspace(state);
}
return state;
}
export function makeState(text, wordCount) {
return {
cursor: 0,
text: text.split("").map((c) => ({ target: c })),
hits: 0,
misses: 0,
wordCount,
};
}