简体   繁体   中英

javascript output time interval

I'm working to automate a google sheet to google calendar, but I'm stuck.

I have an array of strings that correspond to hours

ex: time = [8, 9, 10, 2, 3, 4]

and want to an output a string

ex: range = "8-11, 2-5"

I need to write this in google app script, any suggestions?

I'm new to google app script and having a hard time writing the function. My initial process was to convert the array of strings to military time integers, and create two for loops, but I'm sure there is a more efficient way to do this.

Thanks for the help!

This is my current code:

 var time = [8, 9, 10, 2, 3, 4] // if (currentTime == 13) {currentTime -= 12;} function timeRange(cellInput, hourList) { var start = parseInt(hourList[0]); for (var i = 1; i < hourList.length; ++i) { if (hourList[i] == start + i) { var end = parseInt(hourList[i]); } else { cellInput.setValue(start + " - " + (end + 1)); } } } function soloTime(cellInput, hour) { //convert hour string to hour var hour = parseInt(hour) var start = hour var end = hour + 1 cellInput.setValue(start + "-" + end); }

You could check the predecessor and collect the ranges.

 var time = [8, 9, 10, 2, 3, 4, 11, 12, 1], range = time .reduce((r, t, i, a) => { if (a[i - 1] % 12 + 1 === t) { r[r.length - 1][1] = t; } else { r.push([t]); } return r; }, []) .map(a => a.join('-')) .join(', '); console.log(range);

Is this what you are looking for?

 const timeToRange = (arr) => { const mins = arr .filter((x, i, arr) => x !== arr[i - 1] + 1); const maxs = arr .filter((x, i, arr) => x !== arr[i + 1] - 1) .map(x => x + 1); return mins .map((x, i) => [x, maxs[i]].join('-')) .join(', '); }; console.log( timeToRange([8, 9, 10, 2, 3, 4]) );

You could keep the start of each range, then iterate until the current value does not fit to the previous, then take the previous and the start to create a range, collect them in an array, and that's it.

 const result = [];

 let start = time[0];
 let previous = time[0];

 // Start at the second position, and go over the arrays length by one, so tgat the last range gets added too
 for(const value of time.slice(1).concat(Infinity)) {
   // if the range isn't continuous (12 to 1 is continuous)
   if((value - previous) % 12 !== 1) {
     // Add the previous range, start the new range here
     result.push(start + "-" + previous);
     start = value;
   }
   previous = value;
}

console.log(result.join(", "));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM