Why does this interval merge function duplicate the last range?

I’m merging sorted half-open intervals, but some inputs repeat the final range in the output. I expected adjacent ranges to merge too. What logic bug am I missing?

function merge(intervals) {
  const out = [];
  for (const cur of intervals) {
    const last = out[out.length - 1];
    if (!last || cur[0] > last[1]) out.push(cur);
    if (cur[0] <= last?.[1]) {
      last[1] = Math.max(last[1], cur[1]);
      out.push(last);
    }
  }
  return out;
}

Yoshiii :slightly_smiling_face:

Your merge branch is pushing twice: once for a new interval and again after extending last, so the same array reference gets appended again.

WaffleFries