Advertisement
didkoslawow

Untitled

Sep 16th, 2023
610
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export const ACTIONS = {
  2.      ADD_DIGIT: 'add-digit',
  3.      CHOOSE_OPERATION: 'choose-operation',
  4.      CLEAR: 'clear',
  5.      EVALUATE: 'evaluate',
  6.  };
  7.  
  8.  function reducer(state, { type, payload }) {
  9.      switch (type) {
  10.          case ACTIONS.ADD_DIGIT:
  11.              if (state.overwrite) {
  12.                  return {
  13.                      ...state,
  14.                      currentOperand: payload.digit,
  15.                      overwrite: false,
  16.                  };
  17.              }
  18.  
  19.              if (payload.digit === '0' && state.currentOperand === '0') {
  20.                  return state;
  21.              }
  22.  
  23.              if (payload.digit === '.' && state.currentOperand.includes('.')) {
  24.                  return state;
  25.              }
  26.  
  27.              return { ...state, currentOperand: `${state.currentOperand || ''}${payload.digit}` };
  28.          case ACTIONS.CHOOSE_OPERATION:
  29.              if (state.currentOperand == null && state.previousOperand == null) {
  30.                  return state;
  31.              }
  32.  
  33.              if (state.currentOperand == null) {
  34.                  return {
  35.                      ...state,
  36.                      operation: payload.operation,
  37.                  };
  38.              }
  39.  
  40.              if (state.previousOperand == null) {
  41.                  return {
  42.                      ...state,
  43.                      operation: payload.operation,
  44.                      previousOperand: state.currentOperand,
  45.                      currentOperand: null,
  46.                  };
  47.              }
  48.  
  49.              return {
  50.                  ...state,
  51.                  previousOperand: evaluate(state),
  52.                  operation: payload.operation,
  53.                  currentOperand: null,
  54.              };
  55.          case ACTIONS.CLEAR:
  56.              return {};
  57.          case ACTIONS.EVALUATE:
  58.              if (state.operation == null || state.currentOperand == null || state.previousOperand == null) {
  59.                  return state;
  60.              }
  61.  
  62.              return {
  63.                  ...state,
  64.                  overwrite: true,
  65.                  previousOperand: null,
  66.                  operation: null,
  67.                  currentOperand: evaluate(state),
  68.              };
  69.          default:
  70.              return state;
  71.      }
  72.  }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement