-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
106 lines (90 loc) · 2.68 KB
/
index.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
function getStringBetween(
before = null,
after = null,
minCharCode = 48,
maxCharCode = 126
) {
// Min and max char codes possible
const CHARCODES = [minCharCode, maxCharCode]; // 0-9 => [48, 57]
const firstChar = String.fromCharCode(CHARCODES[0]); // Should never return a string with first character at the end
const middleChar = String.fromCharCode(
Math.floor((CHARCODES[0] + CHARCODES[1]) / 2)
);
if (!before && !after) {
return middleChar;
}
if (!before) {
before = firstChar;
}
function getNextChar(char) {
const charCode = char.charCodeAt(0);
let nextCharCode;
if (charCode >= CHARCODES[1]) {
return null;
} else {
nextCharCode = charCode + 1;
}
return String.fromCharCode(nextCharCode);
}
// Take last char and check if a next char exists
// If not we add middleChar, if yes we update with next char
function nextLastChar(str) {
const nextChar = getNextChar(str[str.length - 1]);
if (!nextChar) {
return `${str}${middleChar}`;
}
return `${str.slice(0, -1)}${nextChar}`;
}
// We add at the end
if (!after) {
return nextLastChar(before);
}
if (before === after) {
throw new Error(`No string between ${before} and ${after}.`);
}
// Swap before and after
if (before >= after) {
const temp = before;
before = after;
after = temp;
}
// We pad before with first char, so that we can compare same length
before = before.padEnd(after.length, firstChar);
after = after.padEnd(before.length, firstChar);
let newStr = "";
for (let i = 0; i < after.length; i++) {
const beforeChar = before[i];
const beforeCharCode = beforeChar && beforeChar.charCodeAt(0);
const afterChar = after[i];
const afterCharCode = afterChar && afterChar.charCodeAt(0);
if (beforeChar === afterChar) {
newStr += beforeChar;
continue;
}
const roomBetween = afterCharCode - beforeCharCode - 1;
if (roomBetween < 1) {
// If afterChar is firstChar it means 85 vs 90
// (firstChar here is from padEnd because no response string can finish by firstChar otherwise)
// so we can just getNextChar of 5 ==> 86
if (afterChar === firstChar) {
newStr = nextLastChar(newStr + beforeChar);
break;
}
// Last char, we add middle char
else if (i === after.length - 1) {
newStr += `${beforeChar}${middleChar}`;
} else {
newStr += beforeChar;
continue;
}
} else {
const betweenChar = String.fromCharCode(
Math.floor((afterCharCode + beforeCharCode) / 2)
);
newStr += betweenChar;
}
break;
}
return newStr;
}
module.exports = getStringBetween;