PHP dispone della funzione range()
che genera un'array di numeri o caratteri a partire da un valore iniziale ed uno finale. Possiamo implementare qualcosa di simile in JavaScript.
Definiamo la seguente funzione:
'use strict';
const range = ( low, high, step ) => {
let matrix = [];
let inival, endval, plus;
let walker = step || 1;
let chars = false;
if ( !isNaN( low ) && !isNaN( high ) ) {
inival = low;
endval = high;
} else if ( isNaN( low ) && isNaN( high ) ) {
chars = true;
inival = low.charCodeAt( 0 );
endval = high.charCodeAt( 0 );
} else {
inival = ( isNaN( low ) ? 0 : low );
endval = ( isNaN( high ) ? 0 : high );
}
plus = ( ( inival > endval ) ? false : true );
if ( plus ) {
while ( inival <= endval ) {
matrix.push( ( ( chars ) ? String.fromCharCode( inival ) : inival ) );
inival += walker;
}
} else {
while ( inival >= endval ) {
matrix.push( ( ( chars ) ? String.fromCharCode( inival ) : inival ) );
inival -= walker;
}
}
return matrix;
}
Esempio d'uso:
let nums = range( 1, 6 );
// [ 1, 2, 3, 4, 5, 6 ]