Skip to content

Commit

Permalink
Exclude the upper bound of range (#36283)
Browse files Browse the repository at this point in the history
  • Loading branch information
geryogam authored Oct 9, 2024
1 parent 1c31c8e commit 029012e
Showing 1 changed file with 10 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -132,20 +132,23 @@ Array.from({ length: 5 }, (v, i) => i);
### Sequence generator (range)

```js
// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP, etc.)
// Sequence generator function (commonly referred to as "range", e.g. Python, Clojure, etc.)
const range = (start, stop, step) =>
Array.from({ length: (stop - start) / step + 1 }, (_, i) => start + i * step);
Array.from(
{ length: Math.ceil((stop - start) / step) },
(_, i) => start + i * step,
);

// Generate numbers range 0..4
range(0, 4, 1);
// Generate numbers from 0 (inclusive) to 4 (exclusive) with step 1
range(0, 5, 1);
// [0, 1, 2, 3, 4]

// Generate numbers range 1..10 with step of 2
// Generate numbers from 1 (inclusive) to 10 (exclusive) with step 2
range(1, 10, 2);
// [1, 3, 5, 7, 9]

// Generate the alphabet using Array.from making use of it being ordered as a sequence
range("A".charCodeAt(0), "Z".charCodeAt(0), 1).map((x) =>
// Generate the alphabet making use of it being ordered as a sequence
range("A".charCodeAt(0), "Z".charCodeAt(0) + 1, 1).map((x) =>
String.fromCharCode(x),
);
// ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
Expand Down

0 comments on commit 029012e

Please sign in to comment.