import _ from 'lodash';

import * as ActionTypes from '../action-types';
import * as ActionHelpers from '../action-helpers';

const { response } = ActionHelpers;
const indexById = list => _.keyBy(list || [], 'id');
const mergeByIds = (state, array) => ({ ...state, ...indexById(array) });

export default function comments(state = {}, action) {
  if (ActionHelpers.isFeedResponse(action)) {
    return mergeByIds(state, action.payload.comments);
  }
  switch (action.type) {
    case response(ActionTypes.GET_SINGLE_POST):
    case response(ActionTypes.SHOW_MORE_COMMENTS):
    case response(ActionTypes.SHOW_MORE_LIKES_ASYNC): {
      return mergeByIds(state, action.payload.comments);
    }
    case response(ActionTypes.SAVE_EDITING_COMMENT): {
      return { ...state, [action.payload.comments.id]: { ...state[action.payload.comments.id], ...action.payload.comments } };
    }
    case response(ActionTypes.DELETE_COMMENT): {
      return { ...state, [action.request.commentId]: undefined };
    }
    case ActionTypes.REALTIME_COMMENT_NEW:
    case ActionTypes.REALTIME_COMMENT_UPDATE: {
      return mergeByIds(state, [action.comment]);
    }
    case ActionTypes.REALTIME_COMMENT_DESTROY: {
      return { ...state, [action.commentId]: undefined };
    }
    case response(ActionTypes.ADD_COMMENT): {
      return { ...state,
        [action.payload.comments.id]: action.payload.comments
      };
    }
    case ActionTypes.REALTIME_POST_NEW: {
      return mergeByIds(state, action.comments);
    }
  }
  return state;
}

@@ -929,35 +929,68 @@
 %7B%0A      
-return %7B ...state, 
+const newState = %7B ...state %7D;%0A      delete newState
 %5Baction.
@@ -1003,37 +1003,47 @@
 t.commentId%5D
-: undefined %7D
+;%0A      return newState
 ;%0A    %7D%0A    
@@ -1244,58 +1244,101 @@
     
-return %7B ...state, %5Baction.commentId%5D: undefined %7D
+const newState = %7B ...state %7D;%0A      delete newState%5Baction.commentId%5D;%0A      return newState
 ;%0A  

Fix pointer "leaks" on removing comments, part 3