スマレジエンジニアyushiのブログ

スマレジエンジニアのブログ

【テトリス #4】ESLint・テストコードの導入

テトリスを作っています。

テトリス カテゴリーの記事一覧 - スマレジエンジニアyushiのブログ

技術スタックは下記の通りです。

  • TypeScript
  • React
  • SCSS
  • Create React App

今回は、ESLintの導入やテストコードの記述をしてみます。

ESLintの導入

ESLintを導入します。

https://eslint.org/

今回は、TypeScript・React用のプラグインなどを同時に入れます。

npm i -D eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-plugin-react

ESLint用の設定ファイルも用意します。

(.eslintrc.json)

module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:@typescript-eslint/recommended',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: ['react', '@typescript-eslint'],
  rules: {},
  overrides: [
    {
      files: ['.eslintrc.js'],
      env: {
        node: true,
      },
    },
    {
      files: ['*.tsx'],
      rules: {
        'react/jsx-uses-react': 'off',
        'react/react-in-jsx-scope': 'off',
      },
    },
  ],
};

回転ロジックとテストコード作成

ブロックを回転できるようにします。

ロジックを用意します。

export const turnOnce = (
  x: number,
  y: number,
  centerX: number,
  centerY: number
) => [centerX + y - centerY, centerY - (x - centerX)];

この引数の値は、前回の記事に関連します。

https://yushi-dev.hatenablog.com/#ブロック形状情報の修正

引数のx・yは前回記事のtiles、引数のcenterX・centerYは前回の記事のcenterに対応します。

テストコードの記述

次に先ほどのロジックのテストコードを記述します。

import * as block from './index';

test('turnOnce', () => {
  const dataSet: [number, number, number, number, number, number][] = [
    // centerが0だった場合
    [1, 1, 0, 0, 1, -1],
    [-1, -1, 0, 0, -1, 1],
    [2, -1, 0, 0, -1, -2],
    [-1, 3, 0, 0, 3, 1],

    // centerが0以外の場合
    [4, 4, 3, 3, 4, 2],
    [2, 2, 3, 3, 2, 4],
    [0, 0, 0.5, 0.5, 0, 1],
    [1, 1, 0.5, 0.5, 1, 0],
  ];

  for (const [x, y, centerX, centerY, resultX, resultY] of dataSet) {
    expect(block.turnOnce(x, y, centerX, centerY)).toStrictEqual([
      resultX,
      resultY,
    ]);
  }
});

テストデータを事前にdataSetとして用意し、forループで順番に実行します。

テスト用のライブラリはCRAに含まれているので、それをそのまま実行します。

npm run test

Pull Request

あとがき

ESLintやテストコードはその有無で可読性や安全性が大きく変わります。

スマレジでのプロダクト開発においても、それらを活用しつつレガシー改善を行っています。