fibonacci.js (1835B)
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 isnan = require( './../../../../base/assert/is-nan' ); 24 var isInteger = require( './../../../../base/assert/is-integer' ); 25 var MAX_FIBONACCI = require( '@stdlib/constants/float64/max-safe-nth-fibonacci' ); 26 var FIBONACCI = require( './fibonacci.json' ); 27 28 29 // MAIN // 30 31 /** 32 * Computes the nth Fibonacci number. 33 * 34 * @param {NonNegativeInteger} n - the Fibonacci number to compute 35 * @returns {NonNegativeInteger} Fibonacci number 36 * 37 * @example 38 * var y = fibonacci( 0 ); 39 * // returns 0 40 * 41 * @example 42 * var y = fibonacci( 1 ); 43 * // returns 1 44 * 45 * @example 46 * var y = fibonacci( 2 ); 47 * // returns 1 48 * 49 * @example 50 * var y = fibonacci( 3 ); 51 * // returns 2 52 * 53 * @example 54 * var y = fibonacci( 4 ); 55 * // returns 3 56 * 57 * @example 58 * var y = fibonacci( 5 ); 59 * // returns 5 60 * 61 * @example 62 * var y = fibonacci( 6 ); 63 * // returns 8 64 * 65 * @example 66 * var y = fibonacci( NaN ); 67 * // returns NaN 68 * 69 * @example 70 * var y = fibonacci( 3.14 ); 71 * // returns NaN 72 * 73 * @example 74 * var y = fibonacci( -1.0 ); 75 * // returns NaN 76 */ 77 function fibonacci( n ) { 78 if ( 79 isnan( n ) || 80 isInteger( n ) === false || 81 n < 0 || 82 n > MAX_FIBONACCI 83 ) { 84 return NaN; 85 } 86 return FIBONACCI[ n ]; 87 } 88 89 90 // EXPORTS // 91 92 module.exports = fibonacci;