Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEATURE] Support loops #9

Open
michaelboyles opened this issue Nov 1, 2021 · 1 comment
Open

[FEATURE] Support loops #9

michaelboyles opened this issue Nov 1, 2021 · 1 comment
Labels
enhancement New feature or request

Comments

@michaelboyles
Copy link
Owner

Currently, using a loop in a Redcr reducer can end up mutably editing the state. For example

interface StringState {
    str: String
}
const reducer = redcr((state: StringState) => {
    for (let i = 0; i < 3; i++) {
        state.str += 'A';
    }
});

Will produce

const reducer = (state) => {
    for (let i = 0; i < 3; i++) {
        state.str += 'A';
    }
    return state;
};

It should probably work similar to how if-statements are handled, and continuously reassign the state

const reducer = (state) => {
    for (let i = 0; i < 3; i++) {
        state = {
            ...state,
            str: state.str + 'A'
        }
    }
    return state;
};

Could explore loop unrolling too if the number of iterations is a compile-time constant.

How often is a loop actually useful in a reducer though?

@michaelboyles michaelboyles added the enhancement New feature or request label Nov 1, 2021
@michaelboyles
Copy link
Owner Author

For-loops are now supported. While-loops will require more thought. This code

interface StringState {
    str: string
}
const reducer = redcr((state: StringState) => {
    let i = 1;
    while (i <= 3) {
        state.str += 'A';
        i++;
    }
});

Produces this:

const reducer = (state) => {
    while (1 <= 3) {
        state.str += 'A';
        1++;
    }
    return state;
};

It's caused by unsophisticated local variable removal which incorrectly inlines the counter. Local variables are inlined to support destructuring the state.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant