Skip to content

Latest commit

 

History

History
26 lines (22 loc) · 632 Bytes

range-generator.md

File metadata and controls

26 lines (22 loc) · 632 Bytes
title type language tags cover dateModified
Range generator
snippet
javascript
function
generator
dark-leaves-6
2020-10-11

Creates a generator, that generates all values in the given range using the given step.

  • Use a while loop to iterate from start to end, using yield to return each value and then incrementing by step.
  • Omit the third argument, step, to use a default value of 1.
const rangeGenerator = function* (start, end, step = 1) {
  let i = start;
  while (i < end) {
    yield i;
    i += step;
  }
};

for (let i of rangeGenerator(6, 10)) console.log(i);
// Logs 6, 7, 8, 9