The recursion in the Lodash function has gone beyond the stack size limit

The objective

I have set out to develop a unique "deepMapValues" function. This function is designed to take a specified function and an object, apply the function to each value in the object deeply, and return the modified object accordingly.

(v, k) => k == 'hello' ? 'world' : v;
// If key is 'hello', replace its value with 'world'; otherwise, retain the original value.

For instance, given the following object...

{
  hello: true,
  foo: {
    hello: 'bar'
  }
}

The function should transform it into...

{
  hello: 'world',
  foo: {
    hello: 'world'
  }
}

This transformation can be achieved by utilizing the function as follows:

deepMap(mapFunction)(inputObject)

The existing function

To implement this functionality, I initially created a small function using lodash library that leverages mapValuesWithKey method.

const mapValuesWithKey = _.mapValues.convert({ 'cap': false });

deepMap = fn => mapValuesWithKey(
  _.cond([
    [_.isArray, _.map(deepMap(fn))],
    [_.isPlainObject, deepMap(fn)],
    [_.T, fn],
  ])
);

Upon executing this function, I encountered a crash with the error message:

RangeError: Maximum call stack size exceeded

Although expected due to recursive nature, simplifying the function resolved the issue temporarily for testing purposes.

Nevertheless, reintroducing recursion within the code led to the same crashing scenario despite no actual recursion occurring.

To address this recurring problem, I attempted to recreate my own version of the cond function from lodash called myCond. However, even this alternative solution failed to prevent the crash.

At this point, I am uncertain about the root cause of the issue and seek guidance on rectifying the situation while maintaining the passage of the fn parameter through the recursion loop.

Rubber Duck EDIT

A likely explanation for the persistent error could be the continuous evaluation and generation of objects within the cond pair, leading to an endless cycle of recursions involving the fn parameter.

Further inquiry

If the above assumption holds true, what measures can be taken to mitigate the error without disrupting the flow of fn during recursion?

Answer №1

Upon reaching the conclusion of my question, I came to a realization. The recursion is not occurring during the execution of functions with the object as input, but rather in the generation of condition pairs in the initial phase.

I made adjustments to the code like this...

deepMap = fn => _.mapValues(
  _.cond([
    [_.isArray, _.map(obj => deepMap(fn)(obj))],
    [_.isPlainObject, obj => deepMap(fn)(obj)],
    [_.T, fn],
  ])
);

This update resolved the issue. Now, the fn is only passed into deepMap after the condition has been evaluated and the function needs to be executed.

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

How can I ensure that the appropriate 'this' is accessed within a callback function for an AJAX request?

When working with a callback function, I am having trouble accessing this. Instead, it seems to be pointing to the AJAX object rather than the object that initially invoked the onClickEmail function. I attempted to store a reference in a variable called th ...

Node.js: Attempting to arrange ISO dates based on their time span

I am currently working on creating a line chart using the chart.js library. In order to do this, I have an array that contains ISO dates and my goal is to determine which ISO dates belong to the same hour and day. This information will then be used to gene ...

Error Alert: Express configuration encounters Unforeseen character <

This is how I have set up my Express: const express = require('express'); const app = express(); app.use(express.static('public')); app.get('*', function (req, res) { res.sendfile('dist/index.html'); }); app.li ...

Should the use of readFileSync() during the initialization of a Node.js web application be avoided?

I have a Node app that serves web pages with static HTML-snippet files included conditionally. I am considering implementing a cache map for these snippets by adding the following code to my Express's app.js file: var cache = Object.create(null); cac ...

apply a visible border to the item that is clicked or selected by utilizing css and vue

I have a list of items that I want to display as image cards with an active blue border when clicked. Only one item can be selected at a time. Below is the code snippet: Template Code <div class="container"> <div v-for="(obj ...

Javascript Popup Functionality Failing to Execute

It seems that the popup link does not function properly when placed between the <script> tags. if(data.userdata["money_back"] == 1){ chat_list += '<a data-popup-open="popup-90">Download</a>'; } On the other hand, when the pop ...

VueJS emits a warning when filtering an array inside a for loop

I'm encountering an issue with my filtering function in VueJS. While it works fine, I am seeing a warning message in the console. You can check out this example to see the problem. The problem arises when I need to filter relational data from a separ ...

"Troubleshooting issue with setAttribute not functioning properly when used with onClick in

A new variable named "navBtn" is created by utilizing document.createElement("span") to generate a span element. However, for unknown reasons, applying setAttribute to this span is not functioning as expected. The navBtn variable resides within its own fun ...

Discovering the Javascript Code Executing on a <span> element with the Help of Chrome Inspector or Firebug

I have encountered a situation where a website is dynamically generating information into <span></span> tags using jQuery. The span has a class of "Price" and an id corresponding to a Product Code, with the data being pulled from a JSON data sh ...

When Ajax sends an HTTP Get request to an MVC Controller with a complex JSON object as a parameter, the controller receives it as null

I am currently working with three classes: public class MainSearch { public MainSearch() { SearchData searchData = new SearchData(); SearchMode searchMode = new SearchMode(); } public SearchData searchData { get; set; } ...

Calculating minutes per hour during a specific date range using JavaScript

What is the method to create an array representing minute counts per hour within a specified date range? If we have the following dates: const initial = new Date('2019-04-04 12:14'); const final = new Date('2019-04-04 16:21'); How ca ...

Stopping XSS Attacks in Express.js by Disabling Script Execution from POST Requests

Just starting to learn ExpressJs. I have a query regarding executing posted javascript app.get('/nothing/:code', function(req, res) { var code = req.params.code; res.send(code) }); When I POST a javascript tag, it ends up getting execut ...

The SkyBox in THREE.js is a visually stunning feature that

I've been trying to create a SkyBox in THREE.js, following some tips I found online. However, none of the methods seem to work for me. I have double-checked the file paths and image paths, so I'm not sure what's causing the skybox not to app ...

The Select2 widget passes parameter term spaces to the ajax request as a plus sign "+" instead of %20

I have been working on an application that connects to SAP's service layer and retrieves data using REST APIs. I am using the popular widget select2, but I have encountered a problem. The API query that needs to be made contains a space character arou ...

Finding the minimum value in a list and the maximum value in JavaScript

My current JavaScript list consists of dollar coin values: let x = [1.0, 2.5, 5.0, 20.0, 50.0, 100.0, 500.0, 2000.0, 5000.0] My challenge is finding an equation in JavaScript that will allow me to use the smallest number of coins to reach the desired max ...

Having trouble with Selenium WebDriverJS on both FireFox and Internet Explorer

Having developed multiple JavaScript tests using chromedriver to run them in Chrome, I am now facing the challenge of running these same tests in FireFox and IE. The test below is functional in Chrome: var assert = require('assert'), test = requ ...

The JQUERY Click event fails to trigger only on the initial click

While attempting to display the name stored as a data value for each button in the code, I encountered an issue where it wouldn't work on the first click event call. However, after the initial click, it operated normally. It is important to note that ...

"Utilizing Bootstrap Modal for efficient AJAX saving of multiple records with the help of bootstrapValidator

I'm encountering an issue with a bootstrap modal form and validation using bootstrapValidator. The problem I'm facing is that when I open the modal, fill out the fields, close it, reopen it, refill the fields, and submit the form, my script inser ...

Create your own custom block on the frontend product page

I am trying to create a custom block on the Product Page of my Magento store. I attempted it like this: Magento- How can i add a new custom block in product details page using module Unfortunately, it did not work as expected. Did I make any mistakes he ...

Implementation of internationalization into a JSON-formatted data file

I recently integrated i18n into my application and I'm facing a challenge with implementing the useTranslation(); function in my navbar data file. This file serves as the database for the page titles and tabs, and I'm unsure about how to proceed. ...