Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript have a method like "range()" to generate a range within the supplied bounds?

In PHP, you can do...

range(1, 3); // Array(1, 2, 3) range("A", "C"); // Array("A", "B", "C") 

That is, there is a function that lets you get a range of numbers or characters by passing the upper and lower bounds.

Is there anything built-in to JavaScript natively for this? If not, how would I implement it?

like image 256
alex Avatar asked Oct 09 '10 02:10

alex


People also ask

Does JavaScript have a range function?

Definition of JavaScript Range. JavaScript Range is a function that is supported by JavaScript in order to return all the integer and its value from starting to the ending while traversing from start index to the end index.

How do you create a range in JavaScript?

The range() function takes the starting and ending index as an input and returns a new range of the specified object. Start represents the beginning point in the index while the end represents the ending point in the list.. It returns the created range of the specified object.

Which method in JavaScript does return a range of elements of an array?

slice() method returns the selected elements in an array, as a new array object.


1 Answers

Numbers

[...Array(5).keys()];  => [0, 1, 2, 3, 4] 

Character iteration

String.fromCharCode(...[...Array('D'.charCodeAt(0) - 'A'.charCodeAt(0) + 1).keys()].map(i => i + 'A'.charCodeAt(0)));  => "ABCD" 

Iteration

for (const x of Array(5).keys()) {   console.log(x, String.fromCharCode('A'.charCodeAt(0) + x)); }  => 0,"A" 1,"B" 2,"C" 3,"D" 4,"E" 

As functions

function range(size, startAt = 0) {     return [...Array(size).keys()].map(i => i + startAt); }  function characterRange(startChar, endChar) {     return String.fromCharCode(...range(endChar.charCodeAt(0) -             startChar.charCodeAt(0), startChar.charCodeAt(0))) } 

As typed functions

function range(size:number, startAt:number = 0):ReadonlyArray<number> {     return [...Array(size).keys()].map(i => i + startAt); }  function characterRange(startChar:string, endChar:string):ReadonlyArray<string> {     return String.fromCharCode(...range(endChar.charCodeAt(0) -             startChar.charCodeAt(0), startChar.charCodeAt(0))) } 

lodash.js _.range() function

_.range(10);  => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] _.range(1, 11);  => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] _.range(0, 30, 5);  => [0, 5, 10, 15, 20, 25] _.range(0, -10, -1);  => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] String.fromCharCode(..._.range('A'.charCodeAt(0), 'D'.charCodeAt(0) + 1));  => "ABCD" 

Old non es6 browsers without a library:

Array.apply(null, Array(5)).map(function (_, i) {return i;});  => [0, 1, 2, 3, 4] 

console.log([...Array(5).keys()]);

(ES6 credit to nils petersohn and other commenters)

like image 97
Ben Avatar answered Sep 23 '22 01:09

Ben