需要幫助正在建立返回最早日期值的方法
P粉521013123
P粉521013123 2024-04-04 19:51:19
0
1
1362

我正在為我接管的遺留程式碼庫重構一個方法。 此方法接受預測日期的物件。 當預測日期在 30、40 或 60 以內時,應使用 getTime() 方法進行轉換,以返回最早的時間。

目前傳回它接收的物件的最早日期,問題是它只與2 個日期進行比較,它會傳回星形日期,並且只傳回結束日期中的2 個值之一,而不是比較所有3 個和傳回最低的.getTime() 值

下面是傳回最早日期的方法

const getEarliestRunout = (runout_dates = {}, dm1_type = '') => {
     try{
        const cur_year = new Date().getFullYear();

        const non_priority_sticker = dm1_type == cur_year + 1 || dm1_type == cur_year ? 'dm1' : 'dm2';
    
        return Object.entries(runout_dates).reduce((earliest,obj) => {            
            const key = obj[0].split('_')[0];

            const value = obj[1];
            
            if(value[`under_${env.STICKER_THRESH[0]}`] && key != non_priority_sticker) {
                return new Date(value[`under_${env.STICKER_THRESH[0]}`]).getTime() < earliest.val ? {val: new Date(value[`under_${env.STICKER_THRESH[0]}`]).getTime(), date: value[`under_${env.STICKER_THRESH[0]}`]} : {...earliest}
            }
            return earliest
        },{val: Infinity, date:''})
    }catch(e){
        console.error(`ERROR :: util.getEarliestRunout: ${e} - ${new Date()}`);
        return {val: Infinity, date: ''}
    }
}

下面是用來呼叫正在使用的方法的變數

const earliest_runout = getEarliestRunout({
 dm1_runouts: value.dm1_type == priority_sticker ? priorityRunouts : nonPriorityRunouts,
 dm2_runouts: value.dm2_type == priority_sticker ? priorityRunouts : nonPriorityRunouts,
 star_runouts: starRunouts
},value.dm1_type);

我期望該方法能夠比較所有日期,但它只比較 2。我很確定這就是我呼叫該方法的方式,但我不確定。我正在尋求進一步解決這個問題,因為我對如何獲得我正在尋找的結果感到困惑。

我確信我可以將其改寫得更清楚,但只是重申一下。此方法接受日期值(在我的用例中只有 3 個日期)並使用 Math.min 和 getTime() 傳回最早的日期。我收到的結果是它傳回所有日期值,但僅將星號值與 dm1_runout 或 dm2_runout 中的一個進行比較。它在比較中保持一致,只返回其中之一,但不會同時返回兩者。

P粉521013123
P粉521013123

全部回覆(1)
P粉949267121

我解決了我的問題的答案。我創建了一個日期數組,透過Math.min 方法運行每個方法,並將每個值推入日期數組,然後對數組進行排序,以使用空字串過濾NaN,並僅返回Math.min 中與每個循環匹配的最小值通過每個物件的數組。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!