Skip to content

Helper to keep calling a function until a criterion is met #3390

Open
@matthewmayer

Description

@matthewmayer

Clear and concise description of the problem

We often get requests for additional options for methods to further restrict the output in some way, e.g. limiting the length or the range of outputs, or excluding certain types of data

Suggested solution

In some cases, rather than add many more options, it may make sense to just repeatedly generate until a certain criterion is met. This could be wrapped in a helpers function.

pseudocode.

/** repeatedly calls a function until a condition is met and returns the result */
function generateUntil(func, condition) {
    let result = null
    do {
        result = func()
    } while (!condition(result))
    return result
}

Usage:

const shortCompanyName = faker.helpers.generateUntil(faker.company.name, (name) => name.length < 30)
const femaleNameStartingWithJ = faker.helpers.generateUntil(()=>faker.person.firstName("female"), (name) => name.startsWith("J"))

Alternative

Write the loop manually

Additional context

Note if you provide an impossible condition, this gives an infinite loop. Might need a automatic failure after a certain number of loops.

Metadata

Metadata

Assignees

Labels

c: featureRequest for new featurem: helpersSomething is referring to the helpers modulep: 1-normalNothing urgents: waiting for user interestWaiting for more users interested in this feature

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions