我试图确保对象中输入的日期顺序符合逻辑顺序。这是我的代码:
function checkDates(pet) {
const dates = [
pet.birthDate,
pet.saleDate,
pet.acquisitionDate,
pet.deathDate
].filter( (date) => {
// filter out undefined items
return date;
});
// list of dates in their chronological order
const sortedDates = dates.slice(0).sort();
const inOrder = dates.every( (date, i) => {
// check to make sure entered date is the same as the chronological date
return date === sortedDates[i];
});
if (!inOrder) {
throw new ValidationError('The dates are in an illogical order');
}
}
问题是 saleDate 和 AcquisitionDate 不需要按照该顺序(如日期数组中定义) - 它们只需要大于birthDate并小于deathDate即可。不同的日期不是必需的,例如,通过我的外观传递的宠物对象如下所示:
const pet = {
name: "Sam",
birthDate: "2017-01-01",
acquisitionDate: "2017-02-01",
saleDate: "2017-03-01"
}
进一步说明:如果存在,出生日期必须始终排在第一位,死亡日期必须始终排在最后。出售和收购必须在出生日期和死亡日期之间(如果存在),否则,无论出售发生在收购之前还是反之亦然。
最佳答案
您走在正确的道路上,但不一定需要排序:
function checkDates(pet) {
const dates = [
pet.birthDate,
pet.saleDate,
pet.acquisitionDate,
pet.deathDate
].filter(date => date);
const inOrder =
(pet.birthDate ? dates.every(date => date >= pet.birthDate) : true) &&
(pet.deathDate ? dates.every(date => date <= pet.deathDate) : true)
if (!inOrder) {
throw new ValidationError('The dates are in an illogical order');
}
}
关于javascript - 检查对象中日期的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46697000/