Created
January 7, 2016 19:44
-
-
Save acconrad/bc9c3f4df9f829b2aedd to your computer and use it in GitHub Desktop.
How to create an Array sequence from one number to the next in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Works in IE9+, Chrome, Safari, Firefox, and Opera | |
// | |
// Examples: | |
// (5).upTo(10) => [5, 6, 7, 8, 9, 10] | |
// (-1).upTo(3) => [-1, 0, 1, 2, 3] | |
Number.prototype.upTo = function( upper ){ | |
'use strict'; | |
var lower = this; | |
if ( lower == undefined ) { | |
throw new TypeError( ' this is null or not defined' ); | |
} | |
if ( typeof upper !== 'number' ) { | |
throw new TypeError( upper + ' is not a number' ); | |
} | |
if ( lower > upper ) { | |
throw new TypeError( upper + ' must be greater than your starting number' ); | |
} | |
return Array.apply( lower, new Array( upper - lower ) ).map( function( _, index ){ return index + lower; }); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Curious why you passed
lower
as the first argument (the "thisArg
") toArray.apply