-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreconstituteSegment.js
86 lines (74 loc) · 2.48 KB
/
reconstituteSegment.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
const segmentsFromAtoM = [
["A", "B", "C"],
["G", "F", "E"],
["G", "H", "I"],
["K", "J", "I"],
["C", "D", "E"],
["K", "L", "M"],
];
const segmentsFromMtoA = [
["C", "B", "A"],
["G", "F", "E"],
["G", "H", "I"],
["K", "J", "I"],
["C", "D", "E"],
["K", "L", "M"],
["Hello", "world", "!!"],
];
const invalidSegments = null;
const reconstituteSegment = (segments) => {
if (!segments || !segments.length) {
return segments;
}
let result = segments.shift();
while (segments.length) {
const matchingSegment = popFirstMatchingSegment(segments, result);
if (matchingSegment)
result = concatenateSegments(result, matchingSegment);
else {
console.error("there is", segments.length, "elem(s) not linked =>", segments);
break;
}
}
return result;
}
const popFirstMatchingSegment = (segments, segmentToMatch) => {
const leftBounderyToMatch = segmentToMatch[0];
const rightBounderyToMatch = segmentToMatch[segmentToMatch.length - 1];
for (let index = 0; index < segments.length; index++) {
const leftBoundery = segments[index][0];
const rightBoundery = segments[index][segments[index].length - 1];
if (leftBoundery === leftBounderyToMatch
|| leftBoundery === rightBounderyToMatch
|| rightBoundery === leftBounderyToMatch
|| rightBoundery === rightBounderyToMatch) {
return segments.splice(segments.indexOf(segments[index]), 1)[0];
}
}
}
const concatenateSegments = (segment1, segment2) => {
const leftBounderySegment1 = segment1[0];
const leftBounderySegment2 = segment2[0];
const rightBounderySegment1 = segment1[segment1.length - 1];
const rightBounderySegment2 = segment2[segment2.length - 1];
if (leftBounderySegment1 === leftBounderySegment2) {
segment2.reverse();
segment2.splice(segment2.length - 1, 1);
segment1.unshift(...segment2);
}
else if (rightBounderySegment2 === rightBounderySegment1) {
segment2.reverse();
segment2.splice(0, 1);
segment1.push(...segment2);
} else if (leftBounderySegment1 === rightBounderySegment2) {
segment2.splice(segment2.length - 1, 1);
segment1.unshift(...segment2);
} else if (rightBounderySegment1 === leftBounderySegment2) {
segment2.splice(0, 1);
segment1.push(...segment2);
}
return (segment1)
}
console.log(reconstituteSegment(segmentsFromAtoM), "sorted From A to M");
console.log(reconstituteSegment(segmentsFromMtoA), "sorted From M to A");
console.log(reconstituteSegment(invalidSegments), "wrong input test");