這是我參與8月更文挑戰的第9天,活動詳情查看:8月更文挑戰」git
上一篇文章主要闡述了刪除任務與事物管理相關的指令開發github
本文將着重介紹上文沒講解完的部分writeRecord
方法,將記錄的事物自動輸出到配置的文件中json
演示過程當中發現了一個bug,趕忙修復一下數組
首先補齊打印事務耗時的邏輯markdown
thing
,包含兩個屬性
new Date(startTime)
轉換開始日期mmsToNormal
計算當前時間與開始時間的差值const { thing } = config
const s = new Date(thing.startTime)
console.log(`事務耗時:${thing.name} ${mmsToNormal(Date.now() - s)}`);
複製代碼
mmsToNormal
方法很是樸素,將一個毫秒錶示的時間換成天,時,分,秒
app
>>
,右移0位function mmsToNormal(mms) {
mms = (mms / 1000) >> 0
const day = (mms / (24 * 60 * 60)) >> 0
mms -= day * 24 * 60 * 60
const hour = (mms / (60 * 60)) >> 0
mms -= hour * 60 * 60
const minute = (mms / 60) >> 0
mms -= minute * 60
return `${day}天 ${hour}時 ${minute}分 ${mms}秒`
}
複製代碼
在結束當前事務和直接開始新的事務的時候都會打印這個任務的耗時,而後將其結果寫入到md中ide
開始新任務的邏輯以下:工具
console.log(`事務耗時:${thing.name} ${mmsToNormal(Date.now() - s)}`);
writeRecord(recordFilepath, task, thing.name, thing.startTime)
thing.name = name
thing.startTime = new Date().getTime()
writeFileSync(configPath, JSON.stringify(config))
複製代碼
下面開始介紹writeRecord
的實現,接收4個參數oop
function writeRecord(filePath, task, thing, startTime){
// ...code
}
複製代碼
經過getJSON
與getFileContent
方法協力將輸出目標文件轉爲json
post
將開始時間轉爲Date
對象,調用Date.prototype.format
方法獲取事務開始時間的日期
其中format
方法的邏輯來源與網上大神寫的正則
事務持續時間保留5位小數
const json = getJSON(getFileContent(filePath))
const date = new Date(startTime)
const title = date.format('yyyy-MM-dd')
const hours = ((Date.now() - date.getTime()) / 3600000).toFixed(5)
複製代碼
導出json使用的是outPutMarkdown
方法,默認導出結果不會帶時間
,例如
# 時間
## 任務名
* content
* 事務2
複製代碼
經過修改獲取的json,將content內容加上時間,加上時間後的輸出結果
# 時間
## 任務名
* content time
* 事務2 0.02
複製代碼
修改原數據content
加上time
的邏輯以下:
const things = json.reduce((pre, v) => {
const { tasks } = v
const things = tasks.map(v => v.things).flat(2)
return pre.concat(things)
}, [])
things.forEach(t => {
const { content, time } = t
t.content = `${content} ${time}`
})
複製代碼
下面開始核心邏輯
遍歷json
判斷事務對應的日期是否已經存在
不存在則爲當天的首個數據,直接向json對象中插入這個完整的對象便可
const dayIdx = json.findIndex(v => v.title === title)
if (dayIdx === -1) {
const item = {
title,
tasks: [
{
title: task,
things: [
{
content: `${thing} ${hours}`,
time: '0'
}
]
}
]
}
json.push(item)
return writeFileSync(filePath, outPutMarkdown(json, false))
}
複製代碼
若是不是當天首個事務,接着就判斷是不是一個新的任務
遍歷這一天數據中的每個任務,判斷任務名是否和當前的任務一致
dataItem
表示這一天的數據const dataItem = json[dayIdx]
const taskIdx = dataItem.tasks.findIndex(v => v.title === task)
// 新的任務
if (taskIdx === -1) {
dataItem.tasks.push({
title: task,
things: [
{
content: `${thing} ${hours}`,
time: '0'
}
]
})
return writeFileSync(filePath, outPutMarkdown(json, false))
}
複製代碼
最後就是直接將事務插入到舊的任務當中
const taskItem = dataItem.tasks[taskIdx]
taskItem.things.push({
content: `${thing} ${hours}`,
time: '0'
})
return writeFileSync(filePath, outPutMarkdown(json, false))
複製代碼
到此timc thing [option] [name]
指令基本開發完畢
--stop,-s
:結束當前事務因爲天天空閒時間有限,本文就先到這
若是讀者還感受意猶未盡,敬請期待後續更新,或持續關注一下倉庫的狀態
歡迎評論區提需求,交流探討
本系列會不斷的更新迭代,直至產品初代完成