From 981a32854a381219ab73eaf6299921ec381ba755 Mon Sep 17 00:00:00 2001 From: Isaac Cambron Date: Fri, 19 Jul 2013 09:48:11 -0400 Subject: [PATCH] string-driven getters and setters --- moment.js | 10 ++++++++ test/moment/getters_setters.js | 43 ++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/moment.js b/moment.js index bdc4c425b..7ace2c008 100644 --- a/moment.js +++ b/moment.js @@ -1459,6 +1459,16 @@ return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); }, + get : function (units) { + units = normalizeUnits(units); + return this[units.toLowerCase() + 's'](); + }, + + set : function (units, value) { + units = normalizeUnits(units); + this[units.toLowerCase() + 's'](value); + }, + // If passed a language key, it will set the language for this // instance. Otherwise, it will return the language configuration // variables for this instance. diff --git a/test/moment/getters_setters.js b/test/moment/getters_setters.js index 49207b950..6cb661a80 100644 --- a/test/moment/getters_setters.js +++ b/test/moment/getters_setters.js @@ -16,6 +16,21 @@ exports.getters_setters = { test.done(); }, + "getters programmatic" : function (test) { + test.expect(8); + + var a = moment([2011, 9, 12, 6, 7, 8, 9]); + test.equal(a.get('year'), 2011, 'year'); + test.equal(a.get('month'), 9, 'month'); + test.equal(a.get('date'), 12, 'date'); + test.equal(a.get('day'), 3, 'day'); + test.equal(a.get('hour'), 6, 'hour'); + test.equal(a.get('minute'), 7, 'minute'); + test.equal(a.get('second'), 8, 'second'); + test.equal(a.get('milliseconds'), 9, 'milliseconds'); + test.done(); + }, + "setters plural" : function (test) { test.expect(8); @@ -88,6 +103,34 @@ exports.getters_setters = { test.done(); }, + "setter programmatic" : function (test) { + test.expect(9); + + var a = moment(); + a.set('year', 2011); + a.set('month', 9); + a.set('date', 12); + a.set('hours', 6); + a.set('minutes', 7); + a.set('seconds', 8); + a.set('milliseconds', 9); + test.equal(a.year(), 2011, 'year'); + test.equal(a.month(), 9, 'month'); + test.equal(a.date(), 12, 'date'); + test.equal(a.day(), 3, 'day'); + test.equal(a.hours(), 6, 'hour'); + test.equal(a.minutes(), 7, 'minute'); + test.equal(a.seconds(), 8, 'second'); + test.equal(a.milliseconds(), 9, 'milliseconds'); + + // Test month() behavior. See https://github.com/timrwood/moment/pull/822 + a = moment('20130531', 'YYYYMMDD'); + a.month(3); + test.equal(a.month(), 3, 'month edge case'); + + test.done(); + }, + "setters strings" : function (test) { test.expect(7); -- 2.47.2