|
| 1 | +/** |
| 2 | + * Fibonacci implementations - CommonJS module |
| 3 | + * Intentionally inefficient for optimization testing. |
| 4 | + */ |
| 5 | + |
| 6 | +/** |
| 7 | + * Calculate the nth Fibonacci number using naive recursion. |
| 8 | + * This is intentionally slow to demonstrate optimization potential. |
| 9 | + * @param {number} n - The index of the Fibonacci number to calculate |
| 10 | + * @returns {number} The nth Fibonacci number |
| 11 | + */ |
| 12 | +function fibonacci(n) { |
| 13 | + if (n <= 1) { |
| 14 | + return n; |
| 15 | + } |
| 16 | + return fibonacci(n - 1) + fibonacci(n - 2); |
| 17 | +} |
| 18 | + |
| 19 | +/** |
| 20 | + * Check if a number is a Fibonacci number. |
| 21 | + * @param {number} num - The number to check |
| 22 | + * @returns {boolean} True if num is a Fibonacci number |
| 23 | + */ |
| 24 | +function isFibonacci(num) { |
| 25 | + // A number is Fibonacci if one of (5*n*n + 4) or (5*n*n - 4) is a perfect square |
| 26 | + const check1 = 5 * num * num + 4; |
| 27 | + const check2 = 5 * num * num - 4; |
| 28 | + return isPerfectSquare(check1) || isPerfectSquare(check2); |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Check if a number is a perfect square. |
| 33 | + * @param {number} n - The number to check |
| 34 | + * @returns {boolean} True if n is a perfect square |
| 35 | + */ |
| 36 | +function isPerfectSquare(n) { |
| 37 | + const sqrt = Math.sqrt(n); |
| 38 | + return sqrt === Math.floor(sqrt); |
| 39 | +} |
| 40 | + |
| 41 | +/** |
| 42 | + * Generate an array of Fibonacci numbers up to n. |
| 43 | + * @param {number} n - The number of Fibonacci numbers to generate |
| 44 | + * @returns {number[]} Array of Fibonacci numbers |
| 45 | + */ |
| 46 | +function fibonacciSequence(n) { |
| 47 | + const result = []; |
| 48 | + for (let i = 0; i < n; i++) { |
| 49 | + result.push(fibonacci(i)); |
| 50 | + } |
| 51 | + return result; |
| 52 | +} |
| 53 | + |
| 54 | +// CommonJS exports |
| 55 | +module.exports = { |
| 56 | + fibonacci, |
| 57 | + isFibonacci, |
| 58 | + isPerfectSquare, |
| 59 | + fibonacciSequence, |
| 60 | +}; |
0 commit comments