Skip to main content Accessibility Feedback

range.js

Create a range of numbers between two values.

Source Code

Examples

// returns [1,2,3,4,5,6,7]
let first = range(7);

// returns [4,5,6,7,8,9,10,11,12]
let second = range(4, 12);

// returns [-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7]
let third = range(-12, 7);

The helper function

/**
 * Create a range of numbers
 * Adapted with permission from Darren Jones, https://www.amazon.com/Learn-Code-JavaScript-Darren-Jones/dp/1925836401
 * (c) Chris Ferdinandi, MIT License, https://gomakethings.com
 * @param  {Number} min The first number in the range
 * @param  {Number} max The last number in the range
 * @return {Array}      The range
 */
function range (min, max) {

	// If only one number is provided, start at one
	if (max === undefined) {
		max = min;
		min = 1;
	}

	// Create a ranged array
	return Array.from(new Array(max - min + 1).keys()).map(function (num) {
		return num + min;
	});

}