Keeping State in a Closure
Every climber at the desk gets a numbered wristband: M-101 in the morning, L-101 in the evening
Learn to Boulder class. In Python, make_band_counter() is a factory that keeps the last number in
a variable, rebound with nonlocal for each band. Port it to JavaScript.
In the JavaScript port, number becomes a let, and the arrow is returned where it’s written.
Watch out for the nonlocal line: as with global, JavaScript has none, so nonlocal number;
stops the file with SyntaxError: Unexpected identifier 'number' before anything runs. Leave it
out, and the rest ports as it is:
function makeBandCounter(prefix, start = 101) {
let number = start - 1;
return () => {
number += 1;
return `${prefix}-${number}`;
};
}
const morning = makeBandCounter("M");
console.log(morning());
console.log(morning());
Run it: Ana gets M-101, and Ben the next one: