From ddcd2a7a11b0b5fb7ad3afe6b95ad6ee2ca93397 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Sun, 23 Jul 2023 16:20:07 +0200 Subject: [PATCH] add alternative fibonacci while loop implementation MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- fibonacci.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/fibonacci.js b/fibonacci.js index 75476bf..a62f471 100644 --- a/fibonacci.js +++ b/fibonacci.js @@ -16,6 +16,22 @@ function fibonacciLoop (num) { return fib[num] } +/** + * + * @param num + * @returns + */ +function fibonacciLoopWhile (num) { + let current = 1 + let previous = 0 + while (--num) { + const temp = current + current += previous + previous = temp + } + return current +} + /** * @param num * @returns @@ -46,6 +62,9 @@ Benchmark.suite( Benchmark.add('fibonacciLoop', () => { fibonacciLoop(number) }), + Benchmark.add('fibonacciLoopWhile', () => { + fibonacciLoopWhile(number) + }), Benchmark.add('fibonacciRecursion', () => { fibonacciRecursion(number) }), -- 2.34.1