Generate a range of numbers
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
endis exclusive:range(0, 5)stops at 4.stepdefaults to 1 when omitted.- Return
[]whenstepis zero or negative. - Return
[]whenstart >= end. - Handle negative start values.
Stuck? The javascript course covers everything this challenge needs.
- 1.counts up to but not including end
- 2.honours a custom step
- 3.returns empty when start is not below end
- 4.returns empty for a non-positive step
- 5.handles negative start values
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.