In my JavaScript code for generating a Fibonacci series, I aim to include a comma at the end of each string

I am currently working on a JavaScript program to generate a Fibonacci series, and there are certain conditions that need to be met:

  1. Each number in the series should be separated by a comma.
  2. The method should handle invalid values and return -1 for integers less than 1 or non-numeric values.
  3. The returned value must always be a string for valid input.
  4. The output string should always end with a comma.

So far, I have completed the first three steps successfully. However, I am facing a challenge when it comes to adding a comma at the end of the series. I am struggling to understand how to achieve this without causing issues such as missing commas between numbers along the way.

function fibonacci(len) {
  var a = 0,
    b = 1,
    f = 1,
    sum = 1;
  if (len > 2) {
    for (var i = 2; i <= len; i++) {
      f = a + b;
      sum += ',' + f;
      a = b;
      b = f;
    }
  } else if (len == 1) {
    sum = '1,1,';
  } else {
    sum = '-1';
  }
  return sum;
}
console.log(fibonacci(10))

Answer №1

function generateFibonacciSequence(length) {
    // validate the length parameter
    if(isNaN(length) || (parseInt(length) | 0) !== length || length < 1) {
        return -1;
    }
    
    var sequence = [1, 1];
    
    for(let index = 1; index<length; index++) {
        // calculate next fibonacci number
        var nextNumber = sequence[index] + sequence[index-1];
        sequence.push(nextNumber);
    }
    
    // convert array to a comma-separated string
    return sequence.join(", ") + ",";
}

console.log(generateFibonacciSequence(1))
console.log(generateFibonacciSequence(5))
console.log(generateFibonacciSequence("a"))

Answer №2

Here's a quick solution: return sum+",";

I recommend using an array and the join method to streamline your code. Don't forget to remove any unnecessary data at the beginning.

Additionally, start looping from 1 instead of 0.

function fibonacci(len) {
  if (isNaN(len) || len < 1 ) return -1;
  let a = 0, b = 1, f = 1, sum = [1];
  for (let i = 1; i <= len; i++) {
    f = a + b;
    sum.push(f);
    a = b;
    b = f;
  }
  return sum === -1 ? sum : sum.join(",") + ",";
}

// tests
console.log(fibonacci(10))
console.log(fibonacci(1))
console.log(fibonacci(2))
console.log(fibonacci(0))
console.log(fibonacci("A"))
console.log(fibonacci("    1    "))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some effective strategies for bypassing CORS requirements in Vue client-side and server-side applications?

I found this amazing MEVN stack tutorial that I've been following: MEVN Stack Tutorial The tutorial is about creating a blog post app, where the client side is built using Vue (referred to as app A) and the backend is built on Express.js providing d ...

Having issues with the right margin in HTML5 canvas and struggling to remove the scroll bar

I am struggling with adjusting the margins of my canvas to ensure equal spacing on both sides without any horizontal scroll bars. Desired Outcome: Equal margin on both sides of canvas without any horizontal scroll bars. Issue: The margin-right property i ...

Keep moving forward in Sailsjs even after sending back a response with res.json();

It will keep running even if the condition is met and the code inside return res.json() gets executed. _.each(rooms, function(room){ if(room.users.length == users.length) { return res.json(room); // <-- returns but execution continues } ...

Clicking to center div elements

When clicking on my div elements, they transform into flipcards and expand to a size of 600px by 600px. I want these divs to be centered in the middle of the screen when clicked, and then move back to their original position when clicked again. I've b ...

Steps to resolve the error message "The port 9876 has no listening server when karma is running"

I have a situation where I am executing the following code: PS D:\app> karma run However, an error is being displayed: [2013-11-29 17:39:54.297] [DEBUG] config - Loading config D:\app\karma.conf.js There is no server listening on port ...

Issue with floating navigation bar functionality when resizing the page

After much tinkering, I have managed to create a floating navigation bar for my website. Most of the time, it works perfectly fine, but there's an issue when the window size is adjusted in the floating mode. Take a look at the image below for referenc ...

The <a> tag does not lead to a different webpage and cannot be clicked on

I have developed a web component that includes a method to generate a copyright string: '<p>Copyright © 2020 John Doe<a href="https://www.example.com">. Terms of Use</a></p>' After creating the string, I conver ...

Scope isolation prevents variables from being accessed in higher levels of the scope chain

In my search for answers, I came across some similar questions on SO: Isolate scope variable is undefined unable to access rootscope var in directive scope However, my question presents a unique scenario. I am facing an issue with a directive that has a ...

The behavior of Datatables varies depending on the screen resolution

In my data table, there are numerous entries with child tables on each row of the main table. I am currently in the process of incorporating this type of functionality into my table, with a few modifications to create a table within the child row. You can ...

How can I show a view page in a specific div element using CodeIgniter?

Here is how I'm implementing the dashboard view in my controller. My goal is to have a specific page, like the index page, displayed within a div element rather than opening in a new tab. public function index() { $this->load->view('in ...

How can I display a particular section of my JSON data in an AngularJS application?

Below is an example of a JSON structure: {"years":[ { "year_title":"94", "months":[...] } { "year_title":"95", "months":[...] } { "year_title":"96", "months":[...] } ]} I was able to display the data using the code sni ...

Exploring the capabilities of utilizing filters within a ternary operator in AngularJS

Can a filter be applied to a variable in the template within a ternary operation? <img ng-src="{{ image_url && image_url|filter:"foo" || other_url }}"> In this scenario, the filter is custom-made and I prefer not to alter it to accommodate ...

Experimenting with Chai in JavaScript to test an incorrect argument

Background: I recently delved into JavaScript and have been experimenting with it. It's possible that my question may sound silly, but I am eager to learn. I have developed a function called `getDayOfTheWeekFromDate` which returns the day of the week ...

Dealing with POST redirection and retrieving parameters in Next.js

In a typical scenario, browsers send GET requests and servers return pages. However, in my case, I am making requests to a remote server and need to receive responses. The issue is that the server redirects me back to my page via a POST request with some d ...

Retrieving Information from Website Components in JavaFX Web View

I am currently developing a Java FX program that loads a folder containing HTML/CSS/JS files with 3 different websites. While the websites are displaying correctly in the webview, I am looking for a way to capture user interactions, such as checkbox selec ...

Sending Angular base64 image data to the server

I am encountering an issue while attempting to upload a base64 image from Angular to ExpressJS. The image is being created using html2canvas to generate the base64 representation. When I try to upload the imageData in its current format, I receive an error ...

Use multiple lines to create a stunning visualization using morris.js. Let your data

I need help creating a graph using morris.js with 2 lines. I have two sets of data in one array, but I can't seem to display both lines on the graph simultaneously. When I use todos[0], only the first line is visible, and when I use todos[1], only the ...

The Jquery Object #<Object> does not have the 'getElement' method available

I've been attempting to set up this table, following the instructions here: Despite verifying that my browser is correctly pulling the CSS and .js files, I keep encountering an error related to my sortabletable.js file. (screenshot of the error) htt ...

Use JavaScript to swap out images

How can I change the image arrow when it is clicked? Currently, I have this code snippet: http://codepen.io/anon/pen/qEMLxq. However, when the image is clicked, it changes but does not hide. <a id="Boton1" class="button" onClick="showHide()" href="j ...

Ways to handle a hidden element in Selenium Webdriver

Special features of this element:- <textarea id="txtSuffixTitle" class="form-control" tabindex="3" rows="2" placeholder="Suffix Title" name="txtSuffixTitle" maxlength="50" cols="20" style="display: none; visibility: hidden;">Suffix Title </text ...