Extracting Loops Via Generators In JavaScript
Often extracting content in loops done via a callback. Firstly, here is a function that loops over some items and modifies them:
function addMoreHp(cars) { for (let car of cars) { const oldHp = car.hp; car.hp += 10; } } let carsHp = generateCars(); addMoreHp(carsHp); console.log(carsHp); // [ { name: 'miata', hp: 165 }, // { name: 'elise', hp: 227 }, // { name: 'alfaromeo', hp: 247 } ]
Later logging needs to be added, the most obvious way is to use a callback (In real world code a logging library would be used instead of console.log):
function addMoreHp(cars, callback) { for (let car of cars) { const oldHp = car.hp; car.hp += 10; callback(oldHp, car.hp); } } addMoreHp(carsHp, (oldHP, newHP) => { console.log(oldHP, '=>', newHP); }); // 165 '=>' 175 // 227 '=>' 237 // 247 '=>' 257
This way the logging strategy, formatting or other details can be easily changed without altering addMoreHp. Though this involves adding an extra parameter which can be annoying in large system with lots of code calling your original function. If a generator is used, this can all be avoided:
function* addMoreHp(cars) { for (let car of cars) { const oldHp = car.hp; car.hp += 10; yield [oldHp, car.hp]; } } for (let [oldHP, newHP] of addMoreHp(carsHp)) { console.log(oldHP, '=>', newHP); } // 165 '=>' 175 // 227 '=>' 237 // 247 '=>' 257
Generators are supported in all browsers except IE (Though MS Edge is supported). I got the idea from this blog post: http://2ality.com/2018/04/extracting-loops.html
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2018/externalLoopExtraction.js













