1.0.0 • Published 6 years ago

range-operator v1.0.0

Weekly downloads
3
License
AGPL-3.0+
Repository
github
Last release
6 years ago

range-operator

import 'range-operator'

for (let i of 1..to(10)) {
  console.log(i) // prints 1,2,3,4,5,6,7,8,9,10
}

Installation

npm install range-operator

Motivation

The one key missing feature in JavaScript is a Python-like range() operator that produces an array of numbers in certain range.

As of ES6, there are no obvious way to perform that task. The one way is to use Array.from:

Array.from({length: end - start + 1}, (_, i) => i + start)

But of course this is far more unreadable. In case of start === 0, this can be simpler, though:

[...Array(end + 1).keys()]

lodash.range solves this problem particularly:

import _ from 'lodash'
_.range(start, end + 1)

range-operator introduces a more native-ish syntax.

Why the range operator is needed at all

Some people think the old C-style for loop for (i = 0; i < 10; i++) is good enough. But consider this example:

if (start <= end) {
  for (let i = start; i <= end; i++) {
    console.log(i)
  }
} else {
  for (let i = start; i >= end; i--) {
    console.log(i)
  }
}

This is a common pattern for looping over a range [start, end], depending which endpoint is larger. With range operator, this is elegantly simplified:

for (let i of start.to(end)) {
  console.log(i)
}

Neither Python, Perl, Ruby or Swift's range operator is behaved that way. This is one crucial feature of JavaScript.

1.0.0

6 years ago