AniUI Academy

Generate a range of numbers

easyArrays & Objects+150 XPPractice

Rendering ten skeleton rows or a row of page numbers means having an array to map over. JavaScript has no built-in range, so every codebase grows one.

Implement range(start, end, step). Return an array of numbers beginning at start, increasing by step each time, and stopping before end — end itself is never included. step defaults to 1 when it is not supplied. If step is zero or negative, return an empty array. If start is greater than or equal to end, return an empty array. Negative values of start and end are ordinary numbers and work the same way.

Arguments

startnumber
The first value in the returned sequence.
endnumber
The exclusive upper bound — iteration stops before this value.
stepnumber
How much to advance each step. Defaults to 1.

Returns

Array<number> — A new array of numbers from start up to but not including end. Returns [] for a non-positive step or when start >= end.

Examples

range(0, 5);
// [0, 1, 2, 3, 4]

end is exclusive — the sequence stops before it.

range(2, 10, 3);    // [2, 5, 8]
range(-3, 2);       // [-3, -2, -1, 0, 1]
range(5, 5);        // []
range(0, 5, -1);    // []

What it has to do

  • end is exclusive: range(0, 5) stops at 4.
  • step defaults to 1 when omitted.
  • Return [] when step is zero or negative.
  • Return [] when start >= end.
  • Handle negative start values.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.