Skip to main content

Create a Fibonacci Sequence function using JavaScript

As a product developer, I tend to focus on developing complex solutions and often times forget about coding basics. I constantly write and deploy code, but It's common to get stuck in the product development rut of reusing pre-developed blocks of code throughout the system. In order sharpen my skills. I made it a goal to revisit popular coding exercises and see how I can solve them now that I have a few years of working experience. 

The fibonacci sequence came across my path once again! I've been asked how to calculate the sequence in past interviews, and it's fairly straight forward. For those not familiar, here's the sequence:

0 1 1 2 3 5 8 13 21

Essentially, the sum of the first two values is the third value...and the sum of the second and third value is the fourth value, and so on. There's a couple of ways to solve this problem.

Solution #1

The n parameter is basically an index stopping point.  In other words, how large do I want the array to be?  I set a default array with the first 2 values as a starting point (I could have passed them into the function, but i'm going to keep this simple)

I iterate n times to calculate the sum of the last two values of the array. I access these values simply by using Array.slice(-2). I use the ES6 spread operator to add the sequence array and the sum together. Each time I do that, I decrement n which stops the while loop when n == 2 (2 values were given as default). 


const fibonacci = (n) => {
  let sequence = [0, 1];
  while (n > 2) { //adjusted since we started with 2
    const [nextToLast, last] = sequence.slice(-2);
    sequence = [...sequence, (nextToLast + last)];
    n--;
  }
  return sequence;
};
console.log("fibonacci non recursive =", fibonacci(9));


Solution #2

I thought this is a good case for recursion. We can use most of concepts in #1 with a few minor changes:


const fibonacciRecursive = (n, sequence = [0, 1]) => {
  if (n == 2) {
    return sequence;
  }
  const [nextToLast, last] = sequence.slice(-2);
  return fibonacciRecursive( n - 1, [...sequence, (nextToLast + last)]);
}
console.log("fibonacci recursive =", fibonacciRecursive(9));


like most recursive functions, the first thing I added was a "bail out" check at the beginning of the function. If n == 2, then return the sequence array.  If that's not the case, call the current function with n - 1 and pass the spread operator with the sum of the last 2 values (we decrement n each iteration). The function will call itself until n == 2 and then bail out. This recursion function will give the same result as the function in example #1.

I hope this helps!


 


Comments

Popular posts from this blog

Resolved Sitecore "If you publish now, the selected version will not be visible on the web site" warning

The Problem:   Unable to publish any Sitecore item within a particular site, even out of the workflow. Rather, a warning reads " If you publish now, the selected version will not be visible on the web site " What I've Discovered: I couldn't publish any item in the site, not just one or two I viewed all parent items of the items in question The main home page displayed a different warning " This item will never be published because it's publishable option is disabled " Another sitecore developer reminded me of the standard fields option View --> check standard fields to show all standard page fields Found out that somebody checked Never Publish within the publishing section The Fix: After I unchecked the checkbox and saved the change, I was able to publish again.  :) Conclusion: Looks like another Sitecore user thought the children items would not be affected by this change.  Lesson  learned.

[Resolved] Sitecore ParseException: End of string expected at position...

Problem:  I have a line of code that uses Sitecore Fast Query to pull all items + children starting with a site item, like so: Item [] allItems = db.SelectItems( "fast:" + sitecorePath + "//*" ); Unfortunately, I would get a Sitecore parsing error at runtime: ParseException: End of string expected at position... Turns out Sitecore doesn't like hyphens ('-') in any sitecore path when using fast query, which I have a few distributor sites in a folder which contained hyphens. Solution: I create a simple method that resolves a sitecore path to be Sitecore fast query friendly:             string sitecorePath = "" ;             if (siteItem.Paths.FullPath.Contains( "-" ))             {                 String [...

Create a File Upload Service using Node.js / Express / Multer

Problem:    I needed to create a form that essentially uploads a file to a server, then posts the rest of the form data to a second server with the new file name. In other words, post the image to an “Image” server, then posts the form data (with the file URL) to a “Form Data” server. Solution:  Create an Express server that uses the “Multer” library to accomplish this. The Code: Create the express server and have it listen on a specific port var express = require( 'express' ); var app = express (); app . listen ( 3313 , function (){     console . log ( 'listening on port 3313' ); }); Install Multer.  Read here: https://www.npmjs.com/package/multer Include Multer to your express app.  We’ll be tweaking the storage properties so you can name the file whatever you like. At the end, you should have an “upload” object you’ll be using in the next step. be sure to change the file destination of your choice. var expre...