Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Write a range generator in JavaScript

100 range, sum and mean over anything iterable

easy

Write range as a generator that takes one, two or three arguments and counts in either direction, then sum and mean that accept any iterable at all: an array, a Set, a Map's values, or the generator itself. Pick sensible answers for the empty case, and make a bad step throw rather than hang.

Stuck? Three hints, smallest first
  1. 1. One argument means "up to, not including", so shift the arguments: if stop is undefined, the single argument was the stop and the start is 0.
  2. 2. A for...of loop is the only thing sum needs, and it is what makes the function work on every iterable rather than just arrays.
  3. 3. mean has to count as it goes, because an iterable has no length. Decide what an empty iterable averages to before you write the division.

The answer

function* range(start, stop, step = 1) {
  if (stop === undefined) {
    stop = start;
    start = 0;
  }
  if (step === 0) throw new RangeError('step must not be 0');
  if (step > 0) for (let i = start; i < stop; i += step) yield i;
  else for (let i = start; i > stop; i += step) yield i;
}

const sum = (iterable) => {
  let total = 0;
  for (const n of iterable) total += n;
  return total;
};

const mean = (iterable) => {
  let total = 0;
  let count = 0;
  for (const n of iterable) {
    total += n;
    count++;
  }
  return count === 0 ? NaN : total / count;
};

const fiveDays = [...range(5)];
const midweek = [...range(2, 6)];
const countdown = [...range(10, 0, -2)];
const wrongWay = [...range(0, 5, -1)];

const takings = [4500, 12000, 9000, 30000];
const asSet = new Set(takings);
const asMap = new Map([['A12', 4500], ['B03', 12000], ['A07', 9000], ['C21', 30000]]);
const fourWays = [sum(takings), sum(asSet), sum(asMap.values()), sum(range(1, 4))];
const average = mean(takings);
const emptySum = sum([]);
const emptyMean = mean([]);
const drift = sum([0.1, 0.2]);

const lazy = range(0, 5, 0);                 // the body has not run yet
let onIteration = 'no error';
try { [...lazy]; } catch (e) { onIteration = e.constructor.name; }

console.log('range   :', fiveDays, midweek, countdown);
console.log('sum     :', fourWays, '| mean:', average);
console.log('empty   :', emptySum, emptyMean);
console.log('step 0  :', typeof lazy.next, '->', onIteration);

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('one argument counts from 0 up to but not including it', fiveDays, [0, 1, 2, 3, 4]);
test('two arguments set both ends, and a negative step counts down', [midweek, countdown], [[2, 3, 4, 5], [10, 8, 6, 4, 2]]);
test('sum takes an array, a Set, a Map iterator or a generator, unchanged', fourWays, [55500, 55500, 55500, 6]);
test('mean has to count as it goes, because an iterable has no length', average, 13875);
test('nothing sums to 0, the identity, but averages to NaN', [emptySum, Number.isNaN(emptyMean)], [0, true]);
test('adding tenths is not exact, so a sum of money should be in kobo', [drift === 0.3, drift.toFixed(2)], [false, '0.30']);
test('a step pointing away from the stop yields nothing instead of looping for ever', wrongWay, []);
test('a step of 0 throws, but only once someone iterates it', [typeof lazy.next, onIteration], ['function', 'RangeError']);

Writing sum against for...of rather than reduce is what makes it work on a Set, a Map's .values(), a string, a generator or anything else with Symbol.iterator. reduce would have tied it to arrays, and [...iterable].reduce(...) would build a throwaway array first. The same argument applies to mean: no length exists, so counting as you go is not a workaround, it is the only way.

The empty cases are a design decision, not an oversight. 0 is the right answer for an empty sum because it is the additive identity: sum([...a, ...b]) === sum(a) + sum(b) stays true. An empty mean has no such answer, so NaN is more honest than 0, which would silently drag a real average down. Note that NaN has to be asserted through Number.isNaN, because JSON.stringify(NaN) is null.

The last assertion is about generators generally. Calling a generator function runs none of its body: it hands back an iterator, and the first next() is what starts executing. So argument validation inside a generator is deferred, sometimes by a long way. If you want range(0, 5, 0) to fail at the call site, wrap it: a plain function that validates and then returns the generator's iterator.

Newsletter

New writing, when it lands.

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