Advertisement
Guest User

Untitled

a guest
Aug 21st, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. /**
  2. * The application state is a list of Posts and every action is processed by the root reducer, i.e. PostsReducer,
  3. * which returns the new state.
  4. */
  5. function PostsReducer(currentState: Post[] = [], action: Action){
  6. switch(action.type){
  7. case 'CREATE_POST':
  8. return createPost(currentState, action);
  9. case 'ADD_COMMENT':
  10. return addCommentToPost(currentState, action);
  11. default:
  12. return currentState;
  13. }
  14. }
  15.  
  16. function createPost(currentState: Post[] = [], action: Action){
  17. const newPost: Post = {
  18. id: action.payload.id,
  19. title: action.payload.title,
  20. text: action.payload.text,
  21. createdBy: action.createdBy,
  22. createdAt: action.createdAt,
  23. comments: []
  24. }
  25. return [...currentState, newPost];
  26. }
  27.  
  28. function addCommentToPost(currentState: Post[] = [], action: Action){
  29. return currentState.map(post => {
  30. if(post.id === action.payload.postId) {
  31. /* this creates a new object copying all atributes in 'post' but replacing
  32. posts.comments with the result of the commentsRecuder function call.
  33. */
  34. return {...post, comments: CommentsReducer(post.comments, action) };
  35. }else{
  36. return post;
  37. }
  38. });
  39. }
  40.  
  41. function CommentsReducer(currentState: Comment[] = [], action: Action){
  42. switch(action.type){
  43. case 'ADD_COMMENT':
  44. return addComment(currentState, action);
  45. default:
  46. return currentState;
  47. }
  48. }
  49.  
  50. function addComment(currentState: Comment[], action: Action){
  51. const newComment: Comment = {
  52. id: action.payload.id,
  53. text: action.payload.text,
  54. createdAt: action.createdAt,
  55. createdBy: action.createdBy
  56. }
  57. return [...currentState, newComment];
  58. }
  59.  
  60. interface Post{
  61. id: string;
  62. title: string;
  63. text: string;
  64. createdBy: string;
  65. createdAt: number;
  66. comments: Comment[];
  67. }
  68.  
  69. interface Comment{
  70. id: string;
  71. text: string;
  72. createdBy: string;
  73. createdAt: number;
  74. }
  75.  
  76. interface Action{
  77. id: string;
  78. type: string;
  79. createdAt: number;
  80. createdBy: string;
  81. payload: any; // in a real application create a type for this as well.
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement