javascript输出时间间隔

问题描述 投票:-2回答:3

我正在努力将谷歌表自动化到谷歌日历,但我被卡住了。

我有一个对应于小时的字符串数组

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

并希望输出一个字符串

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

我需要在谷歌应用程序脚本中写这个,有什么建议吗?

我是谷歌应用程序脚本的新手,并且很难编写该功能。我的初始过程是将字符串数组转换为军事时间整数,并创建两个for循环,但我确信有更有效的方法来执行此操作。

谢谢您的帮助!

这是我目前的代码:

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);
}
javascript intervals appscript
3个回答
0
投票

您可以检查前一个并收集范围。

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);

0
投票

这是你想要的?

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])
);

0
投票

您可以保持每个范围的开始,然后迭代直到当前值不适合前一个,然后采用前一个和开始创建一个范围,将它们收集在一个数组中,就是这样。

 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(", "));
© www.soinside.com 2019 - 2024. All rights reserved.