What's the best way to create a JavaScript function that keeps track of its call count?

I’m trying to make a JavaScript function that can count how many times it’s been called. Here’s what I want it to do:

console.log(countCalls()()); // should show '2'
console.log(countCalls()()()); // should show '3'
console.log(countCalls()()()()); // should show '4'

How can I write countCalls() to work like this? I tried something like:

countCalls.count = 1;
function countCalls() {
  countCalls.count++;
  return function() {
    return countCalls.count;
  };
}

But it doesn’t quite work right. When I do:

let result = countCalls()()()();
console.log(result); // This gives me a number, not a function

It’s different from what I want:

console.log(countCalls()()()()); // This should work and print the count

Any ideas on how to fix this? I’m pretty stuck!

hey, i think i got a simple solution for ya. try this:

function countCalls() {
let count = 1;
const f = () => (++count, f);
f.toString = () => count;
return f;
}

it uses a closure to keep track of calls. the comma operator lets us increment and return f in one go. should work like u want!

I’ve wrestled with this exact problem before, and I think I’ve got a solution that might work for you. The key is to use a closure to maintain the count state and return a function that both increments the count and returns itself. Here’s what I came up with:

function countCalls() {
  let count = 1;
  function counter() {
    return ++count;
  }
  counter.toString = () => count;
  return counter;
}

This approach uses a closure to keep track of the count, and it overrides the toString method to return the current count when the function is coerced to a string (which happens when you log it).

I’ve tested it, and it works exactly as you described:

console.log(countCalls()()); // 2
console.log(countCalls()()()); // 3
console.log(countCalls()()()()); // 4

The beauty of this solution is that it maintains the count across multiple calls and still returns a function each time, allowing for that chained calling pattern you’re after. Hope this helps solve your problem!

I’ve encountered this challenge before, and here’s a solution that should work for you:

const countCalls = (() => {
  let count = 1;
  const f = () => {
    count++;
    return f;
  };
  f.toString = () => count;
  return f;
})();

This uses an Immediately Invoked Function Expression (IIFE) to create a closure. The count variable is private, and the returned function increments it each time it’s called. The toString method is overridden to return the current count.

This approach maintains state between calls and allows for the chaining you’re looking for. It should work exactly as you’ve described in your examples. Give it a try and let me know if you need any clarification!