I have a problem where I need to display the below output
1
23
456
78910
My solution which uses the limit of the number count is below.
let numberStepper = (stepLimit) => {
let stepCounter = 0;
let step = '';
for(let row = 1; row <= stepLimit; row++) {
step = '';
for(let col = 1; col <= row; col++) {
stepCounter++;
step += `${stepCounter}`
}
if(stepCounter > stepLimit) {
break;
}
console.log(step);
}
}
numberStepper(10) // Gives desired output
Another solution that limits the number of steps output is below.
let numberStepper = (stepsLimit) => {
let stepCounter = 0;
let step = '';
for(let row = 1; row <= stepsLimit; row++) {
step = '';
for(let col = 1; col <= row; col++) {
stepCounter++;
step += `${stepCounter}`
}
console.log(step);
}
}
numberStepper(4) // Gives desired output
How can I refactor this function to have a clean implementation?
Any ideas on the first implementation? where the argument determines the numbers displayed in the steps instead of using the number of steps as the determinant of the numbers displayed?
You can do it in one for loop for the first approach where the argument is the number limit to be counted until instead of number of rows
function printNumbers(n){
for(
var counter = 1,
breakPointer = 1,
newBreakPointer = 1;
counter <= n;
counter++,
breakPointer--
){
if(breakPointer == 0){
document.write("<br>");
newBreakPointer++;
breakPointer = newBreakPointer;
}
document.write(counter);
}
}
printNumbers(10)