Skip to content

Commit

Permalink
fix: dayjs.diff improve performance (#2244)
Browse files Browse the repository at this point in the history
* improve: diff performance

* refactor: switch refactor

---------

Co-authored-by: 李权威 <[email protected]>
  • Loading branch information
Qquanwei and 李权威 authored Jun 22, 2023
1 parent 548b217 commit 33c80e1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 12 deletions.
1 change: 1 addition & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ root = true
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_size = 2
44 changes: 32 additions & 12 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -319,18 +319,38 @@ class Dayjs {
const that = dayjs(input)
const zoneDelta = (that.utcOffset() - this.utcOffset()) * C.MILLISECONDS_A_MINUTE
const diff = this - that
let result = Utils.m(this, that)

result = {
[C.Y]: result / 12,
[C.M]: result,
[C.Q]: result / 3,
[C.W]: (diff - zoneDelta) / C.MILLISECONDS_A_WEEK,
[C.D]: (diff - zoneDelta) / C.MILLISECONDS_A_DAY,
[C.H]: diff / C.MILLISECONDS_A_HOUR,
[C.MIN]: diff / C.MILLISECONDS_A_MINUTE,
[C.S]: diff / C.MILLISECONDS_A_SECOND
}[unit] || diff // milliseconds
const getMonth = () => Utils.m(this, that)

let result
switch (unit) {
case C.Y:
result = getMonth() / 12
break
case C.M:
result = getMonth()
break
case C.Q:
result = getMonth() / 3
break
case C.W:
result = (diff - zoneDelta) / C.MILLISECONDS_A_WEEK
break
case C.D:
result = (diff - zoneDelta) / C.MILLISECONDS_A_DAY
break
case C.H:
result = diff / C.MILLISECONDS_A_HOUR
break
case C.MIN:
result = diff / C.MILLISECONDS_A_MINUTE
break
case C.S:
result = diff / C.MILLISECONDS_A_SECOND
break
default:
result = diff // milliseconds
break
}

return float ? result : Utils.a(result)
}
Expand Down

0 comments on commit 33c80e1

Please sign in to comment.