Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

before() and after() function wrappers in JavaScript

102 before and after, two counting wrappers

fair

Write before(n, fn), which calls fn for the first n - 1 calls and then returns the last result it got, and after(n, fn), which stays quiet until the nth call. Show that before(2, fn) is once, that each wrapper carries its own counter, and what the quiet calls actually return.

Stuck? Three hints, smallest first
  1. 1. Both are a closure over a call count. The only difference is which side of the comparison calls the wrapped function.
  2. 2. before has to remember the last result, because it still has to return something once it stops calling through.
  3. 3. Think about what after returns on the calls it swallows, and what that value looks like once it is inside an array being stringified.

The answer

const before = (n, fn) => {
  let calls = 0;
  let last;
  return (...args) => {
    calls++;
    if (calls < n) last = fn(...args);
    return last;
  };
};

const after = (n, fn) => {
  let calls = 0;
  return (...args) => {
    calls++;
    return calls >= n ? fn(...args) : undefined;
  };
};

let discounts = 0;
const applyDiscount = (amount) => {
  discounts++;
  return Math.round(amount * 0.9);
};
const firstTwoOrders = before(3, applyDiscount);
const prices = [firstTwoOrders(10000), firstTwoOrders(20000), firstTwoOrders(30000), firstTwoOrders(40000)];
const discountsRun = discounts;

let alerts = 0;
const raiseAlert = (reason) => {
  alerts++;
  return `alert: ${reason}`;
};
const afterThree = after(3, raiseAlert);
const outcomes = [afterThree('timeout'), afterThree('timeout'), afterThree('declined'), afterThree('bounced')].map((v) => v ?? 'quiet');
const alertsRun = alerts;

let charges = 0;
const charge = (amount) => {
  charges++;
  return amount;
};
const onceLike = before(2, charge);
const onceResults = [onceLike(500), onceLike(900), onceLike(1300)];
const chargesAfterOnce = charges;

const perOrder = before(2, charge);
const perRider = before(2, charge);
const twoWrappers = [perOrder(1), perRider(2)];
const chargesTotal = charges;

const swallowed = after(2, () => 'ran')('first call');
const swallowedShape = [swallowed === undefined, JSON.stringify([swallowed])];

console.log('before(3) :', prices, '| real calls:', discountsRun);
console.log('after(3)  :', outcomes, '| real calls:', alertsRun);
console.log('once      :', onceResults, '| real calls:', chargesAfterOnce);
console.log('swallowed :', swallowedShape);

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('before(3) calls through on the first two calls', prices.slice(0, 2), [9000, 18000]);
test('after that it returns the last result it got, not "no discount"', [prices[2], prices[3], prices[2] === prices[1]], [18000, 18000, true]);
test('so the wrapped function ran exactly twice, and later arguments were thrown away', discountsRun, 2);
test('before(2) is once: one real call, three identical answers', [onceResults, chargesAfterOnce], [[500, 500, 500], 1]);
test('after(3) stays quiet until the third call, then keeps going', outcomes, ['quiet', 'quiet', 'alert: declined', 'alert: bounced']);
test('and it forwards its arguments, so the third call decided the message', alertsRun, 2);
test('each wrapper closes over its own counter, so two wrappers are independent', [twoWrappers, chargesTotal], [[1, 2], 3]);
test('a swallowed call returns undefined, which JSON turns into null', swallowedShape, [true, '[null]']);

These are the two useful relatives of once: before for "only the first few times", after for "not until it has happened enough". once is not a third implementation, it is before(2, fn), and seeing that is the point of the assertion — the off-by-one in the name is the price of the family resemblance.

before caching and returning the last result is the trap. firstTwoOrders(30000) looks like it should discount thirty thousand and instead hands back the discount computed for twenty thousand, so a caller sees a plausible number that is about the wrong order. If a stale answer would be a bug rather than a saving, return a sentinel or throw on the calls you swallow.

after returning undefined for the quiet calls is the honest option, and the last assertion is a reminder about the assertion harness itself: undefined inside an array stringifies to null, so a result that includes swallowed calls has to be projected — with ?? 'quiet' here — before it can be compared.

Newsletter

New writing, when it lands.

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