Home

Documenting a while-loop

Sometimes a while loop is what you need. When you do use the while-loop please document the condition/expression. Below is a decent-enough example of how you can nicely document the condition/expression

/**
 * @param n the number of matches we need
 * @param matcher the function to determine if there is a match
 * @param list the list to search in
 */
const getFirstN = n => matcher => list => {
    const res = []
    let i = 0
    // first condition is to exit when we have enough matches
    const not_enough_matches = () => res.length < n
    // second condition is to exit when we have exhausted the list
    const havent_exhausted_the_list = () => i < list.length
    while(not_enough_matches() && havent_exhausted_the_list()) {
       const candidate = list[i]
       if(matcher(candidate)) {
           res.push(candidate)
       }
       i++
    }
    return res
}