Skip to content

Instantly share code, notes, and snippets.

@sgimeno
Last active April 26, 2018 11:20
Show Gist options
  • Save sgimeno/8d3439fde1e4d8fe3ae42f014548be5c to your computer and use it in GitHub Desktop.
Save sgimeno/8d3439fde1e4d8fe3ae42f014548be5c to your computer and use it in GitHub Desktop.
Rec vs Loop Fibonacci for teaching purposes
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 }
{
"name": "fibonacci",
"version": "1.0.0",
"description": "",
"main": "fib.js",
"scripts": {
"test": "node test.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"tape": "^4.9.0"
}
}
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