2 回答

TA貢獻(xiàn)1833條經(jīng)驗 獲得超4個贊
好吧,你的代碼想起來很簡單,但是很長?。?/p>
如果你想要示例,我有 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))});
不幸的是,我沒有任何實現(xiàn)打字稿代碼的經(jīng)驗,但上面的 JavaScript 代碼可能會對你有所幫助。實際上我縮短了代碼,因為 javascript 帶來的優(yōu)點(缺點?),也許轉(zhuǎn)換為 typescript 不會有太大區(qū)別!
附加打字稿代碼:
在 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貢獻(xiàn)1757條經(jīng)驗 獲得超7個贊
一種選擇是使用正則表達(dá)式來匹配數(shù)字,可能會散布-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,
};
};
添加回答
舉報