CoDEVIANT #26 — Fibonacci Fun

I have a doctorate in music, I can help the patient onboard!
  • You always start with 0, followed by 1.
  • Every subsequent number in the list is the sum of the last two numbers
  • Example: [0, 1, 1, 2, 3, 5, 8, 14, …..]
function getNthFib(n) {
let counter = 2
let array = [0, 1]
while(counter < n) {
array.push(array[array.length - 2] + array[array.length - 1])
counter++
}
return n === 1 ? 0 : n === 2 ? 1 : array[n-2] + array[n-3]
}
  • Death
  • Taxes
  • that any Fibonacci Sequence will start with 0 and then 1
let counter = 2
let array = [0, 1]
while(counter < n) {
array.push(array[array.length - 2] + array[array.length - 1])
counter++
}
function getNthFib(n) {
const lastTwo = [0,1]
let counter = 3
while(counter <= n) {
const nextFib = lastTwo[0] + lastTwo[1]
lastTwo[0] = lastTwo[1]
lastTwo[1] = nextFib
counter++
}
return n > 1 ? lastTwo[1] : lastTwo[0];
}
  • Starting an array with 0 and 1
  • Using a counter variable which gets incremented through a while-loop
  • Using a ternary operator at the end to determine what will be returned
while(counter <= n) {
const nextFib = lastTwo[0] + lastTwo[1]
lastTwo[0] = lastTwo[1]
lastTwo[1] = nextFib
counter++
}
return n > 1 ? lastTwo[1] : lastTwo[0]

--

--

--

is a web developer, opera singer, actor, and lover of cats. (adrian-rosales.tech)

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

A Beginner’s Guide to Unit-Testing With Jest

Information is King — tap() — how to console.log in RxJS

JsUnit(s): The First JavaScript Unit Testing Libraries

Building a Video Sharing Website: Part 5 Category Views and Similar Videos

Blazor Authorization with Auth0 (RBAC)

How to use Angular route resolvers with NgRx store

React Hooks- Understanding the basics

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adrian Rosales

Adrian Rosales

is a web developer, opera singer, actor, and lover of cats. (adrian-rosales.tech)

More from Medium

“A journey of a thousand miles begins with a single step …”

Why you should write ?

Structure & Morphology