0.0.2 • Published 3 years ago

redcr v0.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

Build status NPM release License

Redcr (pronounced redka like the British town) is an experimental alternative to Immer.

Redux reducers require you to update your state in an immutable way, by creating a copy of the previous state with any changes applied. In mordern JavaScript, this can involve a tonne of spread operators. It's difficult to read and write a reducer in this way.

Immer takes a runtime approach to solving this problem which has a performance impact approximately 2-6 times worse than a handwritten reducer, and involves shipping an additional dependency to clients.

Redcr works at compile-time by automatically converting any reducer wrapped in redcr(...) to use immutable operations instead of mutable ones. Redcr has no impact on runtime bundle size, and theoretically has comparable performance to a handwritten reducer.

For example, this reducer

import { redcr } from 'redcr';

const myReducer = redcr((state: State) => {
    state.child.str = 'new';
    state.array.push(1);
    state.anotherArray.pop();
});

will be automatically converted to something like this (the exact output depends on what ES version you're targeting) when the code is compiled to JavaScript:

const myReducer = (state) => {
    return {
        ...state,
        child: {
            ...parent.child,
            str: 'new'
        },
        array: [...state.array, 1]
        annotherArray: state.anotherArray.slice(0, state.anotherArray.length - 1)
    };
};

💿 Install

Redcr works by using TypeScript compiler transforms. Even though this is a native TypeScript feature, it's not yet exposed publically. You need ttypescript which is a smaller wrapper around TypeScript which exposes that feature.

npm install --save-dev redcr ttypescript

Follow ttypescript's setup for the specific tools you're using. There is different configuration for Webpack, Rollup, Jest, etc but mostly they're just 1 or 2 lines of configuration to re-point the compiler.

Then in your tsconfig.json add the transformation:

{
    "compilerOptions": {
        "plugins": [
            { "transform": "redcr/transform" },
        ]
    }
}

📙 Supported operations

TypeExample
Assignmentfoo.bar = 123
Bracket syntaxfoo['bar'] = 123
String concatenationfoo.bar += 'hello'
Delete operatordelete foo.bar
Array access by indexfoo.arr[0] = 123
Array.pushfoo.arr.push(123)
Array.popfoo.arr.pop()
Array.shiftfoo.arr.shift()
Array.unshiftfoo.arr.unshift(123)
Conditional mutationif (condition) foo.bar = 123
Local variableslet tmp = 3; foo.bar = tmp;
Increment/decrementfoo.num++; foo.bar--;

See proposed features

📝 Contributing

Contributions are welcome. Bug reports and use-cases are just as valuable as PRs. All code changes must be accompanied by tests.