cscg24-guacamole

CSCG 2024 Challenge 'Guacamole Mashup'
git clone https://git.sinitax.com/sinitax/cscg24-guacamole
Log | Files | Refs | sfeed.txt

as.js (2094B)


      1import { daysToMonths, monthsToDays } from './bubble';
      2import { normalizeUnits } from '../units/aliases';
      3
      4export function as(units) {
      5    if (!this.isValid()) {
      6        return NaN;
      7    }
      8    var days,
      9        months,
     10        milliseconds = this._milliseconds;
     11
     12    units = normalizeUnits(units);
     13
     14    if (units === 'month' || units === 'quarter' || units === 'year') {
     15        days = this._days + milliseconds / 864e5;
     16        months = this._months + daysToMonths(days);
     17        switch (units) {
     18            case 'month':
     19                return months;
     20            case 'quarter':
     21                return months / 3;
     22            case 'year':
     23                return months / 12;
     24        }
     25    } else {
     26        // handle milliseconds separately because of floating point math errors (issue #1867)
     27        days = this._days + Math.round(monthsToDays(this._months));
     28        switch (units) {
     29            case 'week':
     30                return days / 7 + milliseconds / 6048e5;
     31            case 'day':
     32                return days + milliseconds / 864e5;
     33            case 'hour':
     34                return days * 24 + milliseconds / 36e5;
     35            case 'minute':
     36                return days * 1440 + milliseconds / 6e4;
     37            case 'second':
     38                return days * 86400 + milliseconds / 1000;
     39            // Math.floor prevents floating point math errors here
     40            case 'millisecond':
     41                return Math.floor(days * 864e5) + milliseconds;
     42            default:
     43                throw new Error('Unknown unit ' + units);
     44        }
     45    }
     46}
     47
     48function makeAs(alias) {
     49    return function () {
     50        return this.as(alias);
     51    };
     52}
     53
     54var asMilliseconds = makeAs('ms'),
     55    asSeconds = makeAs('s'),
     56    asMinutes = makeAs('m'),
     57    asHours = makeAs('h'),
     58    asDays = makeAs('d'),
     59    asWeeks = makeAs('w'),
     60    asMonths = makeAs('M'),
     61    asQuarters = makeAs('Q'),
     62    asYears = makeAs('y'),
     63    valueOf = asMilliseconds;
     64
     65export {
     66    asMilliseconds,
     67    asSeconds,
     68    asMinutes,
     69    asHours,
     70    asDays,
     71    asWeeks,
     72    asMonths,
     73    asQuarters,
     74    asYears,
     75    valueOf,
     76};