ronantakizawa/codereview-bench huggingface dataset:
Repository: freeCodeCamp/freeCodeCamp
File: client/src/components/Donation/donation-modal.tsx (TypeScript)

Code before:
  const { t } = useTranslation();
  const rotateProgressModalCta = useFeature('progress-modal-cta-rotation').on;
  if (rotateProgressModalCta)
    return <b>{t(`donate.progress-modal-cta-${ctaNumber}`)}</b>;

  const donationDuration = modalDefaultDonation.donationDuration;
  switch (donationDuration) {
    case 'one-time':
      return <b>{t('donate.duration')}</b>;
    case 'month':
      return <b>{t('donate.duration-2')}</b>;
    default:
      return <b>{t('donate.duration-4')}</b>;
  }
};

const RenderIlustration = ({
  recentlyClaimedBlock
}: {
  recentlyClaimedBlock: RecentlyClaimedBlock;
}) => {
  const showModalBears = useFeature('show-modal-bears').on;
  if (showModalBears && recentlyClaimedBlock !== null) {
    if (recentlyClaimedBlock !== null) return <BearBlockCompletion />;
    else return <BearProgressModal />;
  } else if (recentlyClaimedBlock) {
    return <Cup className='donation-icon' />;
  } else {
    return <Heart className='donation-icon' />;
  }
};

function getctaNumberBetween1To10() {
  const min = 1;
  const max = 10;
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function DonateModal({
  show,
  closeDonationModal,
  executeGA,
  location,
  recentlyClaimedBlock
}: DonateModalProps): JSX.Element {
  const [closeLabel, setCloseLabel] = React.useState(false);
  const [ctaNumber, setCtaNumber] = React.useState(0);
  const { t } = useTranslation();
  const handleProcessing = () => {
    setCloseLabel(true);
  };

Review comment (suggestion):
```suggestion
  } else if (recentlyClaimedBlock !== null) {
```

Code after:
  const { t } = useTranslation();
  const rotateProgressModalCta = useFeature('progress-modal-cta-rotation').on;
  if (rotateProgressModalCta)
    return <b>{t(`donate.progress-modal-cta-${ctaNumber}`)}</b>;

  const donationDuration = modalDefaultDonation.donationDuration;
  switch (donationDuration) {
    case 'one-time':
      return <b>{t('donate.duration')}</b>;
    case 'month':
      return <b>{t('donate.duration-2')}</b>;
    default:
      return <b>{t('donate.duration-4')}</b>;
  }
};

const RenderIlustration = ({
  recentlyClaimedBlock
}: {
  recentlyClaimedBlock: RecentlyClaimedBlock;
}) => {
  const showModalBears = useFeature('show-modal-bears').on;
  if (showModalBears) {
    if (recentlyClaimedBlock !== null) return <BearBlockCompletion />;
    else return <BearProgressModal />;
  } else if (recentlyClaimedBlock !== null) {
    return <Cup className='donation-icon' />;
  } else {
    return <Heart className='donation-icon' />;
  }
};

function getctaNumberBetween1To10() {
  const min = 1;
  const max = 10;
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function DonateModal({
  show,
  closeDonationModal,
  executeGA,
  location,
  recentlyClaimedBlock
}: DonateModalProps): JSX.Element {
  const [closeLabel, setCloseLabel] = React.useState(false);
  const [ctaNumber, setCtaNumber] = React.useState(0);
  const { t } = useTranslation();
  const handleProcessing = () => {
    setCloseLabel(true);
  };
Repository: freeCodeCamp/freeCodeCamp
File: client/src/templates/Challenges/classic/mobile-layout.tsx (TypeScript)

Code before:
      hasNotes,
      hasPreview,
      notes,
      preview,
      showPreviewPane,
      showPreviewPortal,
      removePortalWindow,
      setShowPreviewPane,
      setShowPreviewPortal,
      portalWindow,
      windowTitle,
      guideUrl,
      videoUrl,
      usesMultifileEditor
    } = this.props;

    const editorTabPaneProps = {
      mountOnEnter: true,
      unmountOnExit: true
    };

    const displayPreviewPane = hasPreview && showPreviewPane;
    const displayPreviewPortal = hasPreview && showPreviewPortal;

    const togglePane = (pane: string): void => {
      switch (pane) {
        case 'showPreviewPane':
          if (!showPreviewPane && showPreviewPortal)
            setShowPreviewPortal(false);
          setShowPreviewPane(!showPreviewPane);
          portalWindow?.close();
          removePortalWindow();
          break;
        case 'showPreviewPortal':
          if (!showPreviewPortal && showPreviewPane) setShowPreviewPane(false);
          setShowPreviewPortal(!showPreviewPortal);
          if (showPreviewPortal) {
            portalWindow?.close();
            removePortalWindow();
          }
          break;
        default:
          setShowPreviewPane(true);
          setShowPreviewPortal(false);
      }
    };

    // sets screen reader text for the portal button
    function getPortalBtnSrText() {
      // preview open in main window
      let portalBtnSrText = i18next.t('aria.move-preview-to-new-window');

Review comment (suggestion):
I feel like this is overly complex for a `switch` statement and should be an `if`.

Code after:
  render(): JSX.Element {
    const { currentTab } = this.state;
    const {
      hasEditableBoundaries,
      instructions,
      editor,
      testOutput,
      hasNotes,
      hasPreview,
      notes,
      preview,
      showPreviewPane,
      showPreviewPortal,
      removePortalWindow,
      setShowPreviewPane,
      setShowPreviewPortal,
      portalWindow,
      windowTitle,
      guideUrl,
      videoUrl,
      usesMultifileEditor
    } = this.props;

    const editorTabPaneProps = {
      mountOnEnter: true,
      unmountOnExit: true
    };

    const displayPreviewPane = hasPreview && showPreviewPane;
    const displayPreviewPortal = hasPreview && showPreviewPortal;

    const togglePane = (pane: string): void => {
      if (pane === 'showPreviewPane') {
        if (!showPreviewPane && showPreviewPortal) {
          setShowPreviewPortal(false);
        }
        setShowPreviewPane(!showPreviewPane);
        portalWindow?.close();
        removePortalWindow();
      } else if (pane === 'showPreviewPortal') {
        if (!showPreviewPortal && showPreviewPane) {
          setShowPreviewPane(false);
        }
        setShowPreviewPortal(!showPreviewPortal);
        if (showPreviewPortal) {
          portalWindow?.close();
          removePortalWindow();
        }
      } else {
        setShowPreviewPane(true);
        setShowPreviewPortal(false);
Repository: freeCodeCamp/freeCodeCamp
File: client/src/redux/index.js (JavaScript)

Code before:
import updateCompleteEpic from './update-complete-epic';
import { createUserTokenSaga } from './user-token-saga';

const defaultFetchState = {
  pending: true,
  complete: false,
  errored: false,
  error: null
};

export const defaultDonationFormState = {
  redirecting: false,
  processing: false,
  success: false,
  error: '',
  loading: {
    stripe: true,
    paypal: true
  }
};

const initialState = {
  appUsername: '',
  showMultipleProgressModals: false,
  recentlyClaimedBlock: null,
  completionCountWhenShownProgressModal: null,
  progressDonationModalShown: false,
  completionCount: 0,
  currentChallengeId: store.get(CURRENT_CHALLENGE_KEY),
  examInProgress: false,
  showCert: {},
  showCertFetchState: {
    ...defaultFetchState
  },
  showCodeAlly: false,
  user: {},
  userFetchState: {
    ...defaultFetchState
  },
  allChallengesInfo: {
    challengeEdges: [],
    certificateNodes: []
  },
  userProfileFetchState: {
    ...defaultFetchState
  },
  showDonationModal: false,
  showSignoutModal: false,
  isOnline: true,
  isServerOnline: true,
  renderStartTime: null,

Review comment (suggestion):
```suggestion
  completionCountWhenShownProgressModal: 0,
```
0 seems slightly nicer, but it's fine either way.

Code after:
import updateCompleteEpic from './update-complete-epic';
import { createUserTokenSaga } from './user-token-saga';

const defaultFetchState = {
  pending: true,
  complete: false,
  errored: false,
  error: null
};

export const defaultDonationFormState = {
  redirecting: false,
  processing: false,
  success: false,
  error: '',
  loading: {
    stripe: true,
    paypal: true
  }
};

const initialState = {
  appUsername: '',
  showMultipleProgressModals: false,
  recentlyClaimedBlock: null,
  completionCountWhenShownProgressModal: 0,
  progressDonationModalShown: false,
  completionCount: 0,
  currentChallengeId: store.get(CURRENT_CHALLENGE_KEY),
  examInProgress: false,
  showCert: {},
  showCertFetchState: {
    ...defaultFetchState
  },
  showCodeAlly: false,
  user: {},
  userFetchState: {
    ...defaultFetchState
  },
  allChallengesInfo: {
    challengeEdges: [],
    certificateNodes: []
  },
  userProfileFetchState: {
    ...defaultFetchState
  },
  showDonationModal: false,
  showSignoutModal: false,
  isOnline: true,
  isServerOnline: true,
  renderStartTime: null,
Repository: freeCodeCamp/freeCodeCamp
File: api/src/routes/user.ts (TypeScript)

Code before:
          where: { userId: req.session.user.id }
        });
        await fastify.prisma.user.update({
          where: { id: req.session.user.id },
          data: {
            progressTimestamps: [Date.now()],
            currentChallengeId: '',
            isRespWebDesignCert: false,
            is2018DataVisCert: false,
            isFrontEndLibsCert: false,
            isJsAlgoDataStructCert: false,
            isApisMicroservicesCert: false,
            isInfosecQaCert: false,
            isQaCertV7: false,
            isInfosecCertV7: false,
            is2018FullStackCert: false,
            isFrontEndCert: false,
            isBackEndCert: false,
            isDataVisCert: false,
            isFullStackCert: false,
            isSciCompPyCertV7: false,
            isDataAnalysisPyCertV7: false,
            isMachineLearningPyCertV7: false,
            isRelationalDatabaseCertV8: false,
            // TODO: check if schema should be updated with below field
            // isCollegeAlgebraPyCertV8: false
            completedChallenges: [],
            savedChallenges: [],
            partiallyCompletedChallenges: [],
            needsModeration: false
          }
        });

        return {};
      } catch (err) {
        fastify.log.error(err);
        void reply.code(500);
        return {
          message:
            'Oops! Something went wrong. Please try again in a moment or contact support@freecodecamp.org if the error persists.',
          type: 'danger'
        };
      }
    }
  );

  done();
};


Review comment (suggestion):
```suggestion
            isCollegeAlgebraPyCertV8: false
```
Yep, that can be set now.

Code after:
            isDataAnalysisPyCertV7: false,
            isMachineLearningPyCertV7: false,
            isRelationalDatabaseCertV8: false,
            isCollegeAlgebraPyCertV8: false,
            completedChallenges: [],
            savedChallenges: [],
            partiallyCompletedChallenges: [],
            needsModeration: false
          }
        });

        return {};
      } catch (err) {
        fastify.log.error(err);
        void reply.code(500);
        return {
          message:
            'Oops! Something went wrong. Please try again in a moment or contact support@freecodecamp.org if the error persists.',
          type: 'danger'
        };
      }
    }
  );

  done();
};
Repository: freeCodeCamp/freeCodeCamp
File: api/src/routes/user.test.ts (TypeScript)

Code before:
import { setupServer, superRequest } from '../../jest.utils';

const baseProgressData = {
  currentChallengeId: '',
  isRespWebDesignCert: false,
  is2018DataVisCert: false,
  isFrontEndLibsCert: false,
  isJsAlgoDataStructCert: false,
  isApisMicroservicesCert: false,
  isInfosecQaCert: false,
  isQaCertV7: false,
  isInfosecCertV7: false,
  is2018FullStackCert: false,
  isFrontEndCert: false,
  isBackEndCert: false,
  isDataVisCert: false,
  isFullStackCert: false,
  isSciCompPyCertV7: false,
  isDataAnalysisPyCertV7: false,
  isMachineLearningPyCertV7: false,
  isRelationalDatabaseCertV8: false,
  completedChallenges: [],
  savedChallenges: [],
  partiallyCompletedChallenges: [],
  needsModeration: false
};

const modifiedProgressData = {
  ...baseProgressData,
  currentChallengeId: 'hello there',
  isRespWebDesignCert: true,
  isJsAlgoDataStructCert: true,
  isRelationalDatabaseCertV8: true,
  needsModeration: true
};

describe('userRoutes', () => {
  setupServer();

  describe('Authenticated user', () => {
    let setCookies: string[];

    beforeEach(async () => {
      const res = await superRequest('/auth/dev-callback', { method: 'GET' });
      setCookies = res.get('Set-Cookie');
    });

Review comment (suggestion):
```suggestion
  isRelationalDatabaseCertV8: false,
  isCollegeAlgebraPyCertV8: false,
```

Code after:
import { setupServer, superRequest } from '../../jest.utils';

const baseProgressData = {
  currentChallengeId: '',
  isRespWebDesignCert: false,
  is2018DataVisCert: false,
  isFrontEndLibsCert: false,
  isJsAlgoDataStructCert: false,
  isApisMicroservicesCert: false,
  isInfosecQaCert: false,
  isQaCertV7: false,
  isInfosecCertV7: false,
  is2018FullStackCert: false,
  isFrontEndCert: false,
  isBackEndCert: false,
  isDataVisCert: false,
  isFullStackCert: false,
  isSciCompPyCertV7: false,
  isDataAnalysisPyCertV7: false,
  isMachineLearningPyCertV7: false,
  isRelationalDatabaseCertV8: false,
  isCollegeAlgebraPyCertV8: false,
  completedChallenges: [],
  savedChallenges: [],
  partiallyCompletedChallenges: [],
  needsModeration: false
};

const modifiedProgressData = {
  ...baseProgressData,
  currentChallengeId: 'hello there',
  isRespWebDesignCert: true,
  isJsAlgoDataStructCert: true,
  isRelationalDatabaseCertV8: true,
  needsModeration: true
};

describe('userRoutes', () => {
  setupServer();

  describe('Authenticated user', () => {
    let setCookies: string[];

    beforeEach(async () => {
      const res = await superRequest('/auth/dev-callback', { method: 'GET' });
      setCookies = res.get('Set-Cookie');
Repository: freeCodeCamp/freeCodeCamp
File: api/src/routes/donate.test.ts (TypeScript)

Code before:
import request from 'supertest';

import { setupServer, superRequest } from '../../jest.utils';

describe('Donate', () => {
  setupServer();

  describe('Authenticated User', () => {
    let setCookies: string[];

    // Authenticate user
    beforeAll(async () => {
      const res = await request(fastifyTestInstance.server).get(
        '/auth/dev-callback'
      );
      setCookies = res.get('Set-Cookie');
    });

    describe('POST /donate/add-donation', () => {
      it('should return 200 and update the user', async () => {
        const response = await superRequest('/donate/add-donation', {
          method: 'POST',
          setCookies
        }).send({
          isDonating: true
        });

        expect(response.status).toBe(200);
        expect(response.body).toEqual({
          isDonating: true
        });
      });

      it('should return 400 if the body is empty', async () => {
        const response = await superRequest('/donate/add-donation', {
          method: 'POST',
          setCookies
        }).send({});

        expect(response.status).toBe(400);
      });
    });
  });

  describe('Unauthenticated User', () => {
    describe('POST /donate/add-donation', () => {
      it('should return 403', async () => {
        const response = await superRequest('/donate/add-donation', {
          method: 'POST'
        }).send({
          isDonating: true

Review comment (suggestion):
```suggestion
        }).send({
          anything: true,
          itIs: 'ignored'
        });
```

Code after:
import request from 'supertest';

import { setupServer, superRequest } from '../../jest.utils';

describe('Donate', () => {
  setupServer();

  describe('Authenticated User', () => {
    let setCookies: string[];

    beforeEach(async () => {
      await fastifyTestInstance.prisma.user.updateMany({
        where: { email: 'foo@bar.com' },
        data: { isDonating: false }
      });
      const res = await request(fastifyTestInstance.server).get(
        '/auth/dev-callback'
      );
      setCookies = res.get('Set-Cookie');
    });

    describe('POST /donate/add-donation', () => {
      it('should return 200 and update the user', async () => {
        const response = await superRequest('/donate/add-donation', {
          method: 'POST',
          setCookies
        }).send({
          anything: true,
          itIs: 'ignored'
        });

        expect(response.status).toBe(200);
        expect(response.body).toEqual({
          isDonating: true
        });
      });

      it('should return 400 if the user is already donating', async () => {
        const successResponse = await superRequest('/donate/add-donation', {
          method: 'POST',
          setCookies
        }).send({});

        expect(successResponse.status).toBe(200);

        const failResponse = await superRequest('/donate/add-donation', {
          method: 'POST',
          setCookies
        }).send({});

        expect(failResponse.status).toBe(400);
Repository: freeCodeCamp/freeCodeCamp
File: client/src/components/search/redux/index.js (JavaScript)

Code before:
import { createAction, handleActions } from 'redux-actions';

import { createTypes } from '../../../utils/create-types';

export const ns = 'search';

const initialState = {
  query: '',
  indexName: 'news',
  isSearchDropdownEnabled: true,
  isSearchBarFocused: false
};

const types = createTypes(
  [
    'toggleSearchDropdown',
    'toggleSearchFocused',
    'updateSearchIndexName',
    'updateSearchQuery'
  ],
  ns
);

export const toggleSearchDropdown = createAction(types.toggleSearchDropdown);
export const toggleSearchFocused = createAction(types.toggleSearchFocused);
export const updateSearchQuery = createAction(types.updateSearchQuery);

export const isSearchDropdownEnabledSelector = state =>
  state[ns].isSearchDropdownEnabled;
export const isSearchBarFocusedSelector = state => state[ns].isSearchBarFocused;
export const searchQuerySelector = state => state[ns].query;

export const reducer = handleActions(
  {
    [types.toggleSearchDropdown]: (state, { payload }) => ({
      ...state,
      isSearchDropdownEnabled:
        typeof payload === 'boolean' ? payload : !state.isSearchDropdownEnabled
    }),
    [types.toggleSearchFocused]: (state, { payload }) => ({
      ...state,
      isSearchBarFocused: payload
    }),
    [types.updateSearchIndexName]: (state, { payload }) => ({
      ...state,
      indexName: payload
    }),
    [types.updateSearchQuery]: (state, { payload }) => {
      return {
        ...state,
        query: payload

Review comment (suggestion):
This also appears in the reducer and the `createTypes` call, so those can go too.

Code after:
import { createAction, handleActions } from 'redux-actions';

import { createTypes } from '../../../utils/create-types';

export const ns = 'search';

const initialState = {
  query: '',
  indexName: 'news',
  isSearchDropdownEnabled: true,
  isSearchBarFocused: false
};

const types = createTypes(
  ['toggleSearchDropdown', 'toggleSearchFocused', 'updateSearchQuery'],
  ns
);

export const toggleSearchDropdown = createAction(types.toggleSearchDropdown);
export const toggleSearchFocused = createAction(types.toggleSearchFocused);
export const updateSearchQuery = createAction(types.updateSearchQuery);

export const isSearchDropdownEnabledSelector = state =>
  state[ns].isSearchDropdownEnabled;
export const isSearchBarFocusedSelector = state => state[ns].isSearchBarFocused;
export const searchQuerySelector = state => state[ns].query;

export const reducer = handleActions(
  {
    [types.toggleSearchDropdown]: (state, { payload }) => ({
      ...state,
      isSearchDropdownEnabled:
        typeof payload === 'boolean' ? payload : !state.isSearchDropdownEnabled
    }),
    [types.toggleSearchFocused]: (state, { payload }) => ({
      ...state,
      isSearchBarFocused: payload
    }),
    [types.updateSearchQuery]: (state, { payload }) => {
      return {
        ...state,
        query: payload
      };
    }
  },
  initialState
);
Repository: freeCodeCamp/freeCodeCamp
File: api/src/plugins/redirect-with-message.test.ts (TypeScript)

Code before:
import Fastify, { FastifyInstance } from 'fastify';
import qs from 'query-string';

import redirectWithMessage from './redirect-with-message';

async function setupServer() {
  const fastify = Fastify();
  await fastify.register(redirectWithMessage);
  return fastify;
}

describe('redirectWithMessage plugin', () => {
  it('should decorate reply object with redirectWithMessage method', async () => {
    expect.assertions(3);

    const fastify = await setupServer();

    fastify.get('/', (_req, reply) => {
      expect(reply).toHaveProperty('redirectWithMessage');
      expect(reply.redirectWithMessage).toBeInstanceOf(Function);
      return { foo: 'bar' };
    });

    const res = await fastify.inject({
      method: 'GET',
      url: '/'
    });

    expect(res.statusCode).toEqual(200);
  });

  describe('redirectWithMessage method', () => {
    let fastify: FastifyInstance;
    beforeEach(async () => {
      fastify = await setupServer();
    });

Review comment (suggestion):
```suggestion

      const isString = (value: unknown): value is string => {
        return typeof value === 'string';
      };
```

Code after:
import Fastify, { FastifyInstance } from 'fastify';
import qs from 'query-string';

import redirectWithMessage from './redirect-with-message';

async function setupServer() {
  const fastify = Fastify();
  await fastify.register(redirectWithMessage);
  return fastify;
}

const isString = (value: unknown): value is string => {
  return typeof value === 'string';
};

describe('redirectWithMessage plugin', () => {
  it('should decorate reply object with redirectWithMessage method', async () => {
    expect.assertions(3);

    const fastify = await setupServer();

    fastify.get('/', (_req, reply) => {
      expect(reply).toHaveProperty('redirectWithMessage');
      expect(reply.redirectWithMessage).toBeInstanceOf(Function);
      return { foo: 'bar' };
    });

    const res = await fastify.inject({
      method: 'GET',
      url: '/'
    });

    expect(res.statusCode).toEqual(200);
  });

  describe('redirectWithMessage method', () => {
Repository: freeCodeCamp/freeCodeCamp
File: api/src/plugins/redirect-with-message.test.ts (TypeScript)

Code before:
import Fastify, { FastifyInstance } from 'fastify';
import qs from 'query-string';

import redirectWithMessage from './redirect-with-message';

async function setupServer() {
  const fastify = Fastify();
  await fastify.register(redirectWithMessage);
  return fastify;
}

describe('redirectWithMessage plugin', () => {
  it('should decorate reply object with redirectWithMessage method', async () => {
    expect.assertions(3);

    const fastify = await setupServer();

    fastify.get('/', (_req, reply) => {
      expect(reply).toHaveProperty('redirectWithMessage');
      expect(reply.redirectWithMessage).toBeInstanceOf(Function);
      return { foo: 'bar' };
    });

    const res = await fastify.inject({
      method: 'GET',
      url: '/'
    });

    expect(res.statusCode).toEqual(200);
  });

  describe('redirectWithMessage method', () => {
    let fastify: FastifyInstance;
    beforeEach(async () => {
      fastify = await setupServer();

Review comment (suggestion):
Can you walk me through the need for us to setupServer, instead of using the one similar to the routes.

https://github.com/ojeytonwilliams/freeCodeCamp/blob/f88b2adebcbdea085b43e3de51a5199075499a82/api/jest.utils.ts#L62-L76

Code after:
import Fastify, { FastifyInstance } from 'fastify';
import qs from 'query-string';

import redirectWithMessage from './redirect-with-message';

async function setupServer() {
  const fastify = Fastify();
  await fastify.register(redirectWithMessage);
  return fastify;
}

const isString = (value: unknown): value is string => {
  return typeof value === 'string';
};

describe('redirectWithMessage plugin', () => {
  it('should decorate reply object with redirectWithMessage method', async () => {
    expect.assertions(3);

    const fastify = await setupServer();

    fastify.get('/', (_req, reply) => {
      expect(reply).toHaveProperty('redirectWithMessage');
      expect(reply.redirectWithMessage).toBeInstanceOf(Function);
      return { foo: 'bar' };
    });

    const res = await fastify.inject({
      method: 'GET',
      url: '/'
    });

    expect(res.statusCode).toEqual(200);
  });