Making for loops more readable

Creating a custom function like “repeat” that accepts a number of times to repeat and a callback function can be a great way to improve the readability of your code. It can also make your code more reusable and easier to understand, especially when working with nested for loops.

const repeat = (times: number, callback: Function) => {
    for(let i = 0; i < times; i++) {
        callback(i)
    }
}

repeat(10, i => console.log(`${i}. ${Math.random() * 100}`))

By abstracting the for loop logic into a separate function, you can reduce the complexity of your code and make it more readable. The callback function allows you to pass any code you want to repeat and the index of the current iteration will be passed to it as a parameter. This means you can use the index to perform different operations each time the loop is executed.

In addition, the repeat function can be used throughout your project and makes it easy to repeat the same operation multiple times. This can help to reduce the number of lines of code and make your code more efficient.

It’s worth noting that a version of this technique is also available in JavaScript.

const repeat = (times, callback) => {
    for(let i = 0; i < times; i++) {
        callback(i)
    }
}