我正在为基于语音的应用程序提取日期。我想知道如何检查日期,并且还可以在一个函数中像用户要求的那样添加标志,然后要求更高的日期。现在,我正在使用类似的功能,但是如果有人可以指导我做到这一点,那将是很棒的。我的代码如下,
checkedDateFlag,checkedDate如何使该函数合而为一,这样我就可以得到正确的日期并获得标记(true)
let ent = [{
entity: 'sys-number',
location: [23, 25],
value: '12',
confidence: 1,
metadata: {
numeric_value: 1
}
},
{
entity: 'sys-date',
location: [23, 40],
value: '2017-02-16',
confidence: 1,
metadata: {
calendar_type: 'GREGORIAN',
timezone: 'GMT'
}
},
{
entity: 'sys-number',
location: [36, 40],
value: '2018',
confidence: 1,
metadata: {
numeric_value: 2018
}
},
{
entity: 'sys-date',
location: [49, 52],
value: '2030-12-17',
confidence: 1,
metadata: {
calendar_type: 'GREGORIAN',
timezone: 'GMT'
}
}
];
const dateChecker = (filteredDates, currentDate) => {
// This function checking date higher than todays date and replace higher date with current date.
return filteredDates.map(f => {
let fd = new Date(f);
if(fd > currentDate) {
return currentDate;
} else {
return fd;
}
})
}
const dateCheckerFlag = (filteredDates, currentDate) => {
// This function return true if date is higher and I can check it later and create response saying you have provided higher date than today. I can only issue statement till today and then issue the statement
for (let f of filteredDates) {
let fd = new Date(f);
if(fd > currentDate) {
return true
} else {
return false;
}
}
let filteredDates = ent.filter(f => {
if (f.entity === 'sys-date') {
return f.value
}
}).map(f => f.value);
let checkedDateFlag = helper.dateCheckerFlag(filteredDates, currentDate);
let checkedDate = helper.dateChecker(filteredDates, currentDate);
答案 0 :(得分:0)
我建议不要将这两个功能结合使用。尽管它们似乎做相同的事情,但是它们具有完全不同的输出签名(布尔值与数组)。
如果您认为他们有很多重复的代码。也许以下是一种方法。我将保留合并和单独的职能。但强烈建议使用另一种。
var ent = [{
entity: 'sys-number',
location: [23, 25],
value: '12',
confidence: 1,
metadata: {
numeric_value: 1
}
},
{
entity: 'sys-date',
location: [23, 40],
value: '2017-02-16',
confidence: 1,
metadata: {
calendar_type: 'GREGORIAN',
timezone: 'GMT'
}
},
{
entity: 'sys-number',
location: [36, 40],
value: '2018',
confidence: 1,
metadata: {
numeric_value: 2018
}
},
{
entity: 'sys-date',
location: [49, 52],
value: '2030-12-17',
confidence: 1,
metadata: {
calendar_type: 'GREGORIAN',
timezone: 'GMT'
}
}
];
// we convert to date format here itself less
var filteredDates = ent.filter(f => (f.entity === 'sys-date')).map(f => new Date(f.value));
var getCurrentDate = ()=>new Date();
var checkIfOlder = (f/*:dateformat*/) =>(f > getCurrentDate());
var replaceFutureDates = function(f/*:dateformat*/) {
return (checkIfOlder(f)) ? getCurrentDate() : f;
}
/* cleaner IMHO*/
var checkedDateFlag = filteredDates.every(checkIfOlder);
var checkedDate = filteredDates.map(replaceFutureDates);
/* combined function but very confusing output signature
var dateMapper = (dates, onlyCheck)=> {
if(onlyCheck) {
return dates.every(checkIfOlder);
}
return dates.map(replaceFutureDates);
}
var checkedDateFlag = dateMapper(filteredDates)
var checkedDate =dateMapper(filteredDates, true)
*/