Last active
April 26, 2018 11:20
-
-
Save sgimeno/8d3439fde1e4d8fe3ae42f014548be5c to your computer and use it in GitHub Desktop.
Rec vs Loop Fibonacci for teaching purposes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function FibonacciSeqRec(n) { | |
const fib = (seq) => { | |
if (seq.length === n) return seq | |
if (seq.length < 2) seq.push(1) | |
else seq.push(seq[seq.length - 2] + seq[seq.length - 1]) | |
return fib(seq) | |
} | |
return fib([]) | |
} | |
function FibonacciSeqLoop(n) { | |
let seq = [] | |
while (seq.length < n) { | |
if (seq.length < 2) seq.push(1) | |
else seq.push(seq[seq.length - 2] + seq[seq.length - 1]) | |
} | |
return seq | |
} | |
module.exports = { FibonacciSeqRec, FibonacciSeqLoop } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "fibonacci", | |
"version": "1.0.0", | |
"description": "", | |
"main": "fib.js", | |
"scripts": { | |
"test": "node test.js" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"tape": "^4.9.0" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const test = require('tape') | |
const { FibonacciSeqRec, FibonacciSeqLoop } = require('./fibonacci') | |
test('Should create fibonacci sequence till 233', t => { | |
const expected = [1,1,2,3,5,8,13,21,34,55,89,144,233] | |
t.deepEqual(FibonacciSeqRec(expected.length), expected) | |
t.end() | |
}) | |
test('Should create fibonacci sequence till 233', t => { | |
const expected = [1,1,2,3,5,8,13,21,34,55,89,144,233] | |
t.deepEqual(FibonacciSeqLoop(expected.length), expected) | |
t.end() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment