-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathparse-input.ts
More file actions
81 lines (66 loc) · 2.02 KB
/
parse-input.ts
File metadata and controls
81 lines (66 loc) · 2.02 KB
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
import last from 'lodash.last';
import { FileStructure } from './FileStructure';
/**
* Matches the whitespace in front of a file name.
* Also will match a markdown bullet point if included.
* For example, testing against " - hello" will return
* a positive match with the first capturing group
* with " - " and a second with " "
*/
const leadingWhitespaceAndBulletRegex = /^((\s*)(?:-\s)?)/;
/** Matches lines that only contain whitespace */
const onlyWhitespaceRegex = /^\s*$/;
/** Used to split a block of text into individual lines */
const newlineSplitterRegex = /[^\r\n]+/g;
/**
* Translates a block of user-created text into
* a nested FileStructure structure
* @param input The plain-text input from the user
*/
export const parseInput = (input: string): FileStructure => {
const structures = splitInput(input);
const root: FileStructure = {
name: '.',
children: [],
indentCount: -1,
parent: null,
};
const path = [root];
for (const s of structures) {
while (last(path)!.indentCount >= s.indentCount) {
path.pop();
}
const parent = last(path) as FileStructure;
parent.children.push(s);
s.parent = parent;
path.push(s);
}
return root;
};
/**
* Splits a block of user-created text into
* individual, un-nested FileStructure objects.
* Used internally as part of `parseInput`.
* @param input The plain-text input from the user
*/
export const splitInput = (input: string): FileStructure[] => {
let lines = input.match(newlineSplitterRegex) || [];
// filter out empty lines
lines = lines.filter(l => !onlyWhitespaceRegex.test(l));
return lines.map(l => {
const matchResult = leadingWhitespaceAndBulletRegex.exec(l);
if (!matchResult) {
throw new Error(
`Unable to execute leadingWhitespaceAndBulletRegex against string: "${l}"`,
);
}
const name = l.replace(matchResult[1], '');
const indentCount = matchResult[2].length;
return {
name,
children: [],
indentCount,
parent: null,
};
});
};