{"size": 995, "ext": "js", "max_stars_repo_path": "src/redux/modules/groupExercises.js", "max_stars_repo_name": "exyi/web-app", "max_stars_repo_stars_event_min_datetime": "2017-09-28T09:30:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-14T19:22:27.000Z", "max_issues_repo_path": "src/redux/modules/groupExercises.js", "max_issues_repo_name": "exyi/web-app", "max_issues_repo_issues_event_min_datetime": "2017-04-24T12:10:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T13:05:35.000Z", "max_forks_repo_path": "src/redux/modules/groupExercises.js", "max_forks_repo_name": "exyi/web-app", "max_forks_repo_forks_event_min_datetime": "2017-10-04T19:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T20:01:40.000Z"}
{"max_stars_count": 9, "max_issues_count": 66, "max_forks_count": 6, "avg_line_length": 25.5128205128, "max_line_length": 112, "alphanum_fraction": 0.6231155779}
import { handleActions } from 'redux-actions';
import { actionTypes } from './exercises';

const initialState = {};

const isGroupExercisesAction = ({ meta: { endpoint } }) => /^\/groups\/[a-zA-Z0-9-]+\/exercises/.test(endpoint);

const extractGroupIdFromTheEndpoint = endpoint => {
  const matches = /^\/groups\/([a-zA-Z0-9-]+)\/exercises/.exec(endpoint);
  if (matches.length !== 1) {
    // ???
  }

  return matches[1];
};

const reducer = handleActions(
  {
    [actionTypes.FETCH_MANY_FULFILLED]: (state, action) => {
      if (!isGroupExercisesAction(action)) {
        return state;
      }

      const groupId = extractGroupIdFromTheEndpoint(action.meta.endpoint);
      const exerciseIds = action.payload.map(exercise => exercise.id);
      const oldExerciseIds = state[groupId] || [];
      const ids = [...oldExerciseIds, ...exerciseIds];

      return {
        ...state,
        [groupId]: Array.from(new Set(ids)),
      };
    },
  },
  initialState
);

export default reducer;
