The recursion function within the map is not defined

My coding challenge involves the following logic:

export const normaliseHistoryLog = history => {

    if (history.children.length === 0) {
        debugger;
        return {
            id: history.id,
            date: history.timestamp, 
            time: history.timestamp,
            event: history.event.label,
            eventHTML: getHTML(history.event.detail), 
            source: history.source,
            requestor: history.requestor
        }
    }
    debugger;
    return {
        id: history.id,
        date: history.timestamp, 
        detail: history.children.map(normaliseHistoryLog),
        time: history.timestamp,
        event: history.event.label,
        eventHTML: getHTML(history.event.detail), 
        source: history.source,
        requestor: history.requestor
    }
}

I encountered an error message related to this line of code:

detail: history.children.map(normaliseHistoryLog),

The error indicated that 'normaliseHistoryLog' is undefined.

To troubleshoot, I experimented with the following approach:

detail: history.children.map((el) => normaliseHistoryLog(el))

However, this alternative did not resolve the issue.

This function is utilized within another function as shown below:

export const getHistory = asyncMiddleware(async (req) => {
    const path = `url`;
    const response = await get(req, path);
    debugger;
    return response.result.map(normaliseHistoryLog);
});

In this scenario, 'response.result' contains an array of objects.

Answer №1

In summary;

function standardizeHistoryLog(history) {
    if (history.children.length === 0) {
        debugger;
        return {
            id: history.id,
            date: history.timestamp, 
            time: history.timestamp,
            event: history.event.label,
            eventHTML: getHTML(history.event.detail), 
            source: history.source,
            requestor: history.requestor
        }
    }
    debugger;
    return {
        id: history.id,
        date: history.timestamp, 
        detail: history.children.map(standardizeHistoryLog),
        time: history.timestamp,
        event: history.event.label,
        eventHTML: getHTML(history.event.detail), 
        source: history.source,
        requestor: history.requestor
    }}
    export function standardizeHistoryLog;

The reason for this behavior is due to hoisting. The method in which you defined the function standardizeHistoryLog is known as a function expression. Function expressions - where functions are assigned to variables - are processed at a later stage even when they are exported. Consequently, the function may not be usable at the time the closure is generated (during declaration and assignment).

To delve deeper into this concept, consider researching hoisting in JavaScript. One helpful resource on this topic can be found here:

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

What are the best techniques for organizing SCSS in Next.js?

There are multiple pages with some unused items. Is there a method to search and delete all the items based on their classname? Appreciate any assistance you can provide! ...

AngularJS supports asynchronous validation on blur

Using Angular JS version 1.5.6, I am looking to implement asynchronous input validation that occurs only on blur. However, I am unable to use modelOption: {debounce: 500} or modelOption: {updateOn: 'blur'} due to the directive being used with oth ...

How can I use Ajax to populate a div with data from a php script?

Is there a straightforward method to populate a div by fetching a PHP script (and sending data like POST or GET) to determine what data should be returned? I'm searching for a solution that doesn't rely on a library... All I seem to come across ...

What is causing my page to automatically refresh whenever I click on buttons?

The code snippet below shows the structure of my webpage : HTML : <button class="add-col"><i class="fas fa-columns"> Add a column</i></button> <div class="table-responsive"> <table class="table"> ...

Tips for troubleshooting JavaScript within an embedded V8 environment

Currently, I am endeavoring to grasp the functioning of the Debug object in V8 for debugging javascript within an embedded-javascript C++ application. After invoking v8::Debug::SetDebugEventListener and specifying a callback function, I proceed to execute ...

Error in typescript: The property 'exact' is not found in the type 'IntrinsicAttributes & RouteProps'

While trying to set up private routing in Typescript, I encountered the following error. Can anyone provide assistance? Type '{ exact: true; render: (routerProps: RouterProps) => Element; }' is not compatible with type 'IntrinsicAttribu ...

What is the purpose of using double % in Java or JSP?

Yesterday, while reviewing some code, I came across a line that seemed very peculiar to me. In a JavaScript function, there is a condition checking for a string passed as a parameter in the following manner: "%%unsubscribe%%". See the snippet below for re ...

Clear the cache in Angular to remove the page

Within my current project, I am utilizing angular's $routeProvider to dynamically load pages into an ng-view section. The loaded pages are displaying correctly in the ng-view and are being cached for quick access without needing to make a new server r ...

What is the best way to choose the member variables in this specific data structure?

I have been assigned the task of retrieving the cities from various countries, but I am unsure of the best approach to do so. How can I easily extract city names like: For example, for USA it would be NYC and SFO. I attempted using the code snippet cityD ...

Implementing res.render in an asynchronous fashion

My nodejs application is facing a bottleneck with the res.render method of express, which takes about 400 ms in a blocking manner. I'm looking for ways to handle this so it can execute in a non-blocking way. Running Apache benchmark on my setup shows ...

Deactivate a single choice within the select field while allowing the rest to remain active

I am facing a challenge where I have two select elements with the same options. My goal is to disable an option in one select element if it has already been selected in the other select element. Below are my two select elements: <select class="form-co ...

The POST variable is empty when attempting to stringify with Ajax using JSON

I'm attempting to serialize an HTML form and send it using jQuery with a POST action. Below is the current jQuery code I am using: var dataToSend = { 'name': 'person', 'description&apos ...

Serialization of select value in Ajax/PHP form submission

Currently, the form is sending the correct information but it is missing the state field. The issue arises because the value of the state field is not fixed and depends on the selected state. How can I address this? JS: $('#sendFormBtn').live(& ...

the deactivation of my rollover class is being caused by my float class

With the assistance of a generous contributor on stackoverflow, I was able to overlay different colored CSS boxes onto various images. These boxes could be removed upon mouseover, revealing the images beneath. You can view the code I used on fiddle here. ...

Having trouble accessing the POST RESPONSE json in ReactJS and NodeJS

I have set up my own API server that is connected to a MySQL database. Whenever I send a request to the server, everything seems fine. I can see the input from the browser and the output from the database in the console. However, I am unable to see any new ...

Locate elements based on an array input in Mongoose

Define the Model: UserSchema = new Schema({ email: String, erp_user_id:String, isActive: { type: Boolean, 'default': true }, createdAt: { type: Date, 'default': Date.now } }); module.export ...

Using Angular: Dynamically load an external JavaScript file after the Component View has finished loading

In my Angular 5 application, I am faced with the challenge of loading a JavaScript script file dynamically after my component view has been fully loaded. This script is closely related to my component template, requiring the view to be loaded before it ca ...

What is the axis associated with the angle phi in THREE.OrbitControl?

phi is an angle that relates to which axis in the THREE.OrbitControl code snippet provided below? phi += phiDelta; // Ensure phi stays within specified limits phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, phi ) ); I believe that thet ...

The PrimeReact components are not displaying the PrimeReact theme properly

I'm currently working on integrating a Menubar component from PrimeReact into my React application. I tried to apply one of the predefined PrimeReact themes by importing it, but the page ended up looking strange. When I imported "./../../node_modules ...

Providing a tar.gz file for downloading in a node.js application

I have a tar.gz file stored on a nodejs server and I am trying to make it downloadable from another nodejs application. While I have been successful in downloading txt and jpeg files, I am facing issues with the tar.gz file as it appears empty once downloa ...