We have UI editor from which user can select any number of days.
If the user selects continuous days, those are represented by dashes or hyphens, but if non-continuous days are selected then those are represented by commas..
eg - String - M,W,F - Non Continuous days.
eg - String - M-F - User selected continuous 5 days.

从后台的Angular 来看,如果我们得到一些类似M-Tu,Th,Sa-SuM-W,F-Su等组合的字符串,如何从中找到有效的天数?

我已经创建了一个常量数组,用于循环或判断值

DAYS: ['M', 'Tu', 'W', 'Th', 'F', 'Sa', 'Su']
let userInput = 'M-Tu,Th,Sa-Su' or 'M-W,F-Su'

SomeMethod(userInput) {
  let validDays = [];
  const commaSeperatedDays = userInput?.split(',');
  const contDaysFromCommaSeparatedDays = commaSeperatedDays.map(x => 
  x.split('-'));
  let indDays = validDays.push(contDaysFromCommaSeparatedDays.map(x => 
  findIndividualDays(x)));

  //When only continuous days are there
  const ContinuousDays = days?.split('-');
}

function findIndividualDays(days) {
//getting confused here how to handle cases - if there is any inbuilt library ?
        if (days.length === 1) {
            return days[0];
        }
        let indDays = [];
        const startIndex = constants.DAYS.indexOf(days[0]);
        const endIndex = constants.DAYS.indexOf(days[1]);
        for (let index = startIndex; index <= endIndex; index++) {
            const element = constants.DAYS[index];
            indDays.push(element);
        }
        return { ...indDays };
    }

推荐答案

只是为了好玩,我喜欢使用生成函数

const DAYS = ['M', 'Tu', 'W', 'Th', 'F', 'Sa', 'Su'];

function* enumerateDays(inputString){
    for(const value of inputString.split(',')){
    const [start,end] = value.split('-');
    if(end)
        for(index = DAYS.indexOf(start), endIndex = DAYS.indexOf(end) ;index <= endIndex;index++)
            yield DAYS[index];
    else
        yield start;
  }
}



//test cases
const test = (inputString) => console.log(...enumerateDays(inputString));
test( 'M-Tu,Th,Sa-Su');
test('M-W,F-Su');
test('M-Su');
test('M,Tu,Th-Sa');

Javascript相关问答推荐

无法将nPM simplex-noise包导入在JS项目中工作

传递一个大对象以在Express布局中呈现

django无法解析余数:[0] from carray[0]'

React Code不在装载上渲染数据,但在渲染上工作

Google maps API通过API返回ZERO_RESULTS,以获得方向请求,但适用于Google maps

如何通过将实例方法的名称传递给具有正确类型的参数的继承方法来调用实例方法?

如何从HTML对话框中检索单选项组的值?

WP Bootstrap NavWaker:下拉菜单一次打开所有下拉菜单

查询参数中的JAVASCRIPT/REACT中的括号

如何在箭头函数中引入or子句?

在开发期间,Web浏览器如何运行&qot;.jsx&qot;文件?

无法设置RazorPay订阅API项目价格

如何在脚本编译后直接将RxJ模块导入浏览器(无需Angel、webpack、LiteServer)

有没有办法更改Chart.js 3.x.x中主要刻度的字体?

MongoDB通过数字或字符串过滤列表

在单击按钮时生成多个表单时的处理状态

如何处理不带参数的redux thunk payloadCreator回调函数?

JSON Web令牌(JWT)错误:RSA密钥对的签名无效

如何动态呈现适合未知屏幕大小的最大数量的表行?苗条的

Playwright:ReferenceError:browserContext未定义