Packets arrive in any order
Packets can take different paths, so they arrive late, twice or out of order. TCP numbers every byte with a sequence number; the receiver delivers bytes only in order and ACKs the next byte it's still waiting for — which tells the sender what to resend.
Reassembly
function reassemble(segments) {
const sorted = [...segments].sort((a, b) => a.seq - b.seq);
let next = 0; // the next byte we're waiting for
let data = "";
for (const s of sorted) {
if (s.seq + s.data.length <= next) continue; // all old: a duplicate
if (s.seq > next) break; // a gap: wait for the missing bytes
data += s.data.slice(next - s.seq); // keep only the new part of an overlap
next = s.seq + s.data.length;
}
return { data, ack: next };
}