From 84597c9c99bd8c01879dacc1e744913ac523ac6e Mon Sep 17 00:00:00 2001 From: iamkun Date: Mon, 21 May 2018 10:35:15 +0800 Subject: [PATCH] fix: instance locale change should be immutable --- src/index.js | 6 +++++- test/locale.test.js | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/index.js b/src/index.js index 37f398079..9c72d27d7 100644 --- a/src/index.js +++ b/src/index.js @@ -375,11 +375,15 @@ class Dayjs { return Ls[this.$L] } - locale(preset, object) { + $setLocale(preset, object) { // private set locale mutate instance this.$L = parseLocale(preset, object, true) return this } + locale(preset, object) { + return this.clone().$setLocale(preset, object) + } + clone() { return wrapper(this.toDate(), this) } diff --git a/test/locale.test.js b/test/locale.test.js index 88d34e7cf..5570a062c 100644 --- a/test/locale.test.js +++ b/test/locale.test.js @@ -49,6 +49,20 @@ it('set global locale', () => { .toBe('Saturday 28, April') }) +it('immutable instance locale', () => { + dayjs.locale('en') + const origin = dayjs('2018-4-28') + expect(origin.format(format)) + .toBe('Saturday 28, April') + expect(origin.locale('es').format(format)) + .toBe('Sábado 28, Abril') + const changed = origin.locale('es') + expect(changed.format(format)) + .toBe('Sábado 28, Abril') + expect(origin.format(format)) + .toBe('Saturday 28, April') +}) + it('User custom locale', () => { expect(dayjs('2018-4-28') .locale('xx', {