Patterns: Fibonacci Sequence with a sample in JavaScript

Painting by Hilma af Klint

Nature repeatedly coalesces in spiral patterns; from galaxies to snail shells to weather patterns.

The Fibonacci sequence is the series of numbers with each new number is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377…

“The sequence is named for Leonardo Pisano (also known as – wait for it – Fibonacci), but in a more just world, it would be named the Pingala sequence, after the Sanskrit grammarian who documented it a thousand years earlier.” – Angus Croll, “If Hemingway Wrote JavaScript “

Interview Question

Please Write a function that returns the first n numbers of the Fibonacci Sequence.

There are multiple ways this can be archived.
Please see below a sample code from the book by Angus Croll “If Hemingway Wrote JavaScript”… with slight adjustments from me.
Why Hemingway?
“Basically, a typical Hemingway novel or short story is written in simple, direct, unadorned prose. Possibly, the style developed because of his early journalistic training. ” – Critical Essay Hemingway’s Writing Style
This is brilliant for JavaScript coding… we want our JavaScript to be simple, direct, and short!

function fibonacci(size) {
   // Sonya: added isNaN 
   if (isNaN(size)) {
          return "seriously?.. please enter a number :)"; 
    }
   
     if (size < 2) {
          return "the request was made but it was not good"; 
     }

     var first = 0, second = 1, next, count = 2;
     var result = [first, second]; 
    
     while (count++ < size) {
          next = first + second;
          first = second;
          second = next;
          result.push(next);
     }

     return result;
}

Try it in CodePen

Questions to consider:

Why is it good to have simple code?

What is easier to write code or to read code?

What is the next level of where you are right now?

Do you want to go to the next level, or would you rather stay and meditate?

For Adults:

For Children:



Categories: Patterns, Software Developer

Tags: , , , ,

Leave a Reply

%d bloggers like this: