Saturday, April 7, 2018

Only Robinhood can do nested arrows, don't be so heroic

import IAllState from '../../../store/models/_i-all-state';

export interface IRootState
{
    rootState: IAllState;
}

export const mapAllStateAsRootStateToProps = (state: IAllState): IRootState => ({rootState: state});


// Following looks harder to read than the normal function
export const mapDestructuredStatesToPropsHard =
                 <T>(mapper: (rootState: IAllState) => T): (rootState: IAllState) => T & IRootState =>
                     rootState =>
                         // tslint:disable prefer-object-spread
                         Object.assign({}, {rootState}, mapper(rootState));


// Less hard than above. The exported expression is not mangled with too much types.
type IMapper = <T>(mapper: (rootState: IAllState) => T) => (rootState: IAllState) => T & IRootState;
export const mapDestructuredStatesToPropsLessHard: IMapper =
                 mapper =>
                     rootState =>
                         // tslint:disable prefer-object-spread
                         Object.assign({}, {rootState}, mapper(rootState));


// Nested arrow function looks hard, especially with TypeScript, since it's harder to decipher
// if the things that comes after the arrow is an executing code or if it is just a type.

// So despite some people going gaga over arrow functions,
// but some prefer to use normal functions when nested arrow functions mangles the readability of the code.

export function mapDestructuredStatesToProps
    <T>(mapper: (rootState: IAllState) => T): (rootState: IAllState) => T & IRootState
{
    return rootState =>
        // tslint:disable prefer-object-spread
        Object.assign({}, {rootState}, mapper(rootState));
}


Happy Coding!

No comments:

Post a Comment