Max Yankov
Max Yankov

Reputation: 13297

What's an idiomatic way to get the final value of the iterator function?

I have a pretty complicated function that describes some iterative process. It looks something like this (I've a lot of code that is irrelevant to the question):

function* functionName(
    config: Config,
    poolSize: number
): Generator<[State, Step], boolean, void> {
    /* ... */

    for (const step of someOtherProcess()) {
        /* ... */

        yield [state, step]

        switch (stateType) {
            case StateType.Start:
                if (/* ... */) {
                    return false
                } else {
                    return true
                }

            case StateType.Invalid:
                return false
        }
    }

    return false
}

It does three things: (1) emulates some process, (2) provides information of every step of the process (as you can see in the line with yield), and (3) provides an end result when the process is complete. Obviously, (3) and (2) are direct logical consequences of (1), that's why I perform both tasks in one function.

However, while some users of the function care about each step (2), some others only care about the end result (3).

For now, I use this:

const generator = functionName(config, poolSize)
let result
while (!(result = generator.next()).done) {}
return result.value as boolean

Is there some more idiomatic and simple way to achieve the same result?

Upvotes: 1

Views: 56

Answers (1)

ccarton
ccarton

Reputation: 3666

Can you not just add an option?

function* functionName(
    config: Config,
    poolSize: number,
    yieldSteps = true
): Generator<[State, Step], boolean, void> {
    /* ... */

    for (const step of someOtherProcess()) {
        /* ... */

        if (yieldSteps) { yield [state, step] }

        switch (stateType) {
            case StateType.Start:
                if (/* ... */) {
                    return false
                } else {
                    return true
                }

            case StateType.Invalid:
                return false
        }
    }

    return false
}

Upvotes: 1

Related Questions