首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将活动天数数组转换为可读字符串

将活动天数数组转换为可读字符串
EN

Stack Overflow用户
提问于 2022-10-19 09:05:51
回答 4查看 70关注 0票数 0

我需要转换一个布尔值数组,该数组指示存储是否在给定的一天内打开。

例如,

案例1:

代码语言:javascript
复制
Input data: [true, true, true, true, true, true, true]
Expected output: Every day

案例2:

代码语言:javascript
复制
Input data: [true, true, true, true, true, false, false]
Expected output: Mon-Fri

案例3:

代码语言:javascript
复制
Input data: [true, true, false, false, true, true, true]
Expected output: Mon-Tue, Fri-Sun

案例4:

代码语言:javascript
复制
Input data: [true, false, false, true, false, false, true]
Expected output: Mon, Thu, Sun

案例5:

代码语言:javascript
复制
Input data: [true, true, false, true, true, true, false]
Expected output: Mon-Tue, Thu-Sat

案例6:

代码语言:javascript
复制
Input data: [true, false, false, false, false, false, false]
Expected output: Only Monday

我想出了,但需要2-5例的帮助。

代码语言:javascript
复制
const daysLabels = [
  { label: "Monday", short: "Mon" },
  { label: "Tuesday", short: "Tue" },
  { label: "Wednesday", short: "Wed" },
  { label: "Thursday", short: "Thu" },
  { label: "Friday", short: "Fri" },
  { label: "Saturday", short: "Sat" },
  { label: "Sunday", short: "Sun" }
];

const getSchedule = ({ case: days }) => {
  let activeDays = [];
  for (let i = 0; i < [...days].length; i++) {
    const day = [...days][i];
    if (day) {
      activeDays.push({ ...daysLabels[i], value: day });
    }
  }

  if (activeDays.length === 7) {
    return "Every day";
  }

  if (activeDays.length === 1) {
    return `Only ${activeDays[0].label}`;
  }

  return "#TODO";
};

沙箱- 链接

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2022-10-19 11:45:23

您可以使用Array.reduce()创建日范围组以及正确的标签。

然后,我们使用一个Array.map()调用只返回每个范围的标签。

我已经添加了提到的6个测试用例,它们都应该通过。

代码语言:javascript
复制
const daysLabels = [
  { label: "Monday", short: "Mon" },
  { label: "Tuesday", short: "Tue" },
  { label: "Wednesday", short: "Wed" },
  { label: "Thursday", short: "Thu" },
  { label: "Friday", short: "Fri" },
  { label: "Saturday", short: "Sat" },
  { label: "Sunday", short: "Sun" }
];

function getDayRange(input) {
    // Deal with 7 days and 1 day only first...
    if (input.filter(active => active).length === 7) { 
        return 'Every day';
    } else if (input.filter(active => active).length === 1) { 
        return `Only ${daysLabels[input.findIndex(active => active)].label}`;
    }
    // 2 - 6 days active
    return input.reduce((acc, active, idx) => {
        if (active) {
            if (!acc.length || acc[acc.length - 1].end < (idx - 1) ) { 
                acc.push({ start: idx, end: idx, label: daysLabels[idx].short, startLabel: daysLabels[idx].short });
            } else {
                acc[acc.length - 1].end = idx;
                acc[acc.length - 1].label = acc[acc.length - 1].startLabel + '-' + daysLabels[idx].short; 
            }
        }
        return acc;
    }, []).map(r => r.label).join(', ');
}

const cases = [
    { input: [true, true, true, true, true, true, true], expected: 'Every day' },
    { input: [true, true, true, true, true, false, false], expected: 'Mon-Fri' },
    { input: [true, true, false, false, true, true, true], expected: 'Mon-Tue, Fri-Sun' },
    { input: [true, false, false, true, false, false, true], expected: 'Mon, Thu, Sun' },
    { input: [true, true, false, true, true, true, false], expected: 'Mon-Tue, Thu-Sat' },
    { input: [true, false, false, false, false, false, false], expected: 'Only Monday' },
]
console.log(`Case`, '\t', 'Pass', '\t', 'Output')
cases.forEach(({ input, expected }, idx) => {
    let output = getDayRange(input);
    console.log(`${idx + 1}`, '\t', output === expected, '\t', output)
})
代码语言:javascript
复制
.as-console-wrapper { max-height: 100% !important; }

票数 1
EN

Stack Overflow用户

发布于 2022-10-19 14:34:14

这是我的答案,这不是一个优化版本。

增加以下职能:-

代码语言:javascript
复制
function getWeekDuration(cases) {
  let index = 0;
  let weekDurationArray = [];

  for (let i = 0; i < cases.length; i++) {
    const day = cases[i];
    if (i === 0) {
      weekDurationArray[index] = [];
    }
    if (day) {
      weekDurationArray[index].push({ ...daysLabels[i],
        value: day
      });
    } else {
      if (weekDurationArray[index].length > 0) {
        index += 1;
        weekDurationArray[index] = [];
      }
    }

  }

  // remove empty arrays
  weekDurationArray = weekDurationArray.filter(item => item.length > 0);

  // get only first and last day of each week duration
  weekDurationArray = weekDurationArray.map(weekDuration => {
    // concate inner array into string
    if (weekDuration.length > 1) {
      return `${weekDuration[0].short}-${weekDuration[weekDuration.length - 1].short}`;
    }
    return weekDuration[0].short;
  });

  return weekDurationArray.join(', ');

}

添加从getSchedule return getWeekDuration(days);返回函数

票数 2
EN

Stack Overflow用户

发布于 2022-10-19 09:47:44

我为文本声明了一个映射数组,下面是示例代码,当函数只返回一天或每天的时候,您可以修改文本。

代码语言:javascript
复制
// for index mapping
let indexMapping = [
    "Mon",
    "Tue",
    "Wed",
    "Thu",
    "Fri",
    "Sat",
    "Sun"
];
function getWeeks(arr){
    let list = [];
    let indexes = [];
    let item = [];
    // get all indexes
    arr.forEach((result,index) => {
        if(result) indexes.push(index);
    });

    // push each text to list
    indexes.map(i => {
        if(!indexes.includes(i-1)){
            if(item.length == 1){
                list.push(item[0]);
                item = [];
            }
            item.push(indexMapping[i]);
        }
        else if(!indexes.includes(i+1)){
            item.push(indexMapping[i]);
            list.push(item.join("-"));
            item = [];
        }
    });

    // if indexes only has one item
    if(item.length == 1){
        list.push(item[0]);
    }
    return list;
}

// for test
let testArr2 = [true, true, true, true, true, false, false];
let testArr3 = [true, true, false, false, true, true, true];
let testArr4 = [true, false, false, true, false, false, true];
let testArr5 = [true, true, false, true, true, true, false];
getWeeks(testArr2); // output will be like ['Mon-Fri']
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74122656

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档