What are some strategies for creating a recursive function in JavaScript that avoids exceeding the maximum call stack size error?

I need assistance creating a walking robot function in JavaScript, but I am encountering a call stack size error.

    function walk(meter) {
        if(meter < 0) {
            count = 0;
        } else if(meter <= 2) {
            count = meter;
        } else if(meter == 3) {
            count = walk(meter-1)+walk(meter-2)+1;
        } else {
            count = walk(meter-1)+walk(meter-2)+walk(meter-3);
        }
        return count;
    }


    console.log(walk(100));

Answer №1

To prevent exceeding the call stack size due to exponential complexity, you can utilize memoization to convert it into a polynomial one. This will optimize your code and reduce the time complexity to O(100).

let obj = {};
function climb(steps) {
        if (steps < 0) {
            count = 0;
        } else if (obj[steps] != undefined) {
            return obj[steps];
        } else if (steps <= 2) {
            count = steps;
        } else if (steps == 3) {
            count = climb(steps - 1) + climb(steps - 2) + 1;
        } else {
            count = climb(steps - 1) + climb(steps - 2) + climb(steps - 3);
        }
        obj[steps] = count;
        return count;
    }


console.log(climb(100));

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

Using a custom TypeScript wrapper for Next.js GetServerSideProps

I developed a wrapper for the SSR function GetServerSideProps to minimize redundancy. However, I am facing challenges in correctly typing it with TypeScript. Here is the wrapper: type WithSessionType = <T extends {}>( callback: GetServerSideProps&l ...

WebStorm displays all imported items as unused in a TypeScript backend project

https://i.stack.imgur.com/J0yZw.png It appears that the image does not display correctly for files with a .ts extension. Additionally, in .tsx files, it still does not work. In other projects using WebStorm, everything works fine, but those projects are o ...

Mongoose and ES6 promises are not delivering the expected results

I'm currently working on a piece of code that involves creating an array of promises to save specific numbers. The issue I'm facing is that when the output is printed, it displays the same record 10 times. Below is the code snippet: 'use s ...

Preventing the submission of a form using jQuery until all input, radio, select, and checkbox fields are filled out

I currently have a form that includes various field types, all of which must be filled out before submission. The submit button is disabled by default and I am looking to enable it once all fields are completed. I came across examples of this feature work ...

Tips for rearranging an item to the beginning of an array at index 0

What is the most efficient way to delete a specific object from an array and move it to the beginning? I have attempted using regular methods such as finding the index, manually splicing, and then moving the object to the top. farmer: [ { id:1, name: "na ...

Finding the scope of dynamically generated fields in AngularJS has proven to be quite challenging

I'm currently working on creating a dynamic form where users can add input fields by clicking a button. However, I am facing issues with fetching the value of the input field in the controller. Below is my form: <div ng-repeat="skill in skill_set" ...

The Iron Seal feature is ineffective when a user tries to log in

Iron.seal isn't properly updating the npm module Iron, which is causing login issues for users. var obj = { a: 1, b: 2, c: [3, 4, 5], d: { e: 'f' } }; var password = 'some_not_random_password_that_is_at_lea ...

Using iTextSharp in .Net to convert the action result into a downloadable pdf file via ajax

I have been successfully using iTextSharp to convert a razor view into a downloadable PDF via a C# controller. While the current implementation is functioning perfectly, I am seeking a way to transmit a model from a view to the PDF controller and enable th ...

Response coming from an ajax call in the form of a JSON

With the JSON string provided below: {cols:[{"id":"t","label":"Title","type":"string"},{"id":"l","label":"Avg ","type":"string"},{"id":"lb","label":"High","type":"string"},{"id":"lo","label":"Low","type":"string"}],rows:[{"c":[{"v":"Change navigation"},{"v ...

I am having trouble getting text to display properly in a jQuery Mobile dialog

I am attempting to dynamically set the header and button texts using JavaScript, but unfortunately it's not working as expected. To demonstrate the issue, I have added my code on jsfiddle: http://jsfiddle.net/tMKD3/8/. Here is the HTML code: <bod ...

Retrieving information using getStaticProps

I'm currently working on a new function that pulls data from The Guardian API, but I've hit a roadblock with an error message. Below is the response that's being returned: Furthermore, presented here is the code snippet for the asynchronous ...

Unlock the parent of an unnamed iframe

Here's a scenario: <div id="parent"> <iframe....></iframe> </div> If I had the above structure, I could use window.parent.document.getElementById('parent').innerHTML to access it. However, my current situation is di ...

Guide on transferring information from .ejs file to .js file?

When sending data to a .ejs file using the res.render() method, how can we pass the same data to a .js file if that .ejs file includes a .js file in a script tag? // Server file snippet app.get('/student/data_structures/mock_test_1', (req, res) = ...

The successful Ajax POST request does not result in an update to the JSON file

I am facing an issue with adding data to a *.JSON file. Despite receiving a "success" message from Ajax, the file remains unchanged. I have also noticed that when the JSON file is empty, nothing happens at all. Can someone help me find a solution? I'm ...

Different choice when utilizing Attribute="Value" in jQuery

When the button is clicked, my goal is to hide all elements and show only the Divs with the name attribute equal to the id of the button. I already know how to achieve this by getting elements by ID, but since I need multiple elements with unique IDs, or b ...

Tracking your daily nutrition using cronometer with the powerful combination of JavaScript

I'm currently developing a JavaScript cronometer in vueJS. I want the timer to start at 5 minutes (300 seconds) and then continue counting minutes and seconds. Although my cronometer is functioning, I am struggling to get it to start counting minutes ...

How can I fix the issue of clearInterval not functioning properly in an Electron JS application?

The clearInterval function is not working properly in this code. What can be done to fix this issue? var inter; ipcMain.on("start-stop",(err,data)=>{ console.log(data.data) function start(){ inter = setInterval(fu ...

Display the JSON boolean value on the webpage using Ajax and Jquery

After using Ajax with a GET request to consume a REST web service, I now have the results displayed in my console. Here are some images related to the REST API I am consuming: However, when attempting to print the results inside a table, only one result ...

Encountered a POST Error while attempting to access a backend function from the frontend in a React application, resulting in

I have developed a website using React for the frontend and Node.js Express for the backend. However, I am facing an issue where calling a backend function from the frontend takes around 2 minutes and results in the following error being displayed in the c ...

Issue with jQuery in Internet Explorer causing difficulties loading images

I'm experiencing an issue with my website where all the images load on top of each other when the site is first loaded, creating a chaotic mess. The desired functionality is for the images to remain invisible until specific words are clicked, which is ...