diff options
Diffstat (limited to 'library/moment/src/lib/duration')
-rw-r--r-- | library/moment/src/lib/duration/abs.js | 18 | ||||
-rw-r--r-- | library/moment/src/lib/duration/add-subtract.js | 21 | ||||
-rw-r--r-- | library/moment/src/lib/duration/as.js | 55 | ||||
-rw-r--r-- | library/moment/src/lib/duration/bubble.js | 61 | ||||
-rw-r--r-- | library/moment/src/lib/duration/constructor.js | 41 | ||||
-rw-r--r-- | library/moment/src/lib/duration/create.js | 113 | ||||
-rw-r--r-- | library/moment/src/lib/duration/duration.js | 12 | ||||
-rw-r--r-- | library/moment/src/lib/duration/get.js | 25 | ||||
-rw-r--r-- | library/moment/src/lib/duration/humanize.js | 64 | ||||
-rw-r--r-- | library/moment/src/lib/duration/iso-string.js | 52 | ||||
-rw-r--r-- | library/moment/src/lib/duration/prototype.js | 48 |
11 files changed, 510 insertions, 0 deletions
diff --git a/library/moment/src/lib/duration/abs.js b/library/moment/src/lib/duration/abs.js new file mode 100644 index 000000000..103a4cf9b --- /dev/null +++ b/library/moment/src/lib/duration/abs.js @@ -0,0 +1,18 @@ +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; +} diff --git a/library/moment/src/lib/duration/add-subtract.js b/library/moment/src/lib/duration/add-subtract.js new file mode 100644 index 000000000..3b44e186f --- /dev/null +++ b/library/moment/src/lib/duration/add-subtract.js @@ -0,0 +1,21 @@ +import { createDuration } from './create'; + +function addSubtract (duration, input, value, direction) { + var other = createDuration(input, value); + + duration._milliseconds += direction * other._milliseconds; + duration._days += direction * other._days; + duration._months += direction * other._months; + + return duration._bubble(); +} + +// supports only 2.0-style add(1, 's') or add(duration) +export function add (input, value) { + return addSubtract(this, input, value, 1); +} + +// supports only 2.0-style subtract(1, 's') or subtract(duration) +export function subtract (input, value) { + return addSubtract(this, input, value, -1); +} diff --git a/library/moment/src/lib/duration/as.js b/library/moment/src/lib/duration/as.js new file mode 100644 index 000000000..03ecd6dab --- /dev/null +++ b/library/moment/src/lib/duration/as.js @@ -0,0 +1,55 @@ +import { daysToMonths, monthsToDays } from './bubble'; +import { normalizeUnits } from '../units/aliases'; +import toInt from '../utils/to-int'; + +export function as (units) { + var days; + var months; + var milliseconds = this._milliseconds; + + units = normalizeUnits(units); + + if (units === 'month' || units === 'year') { + days = this._days + milliseconds / 864e5; + months = this._months + daysToMonths(days); + return units === 'month' ? months : months / 12; + } else { + // handle milliseconds separately because of floating point math errors (issue #1867) + days = this._days + Math.round(monthsToDays(this._months)); + switch (units) { + case 'week' : return days / 7 + milliseconds / 6048e5; + case 'day' : return days + milliseconds / 864e5; + case 'hour' : return days * 24 + milliseconds / 36e5; + case 'minute' : return days * 1440 + milliseconds / 6e4; + case 'second' : return days * 86400 + milliseconds / 1000; + // Math.floor prevents floating point math errors here + case 'millisecond': return Math.floor(days * 864e5) + milliseconds; + default: throw new Error('Unknown unit ' + units); + } + } +} + +// TODO: Use this.as('ms')? +export function valueOf () { + return ( + this._milliseconds + + this._days * 864e5 + + (this._months % 12) * 2592e6 + + toInt(this._months / 12) * 31536e6 + ); +} + +function makeAs (alias) { + return function () { + return this.as(alias); + }; +} + +export var asMilliseconds = makeAs('ms'); +export var asSeconds = makeAs('s'); +export var asMinutes = makeAs('m'); +export var asHours = makeAs('h'); +export var asDays = makeAs('d'); +export var asWeeks = makeAs('w'); +export var asMonths = makeAs('M'); +export var asYears = makeAs('y'); diff --git a/library/moment/src/lib/duration/bubble.js b/library/moment/src/lib/duration/bubble.js new file mode 100644 index 000000000..0c4a336ec --- /dev/null +++ b/library/moment/src/lib/duration/bubble.js @@ -0,0 +1,61 @@ +import absFloor from '../utils/abs-floor'; +import absCeil from '../utils/abs-ceil'; +import { createUTCDate } from '../create/date-from-array'; + +export function bubble () { + var milliseconds = this._milliseconds; + var days = this._days; + var months = this._months; + var data = this._data; + var seconds, minutes, hours, years, monthsFromDays; + + // if we have a mix of positive and negative values, bubble down first + // check: https://github.com/moment/moment/issues/2166 + if (!((milliseconds >= 0 && days >= 0 && months >= 0) || + (milliseconds <= 0 && days <= 0 && months <= 0))) { + milliseconds += absCeil(monthsToDays(months) + days) * 864e5; + days = 0; + months = 0; + } + + // The following code bubbles up values, see the tests for + // examples of what that means. + data.milliseconds = milliseconds % 1000; + + seconds = absFloor(milliseconds / 1000); + data.seconds = seconds % 60; + + minutes = absFloor(seconds / 60); + data.minutes = minutes % 60; + + hours = absFloor(minutes / 60); + data.hours = hours % 24; + + days += absFloor(hours / 24); + + // convert days to months + monthsFromDays = absFloor(daysToMonths(days)); + months += monthsFromDays; + days -= absCeil(monthsToDays(monthsFromDays)); + + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; + + data.days = days; + data.months = months; + data.years = years; + + return this; +} + +export function daysToMonths (days) { + // 400 years have 146097 days (taking into account leap year rules) + // 400 years have 12 months === 4800 + return days * 4800 / 146097; +} + +export function monthsToDays (months) { + // the reverse of daysToMonths + return months * 146097 / 4800; +} diff --git a/library/moment/src/lib/duration/constructor.js b/library/moment/src/lib/duration/constructor.js new file mode 100644 index 000000000..884c6f8c8 --- /dev/null +++ b/library/moment/src/lib/duration/constructor.js @@ -0,0 +1,41 @@ +import { normalizeObjectUnits } from '../units/aliases'; +import { getLocale } from '../locale/locales'; + +export function Duration (duration) { + var normalizedInput = normalizeObjectUnits(duration), + years = normalizedInput.year || 0, + quarters = normalizedInput.quarter || 0, + months = normalizedInput.month || 0, + weeks = normalizedInput.week || 0, + days = normalizedInput.day || 0, + hours = normalizedInput.hour || 0, + minutes = normalizedInput.minute || 0, + seconds = normalizedInput.second || 0, + milliseconds = normalizedInput.millisecond || 0; + + // representation for dateAddRemove + this._milliseconds = +milliseconds + + seconds * 1e3 + // 1000 + minutes * 6e4 + // 1000 * 60 + hours * 36e5; // 1000 * 60 * 60 + // Because of dateAddRemove treats 24 hours as different from a + // 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 + // which months you are are talking about, so we have to store + // it separately. + this._months = +months + + quarters * 3 + + years * 12; + + this._data = {}; + + this._locale = getLocale(); + + this._bubble(); +} + +export function isDuration (obj) { + return obj instanceof Duration; +} diff --git a/library/moment/src/lib/duration/create.js b/library/moment/src/lib/duration/create.js new file mode 100644 index 000000000..15f05dead --- /dev/null +++ b/library/moment/src/lib/duration/create.js @@ -0,0 +1,113 @@ +import { Duration, isDuration } from './constructor'; +import toInt from '../utils/to-int'; +import hasOwnProp from '../utils/has-own-prop'; +import { DATE, HOUR, MINUTE, SECOND, MILLISECOND } from '../units/constants'; +import { cloneWithOffset } from '../units/offset'; +import { createLocal } from '../create/local'; + +// ASP.NET json date format regex +var aspNetRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/; + +// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html +// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere +var isoRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/; + +export function createDuration (input, key) { + var duration = input, + // matching against regexp is expensive, do it on demand + match = null, + sign, + ret, + diffRes; + + if (isDuration(input)) { + duration = { + ms : input._milliseconds, + d : input._days, + M : input._months + }; + } else if (typeof input === 'number') { + duration = {}; + if (key) { + duration[key] = input; + } else { + duration.milliseconds = input; + } + } else if (!!(match = aspNetRegex.exec(input))) { + sign = (match[1] === '-') ? -1 : 1; + duration = { + y : 0, + d : toInt(match[DATE]) * sign, + h : toInt(match[HOUR]) * sign, + m : toInt(match[MINUTE]) * sign, + s : toInt(match[SECOND]) * sign, + ms : toInt(match[MILLISECOND]) * sign + }; + } else if (!!(match = isoRegex.exec(input))) { + sign = (match[1] === '-') ? -1 : 1; + duration = { + y : parseIso(match[2], sign), + M : parseIso(match[3], sign), + d : parseIso(match[4], sign), + h : parseIso(match[5], sign), + m : parseIso(match[6], sign), + s : parseIso(match[7], sign), + w : parseIso(match[8], sign) + }; + } else if (duration == null) {// checks for null or undefined + duration = {}; + } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { + diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to)); + + duration = {}; + duration.ms = diffRes.milliseconds; + duration.M = diffRes.months; + } + + ret = new Duration(duration); + + if (isDuration(input) && hasOwnProp(input, '_locale')) { + ret._locale = input._locale; + } + + return ret; +} + +createDuration.fn = Duration.prototype; + +function parseIso (inp, sign) { + // We'd normally use ~~inp for this, but unfortunately it also + // converts floats to ints. + // inp may be undefined, so careful calling replace on it. + var res = inp && parseFloat(inp.replace(',', '.')); + // apply sign while we're at it + return (isNaN(res) ? 0 : res) * sign; +} + +function positiveMomentsDifference(base, other) { + var res = {milliseconds: 0, months: 0}; + + res.months = other.month() - base.month() + + (other.year() - base.year()) * 12; + if (base.clone().add(res.months, 'M').isAfter(other)) { + --res.months; + } + + res.milliseconds = +other - +(base.clone().add(res.months, 'M')); + + return res; +} + +function momentsDifference(base, other) { + var res; + other = cloneWithOffset(other, base); + if (base.isBefore(other)) { + res = positiveMomentsDifference(base, other); + } else { + res = positiveMomentsDifference(other, base); + res.milliseconds = -res.milliseconds; + res.months = -res.months; + } + + return res; +} diff --git a/library/moment/src/lib/duration/duration.js b/library/moment/src/lib/duration/duration.js new file mode 100644 index 000000000..24440bb2b --- /dev/null +++ b/library/moment/src/lib/duration/duration.js @@ -0,0 +1,12 @@ +// Side effect imports +import './prototype'; + +import { createDuration } from './create'; +import { isDuration } from './constructor'; +import { getSetRelativeTimeThreshold } from './humanize'; + +export { + createDuration, + isDuration, + getSetRelativeTimeThreshold +}; diff --git a/library/moment/src/lib/duration/get.js b/library/moment/src/lib/duration/get.js new file mode 100644 index 000000000..6dafacdd8 --- /dev/null +++ b/library/moment/src/lib/duration/get.js @@ -0,0 +1,25 @@ +import { normalizeUnits } from '../units/aliases'; +import absFloor from '../utils/abs-floor'; + +export function get (units) { + units = normalizeUnits(units); + return this[units + 's'](); +} + +function makeGetter(name) { + return function () { + return this._data[name]; + }; +} + +export var milliseconds = makeGetter('milliseconds'); +export var seconds = makeGetter('seconds'); +export var minutes = makeGetter('minutes'); +export var hours = makeGetter('hours'); +export var days = makeGetter('days'); +export var months = makeGetter('months'); +export var years = makeGetter('years'); + +export function weeks () { + return absFloor(this.days() / 7); +} diff --git a/library/moment/src/lib/duration/humanize.js b/library/moment/src/lib/duration/humanize.js new file mode 100644 index 000000000..d6dd83b04 --- /dev/null +++ b/library/moment/src/lib/duration/humanize.js @@ -0,0 +1,64 @@ +import { createDuration } from './create'; + +var round = Math.round; +var thresholds = { + s: 45, // seconds to minute + m: 45, // minutes to hour + h: 22, // hours to day + d: 26, // days to month + M: 11 // months to year +}; + +// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize +function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { + return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); +} + +function relativeTime (posNegDuration, withoutSuffix, locale) { + var duration = createDuration(posNegDuration).abs(); + var seconds = round(duration.as('s')); + var minutes = round(duration.as('m')); + var hours = round(duration.as('h')); + var days = round(duration.as('d')); + var months = round(duration.as('M')); + var years = round(duration.as('y')); + + var a = seconds < thresholds.s && ['s', seconds] || + minutes === 1 && ['m'] || + minutes < thresholds.m && ['mm', minutes] || + hours === 1 && ['h'] || + hours < thresholds.h && ['hh', hours] || + days === 1 && ['d'] || + days < thresholds.d && ['dd', days] || + months === 1 && ['M'] || + months < thresholds.M && ['MM', months] || + years === 1 && ['y'] || ['yy', years]; + + a[2] = withoutSuffix; + a[3] = +posNegDuration > 0; + a[4] = locale; + return substituteTimeAgo.apply(null, a); +} + +// This function allows you to set a threshold for relative time strings +export function getSetRelativeTimeThreshold (threshold, limit) { + if (thresholds[threshold] === undefined) { + return false; + } + if (limit === undefined) { + return thresholds[threshold]; + } + thresholds[threshold] = limit; + return true; +} + +export function humanize (withSuffix) { + var locale = this.localeData(); + var output = relativeTime(this, !withSuffix, locale); + + if (withSuffix) { + output = locale.pastFuture(+this, output); + } + + return locale.postformat(output); +} diff --git a/library/moment/src/lib/duration/iso-string.js b/library/moment/src/lib/duration/iso-string.js new file mode 100644 index 000000000..f33a968da --- /dev/null +++ b/library/moment/src/lib/duration/iso-string.js @@ -0,0 +1,52 @@ +import absFloor from '../utils/abs-floor'; +var abs = Math.abs; + +export function toISOString() { + // for ISO strings we do not use the normal bubbling rules: + // * milliseconds bubble up until they become hours + // * days do not bubble at all + // * months bubble up until they become years + // This is because there is no context-free conversion between hours and days + // (think of clock changes) + // and also not between days and months (28-31 days per month) + var seconds = abs(this._milliseconds) / 1000; + var days = abs(this._days); + var months = abs(this._months); + var minutes, hours, years; + + // 3600 seconds -> 60 minutes -> 1 hour + minutes = absFloor(seconds / 60); + hours = absFloor(minutes / 60); + seconds %= 60; + minutes %= 60; + + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; + + + // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js + var Y = years; + var M = months; + var D = days; + var h = hours; + var m = minutes; + var s = seconds; + var total = this.asSeconds(); + + if (!total) { + // this is the same as C#'s (Noda) and python (isodate)... + // but not other JS (goog.date) + return 'P0D'; + } + + return (total < 0 ? '-' : '') + + 'P' + + (Y ? Y + 'Y' : '') + + (M ? M + 'M' : '') + + (D ? D + 'D' : '') + + ((h || m || s) ? 'T' : '') + + (h ? h + 'H' : '') + + (m ? m + 'M' : '') + + (s ? s + 'S' : ''); +} diff --git a/library/moment/src/lib/duration/prototype.js b/library/moment/src/lib/duration/prototype.js new file mode 100644 index 000000000..0257ff9b5 --- /dev/null +++ b/library/moment/src/lib/duration/prototype.js @@ -0,0 +1,48 @@ +import { Duration } from './constructor'; + +var proto = Duration.prototype; + +import { abs } from './abs'; +import { add, subtract } from './add-subtract'; +import { as, asMilliseconds, asSeconds, asMinutes, asHours, asDays, asWeeks, asMonths, asYears, valueOf } from './as'; +import { bubble } from './bubble'; +import { get, milliseconds, seconds, minutes, hours, days, months, years, weeks } from './get'; +import { humanize } from './humanize'; +import { toISOString } from './iso-string'; +import { lang, locale, localeData } from '../moment/locale'; + +proto.abs = abs; +proto.add = add; +proto.subtract = subtract; +proto.as = as; +proto.asMilliseconds = asMilliseconds; +proto.asSeconds = asSeconds; +proto.asMinutes = asMinutes; +proto.asHours = asHours; +proto.asDays = asDays; +proto.asWeeks = asWeeks; +proto.asMonths = asMonths; +proto.asYears = asYears; +proto.valueOf = valueOf; +proto._bubble = bubble; +proto.get = get; +proto.milliseconds = milliseconds; +proto.seconds = seconds; +proto.minutes = minutes; +proto.hours = hours; +proto.days = days; +proto.weeks = weeks; +proto.months = months; +proto.years = years; +proto.humanize = humanize; +proto.toISOString = toISOString; +proto.toString = toISOString; +proto.toJSON = toISOString; +proto.locale = locale; +proto.localeData = localeData; + +// Deprecations +import { deprecate } from '../utils/deprecate'; + +proto.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString); +proto.lang = lang; |