blob: e02c0a56eb563ed373f9ab445e76088ee3873827 [file] [log] [blame]
Adrià Vilanova Martínez2d9be8d2022-12-28 00:50:14 +01001import GapModel from './Gap.js';
2import MessageModel from './Message.js';
3
4export default class ThreadModel {
5 /**
6 * The following code is based on logic written by Googlers in the TW frontend
7 * and thus is not included as part of the MIT license.
8 */
9 static mergeMessageOrGaps(a, b) {
10 if (a.length == 0 || b.length == 0)
11 return a.length > 0 ? a : b.length > 0 ? b : [];
12
13 let e = [];
14 for (let g = 0, k = 0, m = 0, q = a[g], u = b[k];
15 g < a.length && k < b.length;) {
16 if (q instanceof MessageModel && u instanceof MessageModel) {
17 if (q.getCreatedMicroseconds() === u.getCreatedMicroseconds()) {
18 u.mergeCommentOrGapViews(q);
19 }
20
21 e.push(u);
22
23 if (g === a.length - 1 || k === b.length - 1) {
24 for (; ++g < a.length;) e.push(a[g]);
25 for (; ++k < b.length;) e.push(b[k]);
26 break;
27 }
28
29 q = a[++g];
30 u = b[++k];
31 } else {
32 if (u instanceof GapModel) {
33 let z;
34 for (z = q instanceof MessageModel ? q.getCreatedMicroseconds() :
35 q.getEndTimestamp();
36 z < u.getEndTimestamp();) {
37 e.push(q);
38 m += q instanceof GapModel ? q.getCount() : 1;
39 if (g === a.length - 1) break;
40 q = a[++g];
41 z = q instanceof MessageModel ? q.getCreatedMicroseconds() :
42 q.getEndTimestamp();
43 }
44 if (q instanceof GapModel && u.getCount() - m > 0 &&
45 z >= u.getEndTimestamp()) {
46 const gm = new GapModel();
47 gm.setCount(u.getCount() - m);
48 gm.setStartMicroseconds('' + q.getStartTimestamp());
49 gm.setEndMicroseconds('' + u.getEndTimestamp());
50 gm.setParentId(u.getParentId());
51 e.push(gm);
52 m = u.getCount() - m;
53 } else {
54 m = 0;
55 }
56 if (k === b.length - 1) break;
57 u = b[++k];
58 }
59 if (q instanceof GapModel) {
60 let z;
61 for (z = u instanceof MessageModel ? u.getCreatedMicroseconds() :
62 u.getEndTimestamp();
63 z < q.getEndTimestamp();) {
64 e.push(u);
65 m += u instanceof GapModel ? u.getCount() : 1;
66 if (k === b.length - 1) break;
67 u = b[++k];
68 z = u instanceof MessageModel ? u.getCreatedMicroseconds() :
69 u.getEndTimestamp();
70 }
71 if (u instanceof GapModel && q.getCount() - m > 0 &&
72 z >= q.getEndTimestamp()) {
73 const gm = new GapModel();
74 gm.setCount(q.getCount() - m);
75 gm.setStartMicroseconds('' + u.getStartTimestamp());
76 gm.setEndMicroseconds('' + q.getEndTimestamp());
77 gm.setParentId(q.getParentId());
78 e.push(gm);
79 m = q.getCount() - m;
80 } else {
81 m = 0;
82 }
83 if (g === a.length - 1) break;
84 q = a[++g];
85 }
86 }
87 }
88 return e;
89 }
90
91 static mergeMessageOrGapsMultiarray(mogsModels) {
92 if (mogsModels.length < 1) return [];
93 let mergeResult = mogsModels[0];
94 for (let i = 1; i < mogsModels.length; ++i) {
95 mergeResult = ThreadModel.mergeMessageOrGaps(mergeResult, mogsModels[i]);
96 }
97 return mergeResult;
98 }
99}