-
Notifications
You must be signed in to change notification settings - Fork 0
/
plain_text_delimiters.js
60 lines (50 loc) · 1.41 KB
/
plain_text_delimiters.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
58
59
60
module.exports = () => {
const self = {
fieldDelimiter: ':',
commandDelimiter: '\n',
commentToken: '#'
};
// Takes a { op: "NAME", args: [ "ARG_1", ... ]} and
// returns the formatted command suitable to write to a log file
self.stringFromCommand = ({ op, args }) => {
return [op].concat(args).join(self.fieldDelimiter) + self.commandDelimiter;
};
// Takes a formatted command from the log file (i.e. `stringFromCommand`)
// and returns { op: "OP_NAME", args: ["ARG_1", "ARG_2", "ARG_3"]}
self.commandFromString = (string) => {
const parts = [];
var acc = '';
var matchingQuote = null;
for (var i = 0; i < string.length; i++) {
if (string[i] === '"' || string[i] === "'") {
acc += string[i];
if (!matchingQuote) {
matchingQuote = string[i];
} else if (matchingQuote === string[i]) {
matchingQuote = null;
}
} else if (string[i] === self.fieldDelimiter && !matchingQuote) {
parts.push(acc);
acc = '';
} else {
acc += string[i];
}
}
if (acc) {
parts.push(acc);
}
const command = {};
command.op = parts[0];
command.args = parts.slice(1);
if (!command.op || !command.args) return;
if (command.op[0] === self.commentToken) return;
return command;
};
self.statements = (string) => {
return string.split(self.commandDelimiter).filter(c => !!c);
};
self.command = (line) => {
return self.commandFromString(line);
};
return self;
}