Skip to content

Commit 84597c9

Browse files
committed
fix: instance locale change should be immutable
1 parent 1a7840d commit 84597c9

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/index.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -375,11 +375,15 @@ class Dayjs {
375375
return Ls[this.$L]
376376
}
377377

378-
locale(preset, object) {
378+
$setLocale(preset, object) { // private set locale mutate instance
379379
this.$L = parseLocale(preset, object, true)
380380
return this
381381
}
382382

383+
locale(preset, object) {
384+
return this.clone().$setLocale(preset, object)
385+
}
386+
383387
clone() {
384388
return wrapper(this.toDate(), this)
385389
}

test/locale.test.js

+14
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,20 @@ it('set global locale', () => {
4949
.toBe('Saturday 28, April')
5050
})
5151

52+
it('immutable instance locale', () => {
53+
dayjs.locale('en')
54+
const origin = dayjs('2018-4-28')
55+
expect(origin.format(format))
56+
.toBe('Saturday 28, April')
57+
expect(origin.locale('es').format(format))
58+
.toBe('Sábado 28, Abril')
59+
const changed = origin.locale('es')
60+
expect(changed.format(format))
61+
.toBe('Sábado 28, Abril')
62+
expect(origin.format(format))
63+
.toBe('Saturday 28, April')
64+
})
65+
5266
it('User custom locale', () => {
5367
expect(dayjs('2018-4-28')
5468
.locale('xx', {

0 commit comments

Comments
 (0)