Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Created July 5, 2023 17:59
Show Gist options
  • Save cferdinandi/8187bd8a7739484a96b7d031c5b74244 to your computer and use it in GitHub Desktop.
Save cferdinandi/8187bd8a7739484a96b7d031c5b74244 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Range</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
/**
* 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;
});
}
// 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);
console.log(first, second, third);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment