Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Forward arguments with rest and spread in JavaScript

30 Forwarding arguments with rest and spread

fair

Write a traced wrapper that records what it was called with and passes everything through unchanged, and a partial that pre-fills the first arguments. Then check what wrapping costs you: arity, and the receiver.

Stuck? Three hints, smallest first
  1. 1. Rest on the way in, spread on the way out: (...args) => fn(...args) is a transparent relay.
  2. 2. partial is the same idea with two lists: (fn, ...bound) => (...rest) => fn(...bound, ...rest).
  3. 3. An arrow wrapper cannot forward this. A function wrapper with apply can.

The answer

const attempt = (fn) => {
  try { return fn(); } catch (e) { return e.constructor.name; }
};

const sum = (...ns) => ns.reduce((a, b) => a + b, 0);

const seen = [];
const traced = (fn) => (...args) => { seen.push(args); return fn(...args); };
const tracedSum = traced(sum);

const partial = (fn, ...bound) => (...rest) => fn(...bound, ...rest);
const rentFor = (branch, code, amount) => `${branch}/${code}: ${amount}`;
const ikeja = partial(rentFor, 'Ikeja');

const keepsThis = (fn) => function (...args) { return fn.apply(this, args); };
const till = { total: 100, take(n) { return this.total - n; } };
till.takeWrapped = keepsThis(till.take);
const bareMethod = till.take;
const lostReceiver = attempt(() => bareMethod(40));

console.log('through the relay:', tracedSum(1, 2, 3), tracedSum(), tracedSum(...[4, 5]));
console.log('what it saw      :', seen);
console.log('partial          :', ikeja('A1', 12000));
console.log('arity            :', rentFor.length, '->', ikeja.length, '| sum:', sum.length);
console.log('receiver kept    :', till.takeWrapped(40), '| lost:', lostReceiver);

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('the relay passes every argument through untouched', tracedSum(1, 2, 3), 6);
test('and it saw exactly what was passed', seen[0], [1, 2, 3]);
test('rest and spread are inverses, so no arguments is still no arguments', tracedSum(), 0);
test('a spread at the call site meets a rest at the definition', tracedSum(...[4, 5]), 9);
test('partial application pre-fills from the left', ikeja('A1', 12000), 'Ikeja/A1: 12000');
test('but wrapping destroys the declared arity', [rentFor.length, ikeja.length], [3, 0]);
test('a function wrapper forwards the receiver too', till.takeWrapped(40), 60);
test('while a bare method reference loses it and throws in strict mode', lostReceiver, 'TypeError');

(...args) => fn(...args) is the whole pattern behind logging, timing, memoising and rate-limiting wrappers: rest collects an argument list of unknown shape, spread hands it back out in the same order. Nothing is inspected, so it works for any function.

Two things do not survive. fn.length becomes 0, which breaks any library that inspects arity — Express deciding whether a handler is error-handling middleware, for instance. And an arrow wrapper has no this to forward, so wrapping a method needs function plus apply. The TypeError on the last line is the same hazard from the other direction: pull a method off its object in strict mode and this is undefined.

Newsletter

New writing, when it lands.

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