]> git.ipfire.org Git - thirdparty/moment.git/commitdiff
Add a test for Duration.abs() and make it immutable
authorLucas Sanders <butterflyhug@google.com>
Tue, 21 Mar 2017 04:49:53 +0000 (00:49 -0400)
committerLucas Sanders <butterflyhug@google.com>
Wed, 22 Mar 2017 11:00:21 +0000 (07:00 -0400)
src/lib/duration/abs.js
src/test/moment/duration.js
src/test/moment/mutable.js

index 103a4cf9b304487ce3de819769bc01fef5489af7..4ac020cc955b06e1a2ddc3facfa8f36ca3852ee7 100644 (file)
@@ -1,18 +1,14 @@
+import { Duration } from './constructor';
+
 var mathAbs = Math.abs;
 
 export function abs () {
-    var data           = this._data;
-
-    this._milliseconds = mathAbs(this._milliseconds);
-    this._days         = mathAbs(this._days);
-    this._months       = mathAbs(this._months);
-
-    data.milliseconds  = mathAbs(data.milliseconds);
-    data.seconds       = mathAbs(data.seconds);
-    data.minutes       = mathAbs(data.minutes);
-    data.hours         = mathAbs(data.hours);
-    data.months        = mathAbs(data.months);
-    data.years         = mathAbs(data.years);
-
-    return this;
+    if (!this.isValid()) {
+        return this;
+    }
+    return new Duration({
+        ms: mathAbs(this._milliseconds),
+        d:  mathAbs(this._days),
+        M:  mathAbs(this._months)
+    });
 }
index ee0cebfe94077a3079edb9e090273c4b72c128ef..c13f34902474b7429edad4e20fbcd5224062c9a2 100644 (file)
@@ -678,6 +678,14 @@ test('subtract', function (assert) {
     assert.equal(d._milliseconds, 3 * 60 * 60 * 1000 + 1 * 60 * 1000 - 10000, 'Subtract hour:minute');
 });
 
+test('abs', function (assert) {
+    var d = moment.duration({months: 2, weeks: 2, hours: 5});
+    assert.equal(+d.abs(), +d);
+    
+    d = moment.duration({months: -2, weeks: -2, hours: -5});
+    assert.equal(+d.abs(), -d);
+});
+
 test('JSON.stringify duration', function (assert) {
     var d = moment.duration(1024, 'h');
 
index 627e7ce6f19b13b74b8b64cbc0f35e729b8c1cea..ea4c8ffd3b3d9cb53521273e2506ad644400109a 100644 (file)
@@ -3,7 +3,7 @@ import moment from '../../moment';
 
 module('mutable');
 
-test('manipulation methods', function (assert) {
+test('moment manipulation methods', function (assert) {
     var m = moment([2017, 2, 21, 0, 6, 54]);
 
     assert.notEqual(m, moment(m), 'constructor should return a new moment');
@@ -25,3 +25,12 @@ test('manipulation methods', function (assert) {
     var utc = m.utc();
     assert.notEqual(utc, utc.local(), 'local() should return a new moment');
 });
+
+test('duration manipulation methods', function (assert) {
+    var d = moment.duration({months: 2, weeks: 2, days: 0, hours: 5});
+    
+    assert.notEqual(d, moment.duration(d), 'constructor should return a new duration');
+    assert.notEqual(d, d.abs(), 'abs() should return a new duration');
+    assert.notEqual(d, d.add(1, 'days'), 'add() should return a new duration');
+    assert.notEqual(d, d.subtract(2, 'years'), 'subtract() should return a new duration');
+});