Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

chunk, zip, unzip and partition utilities in JavaScript

96 chunk, zip, unzip and partition

fair

Write the four reshapers: chunk a list into fixed-size pieces, zip several lists into rows, unzip rows back into lists, and partition a list into the ones that match and the ones that do not. Decide what zip should do when the lists are different lengths, and make the choice visible.

Stuck? Three hints, smallest first
  1. 1. chunk is the one place a counting for loop still reads better than anything else: step i by size and slice.
  2. 2. Array.from({ length }, (_, i) => ...) builds a list of a known length from its indices, which is exactly what zip needs.
  3. 3. unzip needs no new code at all. Look at what zip(...rows) does to a list of rows.

The answer

const chunk = (items, size) => {
  if (!Number.isInteger(size) || size < 1) throw new RangeError('size must be a positive integer');
  const out = [];
  for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
  return out;
};

const zip = (...lists) => {
  const length = Math.min(...lists.map((l) => l.length));           // stop at the shortest
  return Array.from({ length }, (_, i) => lists.map((l) => l[i]));
};

const zipLong = (...lists) => {
  const length = Math.max(...lists.map((l) => l.length));           // pad instead
  return Array.from({ length }, (_, i) => lists.map((l) => l[i] ?? null));
};

const unzip = (rows) => zip(...rows);

const partition = (items, keep) => {
  const yes = [];
  const no = [];
  for (const item of items) (keep(item) ? yes : no).push(item);
  return [yes, no];
};

const skus = ['GRP-1', 'GRP-2', 'GRP-3', 'GRP-4', 'GRP-5'];
const units = [12, 3, 40, 7, 25];
const shelves = ['A1', 'A2'];

const pages = chunk(skus, 2);
const exact = chunk(skus.slice(0, 4), 2);
const emptyChunked = chunk([], 3);
const rows = zip(skus, units);
const backAgain = unzip(rows);
const short = zip(skus, shelves);
const padded = zipLong(shelves, units);
const [plenty, scarce] = partition(units, (n) => n >= 10);
const [none, alsoNone] = partition([], (n) => n > 0);

let badSize = 'no error';
try { chunk(skus, 0); } catch (e) { badSize = e.constructor.name; }

console.log('chunk    :', pages);
console.log('zip      :', rows.slice(0, 2), '| shortest wins:', short.length);
console.log('unzip    :', backAgain);
console.log('partition:', plenty, scarce, '| bad size:', badSize);

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('chunk cuts fixed-size pieces and lets the last one be short', pages, [['GRP-1', 'GRP-2'], ['GRP-3', 'GRP-4'], ['GRP-5']]);
test('an exact multiple has no short tail, and nothing chunks to nothing', [exact.length, emptyChunked], [2, []]);
test('zip pairs by position', rows.slice(0, 3), [['GRP-1', 12], ['GRP-2', 3], ['GRP-3', 40]]);
test('unzip is zip spread over the rows, so the round trip is the identity', backAgain, [skus, units]);
test('mismatched lengths stop at the shortest, silently losing the rest', [short.length, short], [2, [['GRP-1', 'A1'], ['GRP-2', 'A2']]]);
test('the other choice pads, and null says "nothing here" out loud', padded, [['A1', 12], ['A2', 3], [null, 40], [null, 7], [null, 25]]);
test('partition keeps the original order inside both halves', [plenty, scarce], [[12, 40, 25], [3, 7]]);
test('and partitioning nothing gives two empty lists, never undefined', [none, alsoNone], [[], []]);
test('a size of zero throws rather than building an infinite list of empties', badSize, 'RangeError');

chunk with a size of zero is the reason the guard exists: i += 0 never advances, so the loop pushes empty arrays for ever. Throwing a RangeError turns a hung tab into a stack trace pointing at the caller, which is the trade you want.

zip has no right answer for ragged input, only two defensible ones. Truncating to the shortest is what most libraries do and what most callers expect, but it discards data with no warning, so it is only safe when the lists are the same length by construction — which is usually the case, because they came from the same rows. Padding keeps everything and forces the caller to handle a hole. Padding with null rather than undefined is deliberate: undefined vanishes through JSON.stringify and reads as "missing key" instead of "missing value".

partition is worth having because the obvious alternative walks the list twice with two opposite predicates, and the second predicate is where the bug goes: n >= 10 and n < 10 drift apart the moment the rule changes. One walk, one predicate, two lists, and the destructure at the call site reads well.

Newsletter

New writing, when it lands.

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