Estoy tratando de escribir una función que devuelva una lista de números enteros desde un valor de 'inicio' (inclusive) a un valor de 'detención' (exclusivo) y me dan el 'paso' (o número para incrementar por...).
Se supone que la función puede manejar diferentes cantidades de argumentos pasados. Creo que tengo la función completa en su mayor parte, pero parece que obtengo un ciclo infinito y no estoy seguro de por qué o cómo proceder.
Aquí está el código que he escrito hasta ahora...
function range(start, stop, step) { if (arguments.length===1) { start = 0; stop = arguments[0]; step = 1; } else if (arguments.length===2) { start = arguments[0]; stop = arguments[1]; step = 1; } else if (arguments.length===3) { start = arguments[0]; stop = arguments[1]; step = arguments[2]; } // define result array let result = []; // create a for-loop for (start; start < stop; start + step) { result.push(start); } return result; }Y aquí hay algunos ejemplos de llamadas y sus resultados esperados...
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]También se supone que la función puede hacer rangos negativos con valores de 'paso' negativos también.
¿Podría alguien explicarme por qué parece que estoy obteniendo un bucle infinito?
Porque no cambia el valor de inicio en su ciclo for . te has perdido un = .
for (start; start < stop; start += step)Su código contiene varios errores. Por ejemplo, reasigna valores a los argumentos, lo que nunca se debe hacer. Entonces, su ciclo for solo funciona para paradas que son mayores que los inicios. Y no hay comprobación de errores en absoluto. Aquí hay una versión autoexplicativa que debería funcionar:
function range(start, stop, step) { for (let i = 0; i < arguments.length; i++) { if (!Number.isInteger(arguments[i])) { return [ 'Invalid arguments: all arguments must be of type Integer' ] } } let from = 0 let to = 0 let increment = 1 if (arguments.length === 1) { to = arguments[0] } else if (arguments.length === 2) { [ from, to ] = arguments } else if (arguments.length === 3) { [ from, to, increment ] = arguments } else { return [ 'Invalid arguments: 0 or more than 3 arguments' ] } if (increment > 0 && from > to) { return [ 'Invalid arguments: step must be negative' ] } else if (increment < 0 && from < to) { return [ 'Invalid arguments: step must be positive' ] } else if (increment === 0) { return [ 'Invalid arguments: step cannot be 0' ] } let result = [] if (increment > 0) { for (from; from < to; from += increment) { result.push(from) } } else { for (from; from > to; from += increment) { result.push(from) } } return result } console.log(range(10)) // [0,1,2,3,4,5,6,7,8,9] console.log(range(1, 11)) // [1,2,3,4,5,6,7,8,9,10] console.log(range(0, 30, 5)) // [0,5,10,15,20,25] console.log(range(0, -10, -1)) // [0,-1,-2,-3,-4,-5,-6,-7,-8,-9] console.log(range('0', 'abc')) // Invalid arguments: all arguments must be of type Integer console.log(range()) // Invalid arguments: 0 or more than 3 arguments console.log(range(0, -10, 1)) // Invalid arguments: step must be negative console.log(range(-20, -10, -1)) // Invalid arguments: step must be positive console.log(range(0, 10, 0)) // Invalid arguments: step cannot be 0Otra solución de rango:
const range = (start, stop, step) => { // manipulation with arguments const itemsCout = Math.ceil((stop - start) / step) return [...Array(itemsCout)].map((_value, index) => index*step+start ) }; console.log(range(1,10,2)); // [ 1, 3, 5, 7, 9 ] console.log(range(0,30,5)); // [ 0, 5, 10, 15, 20, 25 ] console.log(range(0,-10,-1)); // [ 0,-1,-2,-3,-4,-5,-6,-7,-8,-9 ]