Skip to content

Instantly share code, notes, and snippets.

@acconrad
Created January 7, 2016 19:44
Show Gist options
  • Save acconrad/bc9c3f4df9f829b2aedd to your computer and use it in GitHub Desktop.
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
// 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; });
};
@ali
Copy link

ali commented Jan 22, 2016

Curious why you passed lower as the first argument (the "thisArg") to Array.apply

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment