seconds_in_year.js (1958B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var isDateObject = require( '@stdlib/assert/is-date-object' ); 24 var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; 25 var isLeapYear = require( '@stdlib/assert/is-leap-year' ); 26 27 28 // VARIABLES // 29 30 var NON_LEAP_YEAR = 31536000|0; // 365 * 86400 31 var LEAP_YEAR = 31622400|0; // 366 * 86400 32 33 34 // MAIN // 35 36 /** 37 * Returns the number of seconds in a year. 38 * 39 * @param {(integer|Date)} value - year or `Date` object 40 * @throws {TypeError} must provide either an integer or a `Date` object 41 * @returns {integer} number of seconds in a year 42 * 43 * @example 44 * var num = secondsInYear(); 45 * // returns <number> 46 * 47 * @example 48 * var num = secondsInYear( 2016 ); 49 * // returns 31622400 50 * 51 * @example 52 * var num = secondsInYear( 2017 ); 53 * // returns 31536000 54 */ 55 function secondsInYear( value ) { 56 var yr; 57 if ( arguments.length ) { 58 if ( isDateObject( value ) ) { 59 yr = value.getFullYear(); 60 } else if ( isInteger( value ) ) { 61 yr = value; 62 } else { 63 throw new TypeError( 'invalid argument. Must provide either an integer or a `Date` object. Value: `'+value+'`.' ); 64 } 65 } else { 66 // Note: cannot cache as application could cross over into a new year: 67 yr = ( new Date() ).getFullYear(); 68 } 69 if ( isLeapYear( yr ) ) { 70 return LEAP_YEAR; 71 } 72 return NON_LEAP_YEAR; 73 } 74 75 76 // EXPORTS // 77 78 module.exports = secondsInYear;