Track the number of function calls using closure and function attribute

Recently, I encountered an issue while trying to track how many times a particular JavaScript function got called. The approach of adding an attribute to the function worked perfectly fine for keeping count, but surprisingly, I faced difficulty when attempting to access this count value from outside the function. Why is it that g.n doesn't return 2 in my scenario?

var keepCount = function (fn) {
  fn.calls = 0

  return function () {
    fn.calls++;
    console.log('Function was executed ' + fn.calls + ' times')
    return fn.apply(null, arguments)
  }
}

var func1 = function (x) { return x };
var func2 = keepCount(func1)

console.log(func2(1));  // Function was executed 1 time, returns 1
console.log(func2(2)); // Function was executed 2 times, returns 2 
console.log(func2.calls); // Undefined

Answer №1

To ensure the counter is saved correctly, assign it to the newly formed function instead of the original one.

let countFunction = function (func) {
  function wrapped () {
    wrapped.counter++;
    console.log('Number of calls: ' + wrapped.counter);
    return func.apply(null, arguments)
  };
  
  wrapped.counter = 0;
  
  return wrapped;
}

let addOne = function (num) { return num + 1 };
let addToCounter = countFunction(addOne)

console.log(addToCounter(3)); // Number of calls: 1
console.log(addToCounter(7)); // Number of calls: 2
console.log(addToCounter.counter); // 2

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 you prevent "hits" from being displayed on the screen until the searchBox is utilized in React InstantSearch?

I am currently implementing React InstantSearch in Algolia and I am trying to configure it to hide the "hits" component by default, only displaying it when the searchBox is clicked. My initial research led me here: Although I was able to implement the qu ...

What is the best way to retrieve the value from a PHP request?

I am encountering an issue with a multiselect form field named properties[]. When I attempt to retrieve the values in my controller using dd($request->get('properties')), it gives me ["1,2"]. However, trying to access the first ele ...

Angular routing does not properly update to the child's path

I've organized my project's file structure as follows: app/ (contains all automatically built files) app-routing.module.ts components/ layout/ top/ side/ banner/ pages/ ...

Creating a fade in or fade out effect in AJAX without using jQuery is a simple yet

Is there a simple way to achieve fade in or fade out effects in ajax without relying on jQuery? I'm looking for a solution that can add color or background color to make it visually appealing, especially for small web pages with poor internet connecti ...

Encountering difficulties loading .mtl and .obj files using react-three-renderer

I'm currently utilizing react-three-renderer to load .obj and .mtl files, but I'm encountering difficulties in rendering the model. Instead, a cube is being rendered inside the div. My goal is to replace the cube with my desired .obj model. Inst ...

Is there a way to efficiently transform an 'Array of Objects' with values 'Array of Object' into an array of Objects with individual array values using JS/lodash?

I utilized the lodash library to divide arrays into chunks (batches). let values = { 'key1' : [lotsOfValues1], 'key2' : [lotsOfValues2] }; let keys = ['key1', 'key2']; let arrObj = []; keys.forEach((key) => ...

Exploring various data promises in AngularUI router

I am attempting to utilize the $q service to resolve multiple promises using the $q.all() function with AngularUI router. However, I am encountering issues where it is failing or not functioning as expected. This snippet is from my configuration file that ...

Having trouble with setting up the next image configuration for graphcms' images

I've been using graphcms solely for my image assets and trying to integrate them into my Next JS (v12.0.1) frontend. However, I keep getting the error message hostname not configured in next.config.js, even though I have already specified it in my nex ...

Can you explain the significance of the role attribute being set to "button"?

While browsing through the Google+ Project's page, I noticed that all the buttons were created using div elements like: <div role="button"></div> I'm curious to know if this is done for semantic reasons or if it has an impa ...

Toggle Class Based on Scroll Movement

I am currently designing an HTML page that includes a small navigation bar located halfway down the page. I am aiming to have this navigation bar stick to the top of the page (become fixed) once it reaches the top. Here is the code I have tried: The scrip ...

Using git mv in VSCode does not automatically adjust TypeScript / JavaScript import paths

Is there a way to successfully move a typescript file in VSCode to achieve both of the following: Ensure Git acknowledges the file continuity Have VSCode update the parent files' import statements I have tried two methods, but each one falls short: ...

Incorporating an external HTML page's <title> tag into a different HTML page using jQuery

I am faced with a challenge involving two files: index.html and index2.html. Both of these files reside in the same directory on a local machine, without access to PHP or other server-side languages. My goal is to extract the <title>Page Title</ ...

working with html data in a bootstrap modal using javascript

Utilizing an id, I pass data to a bootstrap modal and link that id with stored data. $("#fruit").html($(this).data("fruit")); In addition, I am appending data to the bootstrap modal $('#mymodal').find('.modal-body').append('< ...

multer - the file uploaded by the request is not defined

I've been working on an app with Node, Express, and multer for image uploads. However, after submitting the form, req.file is coming up as undefined. I've spent hours trying to troubleshoot this issue but haven't been able to pinpoint the pr ...

The Delay in Meteor's Data Transfer between Publish and Subscription

I am utilizing d3 to visualize a compilation of meteors (Hostiles) on an image based on their x and y coordinates. This process is successful for me. However, I have a publish function that verifies the user's login status to determine if they are an ...

Encountering an issue with JQuery when attempting to create a double dropdown SelectList. Upon submitting the POST request, the output received is always

Two dropdownlists have been created, where one acts as a filter for the other. When selecting a customer from the dropdown Customer, only a limited set of ClientUsers is displayed in the dropdown ClientUser. This functionality is achieved using a jQuery fu ...

A JavaScript function that smoothly scrolls an element into view while considering any scrollable or positioned parent elements

I needed a function that could smoothly scroll a specific element into view with some intelligent behavior: If the element is a descendant of a scrollable element, I wanted the ancestor to be scrolled instead of the body. If the element is within a posit ...

Issues encountered with certain Tailwind styles functioning improperly when deployed in a production environment with Next.js

It seems that there are some style issues occurring in the production build hosted on Netlify for a specific component. The problematic component is a wrapper located at ./layout/FormLayout.tsx. Below is the code for this wrapper: const FormLayout: React.F ...

What is the process for interacting with a Node.js Web API using an Angular JS API?

Seeking assistance with converting HTML into JADE format, encountering issues with {{record.name}} not functioning correctly. This is preventing the fetching and printing of values. Below are the complete file details: Directory view can be seen here. JS ...

Accessing cell values within a table using JavaScript

I am having some trouble with extracting unique IDs from the input text areas in the first column of an HTML table. These IDs are dynamically assigned using JavaScript. Can someone help me with this issue? Below is the HTML code for my table: <table id ...