Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dayjs.diff improve performance #2244

Merged
merged 2 commits into from
Jun 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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