2 回答
TA贡献1833条经验 获得超4个赞
好吧,你的代码想起来很简单,但是很长!!
如果你想要示例,我有 javascript vanilla 代码:
function parse (value) {
var list = (value + "").trim().split("-").reverse();
if (list != 0 && list.every(x => !isNaN(x))) {
return {
year: parseInt(list[0]),
month: parseInt(list[1]) || undefined,
day: parseInt(list[2]) || undefined,
}
}
return undefined;
}
// below for testing
[
"08-11-2020",
"11-2020",
"2020",
""
].forEach(x => {console.log(x, parse(x))});
不幸的是,我没有任何实现打字稿代码的经验,但上面的 JavaScript 代码可能会对你有所帮助。实际上我缩短了代码,因为 javascript 带来的优点(缺点?),也许转换为 typescript 不会有太大区别!
附加打字稿代码:
在 typescriptlang.org 上
type NgbDateStruct = {
year?: number;
month?: number;
day?: number;
};
function parse (value: string) : NgbDateStruct {
var list = (value + "").trim().split("-").reverse().map(x => x || -1).map(Number);
if (list.length > 0 && list.every(x => !isNaN(Number(x))) && list.every(x => x > -1)) {
return {
year: list[0] || undefined,
month: list[1] || undefined,
day: list[2] || undefined,
}
}
return undefined as any;
}
// below for testing
[
"08-11-2020",
"11-2020",
"2020",
"",
"nothing"
].forEach(x => {console.log(x, parse(x))});
TA贡献1757条经验 获得超7个赞
一种选择是使用正则表达式来匹配数字,可能会散布-s:
const getDateObj = value => {
const match = value.match(/(^\d+)(?:-(\d+)(?:-(\d+))?)?$/);
if (!match) return undefined;
const [, first, second, third] = match.filter(group => group !== undefined).map(Number);
if (third) {
// All were matched
return {
year: third,
month: second,
day: first
};
} else if (second) {
// Only first two were matched
return {
year: second,
month: first
}
}
return {
year: first
}
};
console.log(getDateObj('31-12-2000'));
console.log(getDateObj('12-2000'));
console.log(getDateObj('2000'));
console.log(getDateObj('incorrect'));
在 TypeScript 语法中:
type NgbDateStruct = {
year: number;
month?: number;
day?: number;
};
const getDateObj = (value: string): NgbDateStruct | undefined => {
const match = value.match(/(^\d+)(?:-(\d+)(?:-(\d+))?)?$/);
if (!match) return undefined;
const [, first, second, third] = match.filter(group => group !== undefined).map(Number);
if (third) {
// All were matched
return {
year: third,
month: second,
day: first,
};
}
if (second) {
// Only first two were matched
return {
year: second,
month: first,
};
}
return {
year: first,
};
};
添加回答
举报