JavaScript function not updating value after a while loop

53 Views Asked by At

So I'm writing a CloudFront Function that takes the number from a request, calculates the result, and sends it back to the user via a header named "fibval".

The trouble I'm having is primarily within the fibonacci sequence function. When I test my url doing this: "/fibonacci/13" I'm expecting a custom header to come back with fibval: 233, however it comes back as fibval: 1.

This is due to my function (code below) not sending the proper number back. Using some hardcoded testing, I've found the issue is primarily with var num2 and return num2. I've validated this by rewriting var num2 to be instantiated to 67, and can confirm that's the issue when I check the header it sends back.

function fibFunc(index){
    if (index == 1)
        return 0;
    if (index == 2)
        return 1;
    var num1 = 0;
    var num2 = 1;
    var sum;
    var i = 1;
    while (i < index) {
        sum = num1 + num2;
        num1 = num2;
        num2 = sum;
        i += 1;
    }
    return num2;
}

I'm no greenhorn to coding, but I'm not super familiar with JavaScript's deeper mechanisms, and it operates differently than expected within CloudFront Functions.

I've attempted to return from within the while loop using something such as

while (i < index) {
        sum = num1 + num2;
        num1 = num2;
        num2 = sum;
        i += 1;
        if(i == index){
        ``return num2
        }
    }

but it returns 503 errors when I put it into practice and try to utilize the function. Similarly, I can not avoid this problem by swapping to the recursive variant of the fibonacci function, as that causes significant performance lag on CloudFront as well as delivers another 503 error.

Due to a comment, I'm providing the handler function to provide more context.

async function handler(event) {
    const url = event.request;
    const pathSegments = url.uri.split('/')
    const key = pathSegments[4] //returns fib number from input
    var result = fibFunc(key)
    //var five = 5;
    var response = {
        statusCode: 302,
        statusDescription: 'Found',
        headers: {
        'fibval': {'value': result.toString()},
        //'fibval': {'value': five.toString()},
        }
    };
    return response;
}
0

There are 0 best solutions below