]> git.ipfire.org Git - thirdparty/moment.git/commitdiff
Construct immutable Durations
authorLucas Sanders <butterflyhug@google.com>
Sun, 30 Oct 2016 18:27:57 +0000 (14:27 -0400)
committerLucas Sanders <butterflyhug@google.com>
Wed, 22 Mar 2017 11:00:18 +0000 (07:00 -0400)
src/lib/duration/constructor.js
src/lib/duration/create.js

index 578ba34f617ec7d2994dd2de8617b9926b3bf2f0..856375655d2b2671bdb4f51981cbaaff2db02a14 100644 (file)
@@ -2,6 +2,7 @@ import { normalizeObjectUnits } from '../units/aliases';
 import { getLocale } from '../locale/locales';
 import { bubble } from './bubble';
 import isDurationValid from './valid';
+import extend from '../utils/extend';
 
 export function Duration (duration) {
     var normalizedInput = normalizeObjectUnits(duration),
@@ -15,6 +16,11 @@ export function Duration (duration) {
         seconds = normalizedInput.second || 0,
         milliseconds = normalizedInput.millisecond || 0;
 
+    if (isDuration(duration)) {
+        copyDuration(this, duration);
+        return;
+    }
+
     this._isValid = isDurationValid(normalizedInput);
 
     // representation for dateAddRemove
@@ -26,7 +32,7 @@ export function Duration (duration) {
     // day when working around DST, we need to store them separately
     this._days = +days +
         weeks * 7;
-    // It is impossible translate months into days without knowing
+    // It is impossible to translate months into days without knowing
     // which months you are are talking about, so we have to store
     // it separately.
     this._months = +months +
@@ -41,3 +47,12 @@ export function Duration (duration) {
 export function isDuration (obj) {
     return obj instanceof Duration;
 }
+
+function copyDuration(to, from) {
+    to._isValid = from._isValid;
+    to._milliseconds = from._milliseconds;
+    to._days = from._days;
+    to._months = from._months;
+    to._data = extend({}, from._data);
+    to._locale = from._locale;
+}
index 8f435015f41893b7bb549315d00ddd17cea69f90..ef9707221ecf04233f02feb83d0abc30a9d2726f 100644 (file)
@@ -25,11 +25,7 @@ export function createDuration (input, key) {
         diffRes;
 
     if (isDuration(input)) {
-        duration = {
-            ms : input._milliseconds,
-            d  : input._days,
-            M  : input._months
-        };
+        duration = input;
     } else if (isNumber(input)) {
         duration = {};
         if (key) {