Skip to content

Commit

Permalink
Fixed cloning a modified duration
Browse files Browse the repository at this point in the history
Storing the _input for creating a duration doesn't work for cloning when the
original duration is modified, because input no longer corresponds to the new
duration. Instead use the ms, days and month values which uniquely identify
a duration.

This also happens to fix moment#1242
  • Loading branch information
ichernev committed Oct 31, 2013
1 parent ca3c889 commit 925762d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
18 changes: 10 additions & 8 deletions moment.js
Original file line number Diff line number Diff line change
Expand Up @@ -298,9 +298,6 @@
seconds = normalizedInput.second || 0,
milliseconds = normalizedInput.millisecond || 0;

// store reference to input for deterministic cloning
this._input = duration;

// representation for dateAddRemove
this._milliseconds = +milliseconds +
seconds * 1e3 + // 1000
Expand Down Expand Up @@ -1559,9 +1556,7 @@

// duration
moment.duration = function (input, key) {
var isDuration = moment.isDuration(input),
isNumber = (typeof input === 'number'),
duration = (isDuration ? input._input : (isNumber ? {} : input)),
var duration = input,
// matching against regexp is expensive, do it on demand
match = null,
sign,
Expand All @@ -1570,7 +1565,14 @@
timeEmpty,
dateTimeEmpty;

if (isNumber) {
if (moment.isDuration(input)) {
duration = {
ms: input._milliseconds,
d: input._days,
M: input._months
};
} else if (typeof input === 'number') {
duration = {};
if (key) {
duration[key] = input;
} else {
Expand Down Expand Up @@ -1609,7 +1611,7 @@

ret = new Duration(duration);

if (isDuration && input.hasOwnProperty('_lang')) {
if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
ret._lang = input._lang;
}

Expand Down
6 changes: 4 additions & 2 deletions test/moment/duration.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,12 +130,14 @@ exports.duration = {
minutes: 9,
seconds: 20,
milliseconds: 12
});
}),
modified = moment.duration(1, 'day').add(moment.duration(1, 'day'));

test.expect(3);
test.expect(4);
test.deepEqual(moment.duration(simple), simple, "simple clones are equal");
test.deepEqual(moment.duration(lengthy), lengthy, "lengthy clones are equal");
test.deepEqual(moment.duration(complicated), complicated, "complicated clones are equal");
test.deepEqual(moment.duration(modified), modified, "cloning modified duration works");
test.done();
},

Expand Down

0 comments on commit 925762d

Please sign in to comment.