• API
• FAQ
• Tools
• Archive
SHARE
TWEET

Untitled

a guest Jun 26th, 2019 84 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. /**
2.  * range()
3.  *
4.  * Returns an array of numbers between a start number and an end number incremented
5.  * sequentially by a fixed number(step), beginning with either the start number or
6.  * the end number depending on which is greater.
7.  *
8.  * @param {number} start (Required: The start number.)
9.  * @param {number} end (Required: The end number. If end is less than start,
10.  *  then the range begins with end instead of start and decrements instead of increment.)
11.  * @param {number} step (Optional: The fixed increment or decrement step. Defaults to 1.)
12.  *
13.  * @return {array} (An array containing the range numbers.)
14.  *
15.  * @throws {TypeError} (If any of start, end and step is not a finite number.)
16.  * @throws {Error} (If step is not a positive number.)
17.  */
18. function range(start, end, step = 1) {
19.
20.   // Test that the first 3 arguments are finite numbers.
21.   // Using Array.prototype.every() and Number.isFinite().
22.   const allNumbers = [start, end, step].every(Number.isFinite);
23.
24.   // Throw an error if any of the first 3 arguments is not a finite number.
25.   if (!allNumbers) {
26.     throw new TypeError('range() expects only finite numbers as arguments.');
27.   }
28.
29.   // Ensure the step is always a positive number.
30.   if (step <= 0) {
31.     throw new Error('step must be a number greater than 0.');
32.   }
33.
34.   // When the start number is greater than the end number,
35.   // modify the step for decrementing instead of incrementing.
36.   if (start > end) {
37.     step = -step;
38.   }
39.
40.   // Determine the length of the array to be returned.
41.   // The length is incremented by 1 after Math.floor().
42.   // This ensures that the end number is listed if it falls within the range.
43.   const length = Math.floor(Math.abs((end - start) / step)) + 1;
44.
45.   // Fill up a new array with the range numbers
46.   // using Array.from() with a mapping function.
47.   // Finally, return the new array.
48.   return Array.from(Array(length), (x, index) => start + index * step);
49.
50. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top