I am currently working on a JavaScript program to generate a Fibonacci series, and there are certain conditions that need to be met:
- Each number in the series should be separated by a comma.
- The method should handle invalid values and return -1 for integers less than 1 or non-numeric values.
- The returned value must always be a string for valid input.
- 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))