Search code examples
reduxreselect

Redux / Reselect - selector reusing


I am new to selectors. I have created the following ones:

import { createSelector } from 'reselect';

const getValues = (state) => state.grid; // [3, 4, 7, 3, 2, 7, 3,...]
const getTiles = (state) => state.tiles; // [0, 1, 0, 1, 0, 0, 1,...]

// counts selected tiles (ie. adds up all the 1s)
export const getSelected = createSelector(
  [getTiles],
  tiles => tiles.reduce((acc, elem) => acc + elem, 0)
);

// displays only values of selected tiles, for the rest it shows 0
export const showSelected = createSelector(
  [getTiles, getValues],
  (tiles, grid) => tiles.map((idx, i) => (idx === 1 ? grid[i] : 0))
);



  export const addSelected = createSelector(
  [showSelected]
  .....
);

/*
export const addSelected = createSelector(
  [showSelected],
  coun => coun.reduce((acc, elem) => acc + elem, 0)
);

*/

The third selector (addSelected - the last bottom, commented-out version) basically does the same thing as the first one (with different inputs). How can I make it more generic so I can reuse it instead of writing the whole 'reduce' line again?


Solution

  • You could just extract the reduce part into it's own function like this:

    import { createSelector } from 'reselect'
    
    ...
    
    // addElements adds all elements from given array
    const addElements = elements =>
      elements.reduce((acc, elem) => acc + elem, 0)
    
    export const getSelected = createSelector([getTiles], addElements)
    
    export const addSelected = createSelector([showSelected], addElements)
    

    I hope this was helpful.