From: Lucas Sanders Date: Tue, 21 Mar 2017 04:49:53 +0000 (-0400) Subject: Add a test for Duration.abs() and make it immutable X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=a488f4cff7ad4b7d8fa7b80e585058ea164db477;p=thirdparty%2Fmoment.git Add a test for Duration.abs() and make it immutable --- diff --git a/src/lib/duration/abs.js b/src/lib/duration/abs.js index 103a4cf9b..4ac020cc9 100644 --- a/src/lib/duration/abs.js +++ b/src/lib/duration/abs.js @@ -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) + }); } diff --git a/src/test/moment/duration.js b/src/test/moment/duration.js index ee0cebfe9..c13f34902 100644 --- a/src/test/moment/duration.js +++ b/src/test/moment/duration.js @@ -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'); diff --git a/src/test/moment/mutable.js b/src/test/moment/mutable.js index 627e7ce6f..ea4c8ffd3 100644 --- a/src/test/moment/mutable.js +++ b/src/test/moment/mutable.js @@ -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'); +});