Is there a way to transform this recursive function into an iterative one? (utilizing var_dump in JavaScript)

Recently, I've been exploring the process of converting a recursive function into an iterative one.

After researching on this topic for several days, I came across some informative websites that provided me with new ideas to experiment with. However, I haven't yet been able to find a working solution.

Here is the original code that I am attempting to transform:


function dump(value, recursionLevel) {
  // Initial check for recursion level.
  if(!recursionLevel) {
    recursionLevel = 0;
  }
  
  var vType = typeof value;
  var out = vType;
  
  switch (vType) {
    case "number":
    case "boolean":
      out += ": " + value;
      break;
    case "string":
      out += "(" + value.length + '): "' + value + '"';
      break;
    case "object":
      // Check if null.
      if (value === null) {
        out = "null";
      } else if(Array.isArray(value)) {  
        out = 'array(' + value.length + '): {\n';
        
        // Loop through array elements.
        for(var i = 0; i < value.length; i++) {
          out += '  '.repeat(recursionLevel) + "   [" + i + "]:  " + dump(value[i], recursionLevel + 1) + "\n";
        }
        out += '  '.repeat(recursionLevel) + "}";
      }
      break;
  }

  return out;
}

I'm facing difficulties in particular with the conversion due to the presence of a for loop. Any assistance or guidance would be greatly appreciated.

Thank you for your help!

EDIT:

Below is the final outcome after transforming the code:

Recursive version:


// Recursive implementation has been done.
// Code preserved for future reference.

Iterative version:


// Iterative transformation completed successfully.
// Replaced original code with iterative version.

Iterative version accepting multiple parameters:


// Revised the function to handle multiple arguments.
// Implementation successful and operational.

Testing script:


// Created a testing function to validate transformations.
// Tests passed successfully.

NOTES:

Original source of the code referenced:

  • What is the JavaScript equivalent of var_dump or print_r in PHP?

The structure of the code shared here closely resembles another similar resource:

Answer №1

It seems like the type of challenge typically assigned for homework. To tackle this, a stack will be required. In JavaScript, stacks can be implemented using arrays as they come equipped with the necessary push() and pop() methods.

Below is a basic program written in JavaScript that performs a dump operation in a form resembling JSON (though not entirely). Adapting the output format to suit your specific requirements is an exercise left to the user.

function dump(value) {
   var stack=[{value:value}];
   var out = "";
   while (stack.length>0) {
     var entry = stack.pop();
     if (entry.output) {
       out+=entry.output;
     }
     else {
       value = entry.value;
       switch(typeof value) {
         case "number":
         case "boolean":
           out += value;
           break;
         case "string":
           out += '"'+value+'"';  // take caution with strings containing "
           break;
         case "object":
           if (value === null) {
              out += "null";
           }
           else if (Array.isArray(value)) {
              out += "[";
              stack.push({output:"]"});
              for (var i=value.length-1; i>=0; i--) {
                 stack.push({value: value[i]});
                 if (i>0) {
                   stack.push({output:","});
                 }
              }
           }
           else {
              out += "{";
              stack.push({output:"}"});
              var s = "";
              var f;
              for (f in value ) {
                 if (s) {
                   stack.push({output: s});
                 }
                 stack.push({value: value[f]});
                 stack.push({output: f+":"});
                 s = ",";
              }
           }
           break;
       }
     }
   }
   return out;
}

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

Steering clear of conditional statements in a straightforward transformation process

Looking for an alternative to using an IF statement in this mapping function: X Y 1 11 2 10 3 9 4 8 5 7 6 6 7 5 8 4 9 3 10 2 11 1 12 12 The relationship is represented by the equation Y = (12 - X), except when X = 12, then Y = 12. ...

Schema Error - ReferenceError: Phone variable is undefined

I'm encountering a slight issue while working on a CRUD API using node.js and express. After making a POST request to my API, I'm receiving an error message saying "ReferenceError: Phone is not defined". // server.js // BASE SETUP // ========= ...

Do I need to include the title, html, and head tags in a page that is being requested via ajax

I have a page called welcome.htm that is being loaded into another page using ajax. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xh ...

Using Jquery to activate a vertical scrolling bar

Within my div, I have a tree view that extends beyond the size of the div, causing a vertical scroll bar to appear on the right side. When users click a button outside of the div, I want the page to scroll to a specific item within the div (which I know th ...

Is it possible to employ variable data outside the function?

As a newcomer to programming, I understand that variables inside a function cannot be accessed outside of it. However, I am in need of the object stored in 'call'. Is there any way to extract data from this object? I have attempted declaring &ap ...

Validation of 'e' Symbol in Input Type Number Using jQuery Validator

Hey everyone, I'm currently utilizing jQuery validator for an input field with the type of number. However, when I enter 1e1, it shows an error message saying "invalid number." Is there a way to allow numbers like 1e1 (which equals 10) without trigger ...

Creating visual content using Webpack and Angular2

I have a small Angular2 app that utilizes Webpack for project building and scaffolding. One issue I've encountered is the inability to load images specified in TypeScript files during production. After running npm run build, I noticed that these imag ...

Is it possible to use multiple routes in the same page with Vue-router?

In the process of developing a Vue-based web application that utilizes vue-router in history mode, everything was functioning smoothly for navigating between various pages. However, a new request has been made to open certain pages within a virtual dialogu ...

Utilizing Rails for dynamic form validation with AJAX

As someone who is new to jQuery, AJAX, and JavaScript in general, I am facing a challenge with front-end validation for a Rails form that utilizes an ajax call to query the server. The validation works fine when I am debugging, giving enough time for the A ...

What is the reason behind being able to assign unidentified properties to a literal object in TypeScript?

type ExpectedType = Array<{ name: number, gender?: string }> function go1(p: ExpectedType) { } function f() { const a = [{name: 1, age: 2}] go1(a) // no error shown go1([{name: 1, age: 2}]) // error displayed ...

Executing multiple functions in a for loop using PHP

Is it possible to use functions within a for loop in PHP? I have multiple databases that are identical and I want to establish connections for each one using a loop (35 databases in total). However, I am struggling with creating dynamic function names wi ...

Touchwipe incorporation - single-page website script

Today has been dedicated to troubleshooting and searching for a solution regarding the integration of TouchWipe () on a custom one-page-site script based on Parallax that I found perfect for my latest project (). The script itself performs beautifully wit ...

Issue with ng-model in ng-repeat not functional

I need assistance with setting the ng-model for answer option checkboxes in a list of questions and options. I am currently using two ng-repeat directives to display the questions and options, but I'm unsure how to set the ng-model to capture all sele ...

Implementing socket.io in a node.js server with express to showcase a welcome message upon user login

Currently, I am in the process of creating a web chat client using socket.io. However, before I can proceed with this project, I need to establish communication between my server and the website on localhost. Despite receiving the 'listening' me ...

Invoking functions from a JS file that has already been loaded

I am currently utilizing jQuery for my project. Within a JS file named super.js, I have the following code: $("#content").load("/profile"); function setHash(hash) { location.hash = "#/:-)/"+hash; } The "/profile" path is used to load an external JS f ...

Utilizing media queries to customize the appearance of a jQuery accordion widget

Hello, I'm struggling with implementing a jQuery accordion for mobile platforms that destroys itself on larger screens. While my code is mostly working, I've encountered two issues: The accordion only gets destroyed when the window is resized ...

I'm having trouble with res.redirect, why isn't it redirecting me as expected?

In my login controller, I have a form that updates the user's scope when they click a button triggering the login() function. .controller('loginCtrl', ['$scope','$http',function($scope,$http) { $scope.user = { ...

Results don't align with search parameters

const searchClientes = (event) => { if (event.target.value === '') { getClientes(); return; } else { const searchTerm = event.target.value; const filteredClients = clientes.filter(cliente => { return cliente.nome ...

Looking to display a JSON-based menu using AngularJS?

Having trouble displaying a dropdown menu when trying to print a menu from a JSON file. https://i.sstatic.net/fNLxw.png JSON Data [{ "Option": "Request", "Name": "<a href=\"#/request\"><i class=\"material-icons left\ ...

Store the advertisement click into the database utilizing PHP, subsequently access the provided hyperlink

I am developing a custom WordPress widget that displays advertisements. I want to track clicks on these ads and store the data in a database. The database table for click tracking is already set up, and I have a function called f1_add_advert_click($advert ...