In JavaScript possiamo implementare la funzione di PHP che genera un range di valori.
La soluzione รจ la seguente:
'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;
};
Esempi:
range( 0, 12 ); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
range( 0, 100, 10 ); // [ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 ]
range( 'a', 'i' ); // [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' ]