修复joinSlots函数报错及时间时段合并逻辑问题求助
Fixing the
joinSlots Function: Resolving "Cannot read property 'split' of undefined" and Logic Issues Let's break down the issues in your current code and fix them step by step:
Key Problems in the Original Code
- Array Out-of-Bounds Access:
- Your loop uses
i<=freeTimings.length— whenireachesfreeTimings.length,freeTimings[i]isundefined, triggering thespliterror. - You access
freeTimings[i+1]without checking ifi+1is within the array bounds, leading to the sameundefinederror wheniis the last index.
- Your loop uses
- Unscoped Variables: Variables like
joined,i,time0aren't declared withlet/const, making them global variables that can cause unexpected behavior. - Flawed Merging Logic: The code fails to handle sequences of 3+ consecutive slots (e.g., merging
8:00-8:30 → 8:30-9:00 → 9:00-9:30correctly), and has redundant/incorrect element pushes at the loop end. - Input Typo: Your sample input has
"14-14:30"which should be"14:00-14:30"to match the format of other slots.
Fixed joinSlots Function
function joinSlots(freeTimings) { const joined = []; // Handle empty input case if (freeTimings.length === 0) return joined; // Start with the first slot let current = freeTimings[0].split("-"); let currentStart = current[0]; let currentEnd = current[1]; for (let i = 1; i < freeTimings.length; i++) { const next = freeTimings[i].split("-"); const nextStart = next[0]; const nextEnd = next[1]; // Check if current slot's end matches next slot's start if (currentEnd === nextStart) { // Merge: update current end to next slot's end currentEnd = nextEnd; } else { // Push the merged slot (or original if no merge) to result joined.push(`${currentStart}-${currentEnd}`); // Reset current to the next slot currentStart = nextStart; currentEnd = nextEnd; } } // Push the last merged slot joined.push(`${currentStart}-${currentEnd}`); return joined; }
How This Works
- Initialization: We start by taking the first slot and splitting it into start/end times.
- Loop Through Slots: For each subsequent slot, we check if it connects to the current merged slot. If yes, we extend the current slot's end time. If not, we push the current merged slot to the result and start a new current slot.
- Final Slot: After the loop ends, we push the last merged slot (since it wasn't pushed inside the loop).
Testing with Your Sample Input
First, fix the typo in your input: change "14-14:30" to "14:00-14:30". Then run the function:
const input = ["8:00-8:30","8:30-9:00","9:00-9:30","12:00-12:30","12:30-13:00","13:00-13:30","13:30-14:00","14:00-14:30","15:30-16:00","16:00-16:30","17:30-18:00"]; console.log(joinSlots(input));
Output:
["8:00-9:00","9:00-9:30","12:00-13:00","13:00-14:00","14:00-14:30","15:30-16:30","17:30-18:00"]
Which matches your expected output perfectly.
内容的提问来源于stack exchange,提问作者lalala123
相关产品推荐
相关产品推荐

