-
Notifications
You must be signed in to change notification settings - Fork 12
/
box.js
84 lines (75 loc) · 1.97 KB
/
box.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
function countLines(text, position) {
var count = 0;
for (var i = 0; i < position; i++) {
if (text.charAt(i) == '\n') count++;
}
return count;
}
function startOfLinePosition(text, lineNumber) {
var count = 0;
for (var i = 0; i < text.length; i++) {
if (text.charAt(i) == '\n') {
count++;
if (count >= lineNumber) return i + 1;
}
}
return i;
}
function changeLetter(text, lineNumber, newLetter) {
var lines = text.split('\n');
if (!lines[lineNumber]) {
throw 'No line ' + lineNumber + ' in text';
}
var lineParts = lines[lineNumber].split(' ');
lineParts[0] = newLetter;
lines[lineNumber] = lineParts.join(' ');
return lines.join('\n');
}
function parseBoxLine(line) {
var parts = line.split(' ');
return {
letter: parts[0],
left: parseInt(parts[1], 0),
top: parseInt(parts[2], 0),
right: parseInt(parts[3], 0),
bottom: parseInt(parts[4], 0),
rest: parts.slice(5).join(' ')
}
}
function serializeBoxLine(box) {
return [box.letter, box.left, box.top, box.right, box.bottom, box.rest].join(' ');
}
function splitLine(text, lineNumber, numWays) {
var lines = text.split('\n');
if (!lines[lineNumber]) {
throw 'No line ' + lineNumber + ' in text';
}
var box = parseBoxLine(lines[lineNumber]);
var x = function(idx) { // idx is in 0..numWays
return Math.round(box.left + (box.right - box.left) * idx / numWays);
};
var newBoxes = [];
for (var i = 0; i < numWays; i++) newBoxes.push(i);
newBoxes = newBoxes.map((_, i) => ({
letter: box.letter,
left: x(i),
right: x(i + 1),
top: box.top,
bottom: box.bottom,
rest: box.rest
}));
var newLines = newBoxes.map(serializeBoxLine),
spliceArgs = [lineNumber, 1].concat(newLines);
[].splice.apply(lines, spliceArgs);
return lines.join('\n');
}
if (typeof(module) !== 'undefined') {
module.exports = {
countLines,
startOfLinePosition,
changeLetter,
parseBoxLine,
serializeBoxLine,
splitLine
};
}