Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Write a once() function with closures in JavaScript

63 Returning a function: a counter and once

fair

Write makeCounter(start, step) that returns an object of small functions closing over a private count, and prove two counters do not share it. Then write once(fn) so that a charge can only be taken one time however often it is called.

Stuck? Three hints, smallest first
  1. 1. The variable declared in the outer function is the private state. The returned functions are the only way to reach it.
  2. 2. Every call to the factory makes a new variable, so two counters are genuinely separate.
  3. 3. once needs two pieces of state: whether it has run, and what it returned that time.

The answer

const makeCounter = (start = 0, step = 1) => {
  let count = start;                          // private: no other way in
  return {
    next: () => (count += step),
    peek: () => count,
    reset: () => { count = start; return count; },
  };
};

const once = (fn) => {
  let called = false;
  let result;
  return (...args) => {
    if (called) return result;
    called = true;
    result = fn(...args);
    return result;
  };
};

let charges = 0;
const charge = (kobo) => { charges++; return `charged ${kobo}`; };
const chargeOnce = once(charge);

const ticket = makeCounter(100);
const other = makeCounter(100);
const threeInARow = [ticket.next(), ticket.next(), ticket.next()];
const otherUntouched = other.peek();
const afterReset = [ticket.reset(), ticket.next()];
const inFives = (() => {
  const c = makeCounter(0, 5);
  return [c.next(), c.next()];
})();

const results = [chargeOnce(500), chargeOnce(999), chargeOnce(1)];
const exposed = Object.keys(ticket);
const shared = ticket.next === other.next;

console.log('three pulls :', threeInARow, '| the other counter:', otherUntouched);
console.log('reset       :', afterReset, '| step of five:', inFives);
console.log('once        :', results, '| the wrapped function ran', charges, 'time(s)');
console.log('what is public:', exposed, '| count reachable?', ticket.count);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('each call advances the captured count', threeInARow, [101, 102, 103]);
test('a second counter has a count of its own', otherUntouched, 100);
test('reset puts it back to the start', afterReset, [100, 101]);
test('the step is captured just as the start is', inFives, [5, 10]);
test('once returns the first result to every later caller', results, ['charged 500', 'charged 500', 'charged 500']);
test('so the side effect happened exactly once', charges, 1);
test('and the later arguments were never even looked at', results[1], 'charged 500');
test('only the functions are public', exposed, ['next', 'peek', 'reset']);
test('the count is nowhere on the object, and not shared between counters', [ticket.count === undefined, shared], [true, false]);

A closure is a function plus the variables it was born next to. count outlives makeCounter because next, peek and reset still refer to it, and nothing else in the program can name it — privacy with no #, no WeakMap and no convention. The price is per-instance functions, the same cost as the arrow field in exercise 50, which is why a class with #count is the better choice when there will be thousands of counters.

once is the smallest useful higher-order function: it takes a function and returns a function, and its two closed-over variables are the whole implementation. Two details in the assertions are deliberate. It caches the result, so later callers get the first answer rather than undefined. And it ignores later arguments completely, which is a real trap — chargeOnce(999) looks like it should charge 999 and quietly does nothing at all. If that would be a bug, throw on the second call instead of returning the cached value.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.