Skip to content

Instantly share code, notes, and snippets.

@rumkin
Last active March 6, 2020 00:28
Show Gist options
  • Save rumkin/d7d7cc91b309351d81d0c2061441a45f to your computer and use it in GitHub Desktop.
Save rumkin/d7d7cc91b309351d81d0c2061441a45f to your computer and use it in GitHub Desktop.
Range

Range Function

This funtion could be used in cicles and make it more clear:

for (const i of range(1, 10)) {
  console.log(i)
}

Outputs numbers from 1 to 9.

for (const i of range(10, 1)) {
  console.log(i)
}

Outputs numbers from 9 to 1.

Using arrays

The logic of the range is based on array behavior and created to create indexes.

const arr = ['a', 'b', 'c']

for (const i of range(0, arr.length)) {
  console.log(arr[i])
}

for (const i of range(arr.length, i)) {
  console.log(arr[i])
}

Output order: a b c b c a

function * range(start, end, step = 1) {
if (start < end) {
while (start < end) {
yield start
start += step
}
}
else if (start > end) {
while (start > end) {
start -= step
yield start
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment