Skip to content

Instantly share code, notes, and snippets.

@zaynali53
Created October 25, 2020 18:49
Show Gist options
  • Select an option

  • Save zaynali53/4fc01d6b5070289c21d99e794a8fa18c to your computer and use it in GitHub Desktop.

Select an option

Save zaynali53/4fc01d6b5070289c21d99e794a8fa18c to your computer and use it in GitHub Desktop.
// Returns Given Length Fibonacci Sequence (Array)
// Loop
function fibonacci(length) {
let n1 = 0, n2 = 1, next, sequence = []
for (let i = 1; i <= length; i++) {
sequence.push(n1)
next = n1 + n2
n1 = n2
n2 = next
}
return sequence
}
// Functional
let fibonacci = length => Array(length).fill().reduce(
(sequence, _, index) => sequence.concat(
index < 2 ? index : sequence[index - 1] + sequence[index - 2]
), []
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment