这是我参与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
:结束当前事务因为天天空闲时间有限,本文就先到这
若是读者还感受意犹未尽,敬请期待后续更新,或持续关注一下仓库的状态
欢迎评论区提需求,交流探讨
本系列会不断的更新迭代,直至产品初代完成