我试图确保在对象中输入的日期顺序符合逻辑顺序。这是我的代码:
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"
}进一步澄清:如果存在,birthDate必须总是第一位的,而deathDate必须始终是最后一位。销售和收购必须在出生和死亡日期之间(如果他们在场),否则,出售是在收购之前还是反之亦然。
发布于 2017-10-11 20:38:14
您在正确的路径上,但不一定需要排序:
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');
}
}发布于 2017-10-11 20:42:17
您只需迭代给定的数组,而不进行排序,因为所有日期都必须按顺序排列。
function check({ birthDate, acquisitionDate, saleDate, deathDate }) {
return [birthDate, acquisitionDate, saleDate, deathDate]
.filter(Boolean)
.every((a, i, aa) => !i || aa[i - 1] <= a);
}
console.log(check({ name: "Sam", birthDate: "2017-01-01", acquisitionDate: "2017-02-01", saleDate: "2017-03-01" }));
console.log(check({ name: "Sam", birthDate: "2018-01-01", acquisitionDate: "2017-02-01", saleDate: "2017-03-01" }));
发布于 2017-10-11 20:43:15
您是说,saleDate和acquisitionDate的顺序并不重要--它们只需要高于birthDate而低于deathDate,在这种情况下,您可以简化您的函数,只执行以下四项检查:
function checkDates(pet) {
var birthDate = new Date(pet.birthDate);
var saleDate = new Date(pet.saleDate);
var acquisitionDate = new Date(pet.acquisitionDate);
var deathDate = pet.deathDate ? new Date(pet.deathDate) : Infinity;
var inOrder = (birthDate < saleDate) && (birthDate < acquisitionDate) && (saleDate < deathDate) && (acquisitionDate < deathDate);
if (!inOrder) {
throw new ValidationError('The dates are in an illogical order');
}
}不需要使用array,不需要排序和循环操作,它实际上是无用的。
演示:
function checkDates(pet) {
var birthDate = new Date(pet.birthDate);
var saleDate = new Date(pet.saleDate);
var acquisitionDate = new Date(pet.acquisitionDate);
var deathDate = pet.deathDate ? new Date(pet.deathDate) : Infinity;
var inOrder = (birthDate < saleDate) && (birthDate < acquisitionDate) && (saleDate < deathDate) && (acquisitionDate < deathDate);
if (!inOrder) {
throw new ValidationError('The dates are in an illogical order');
}
}
console.log(checkDates({
name: "Sam",
birthDate: "2018-01-01",
acquisitionDate: "2017-02-01",
saleDate: "2017-03-01"
}));
https://stackoverflow.com/questions/46697000
复制相似问题