Skip to content

Calculator 과제 제출합니다 #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"env": {
"browser": true,
"es2021": true,
"cypress/globals": true
},
"extends": [
"airbnb-base",
"plugin:cypress/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"plugins": [
"@typescript-eslint",
"cypress"
],
"rules": {
"no-console": "off"
}
}
Comment on lines +1 to +23

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eslint 설정을 자세하게 하는 법을 저도 배워야겠네요 👍

1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
src/js/*

# Created by https://www.toptal.com/developers/gitignore/api/vscode,node,intellij
# Edit at https://www.toptal.com/developers/gitignore?templates=vscode,node,intellij
Expand Down
3 changes: 3 additions & 0 deletions cypress.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"baseUrl": "http://127.0.0.1:5500"
}
5 changes: 5 additions & 0 deletions cypress/fixtures/example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "Using fixtures to represent data",
"email": "[email protected]",
"body": "Fixtures are a great way to mock data for responses to routes"
}
167 changes: 167 additions & 0 deletions cypress/integration/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
describe("Calculator module", () => {
const testClickResult = (fomular: string, result: string) => (
fomular
.split('')
.reduce<Cypress.Chainable<JQuery<HTMLElement>>>(
(cyObj: Cypress.Chainable<JQuery<HTMLElement>>, f: string) => (
cyObj
.get(/\d/.test(f) ? '.digit' : '.operation')
.contains(f)
.click()
),
cy)
.get('#total').should((elem) => {
expect(elem.text()).to.equal(result);
})
Comment on lines +5 to +15

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 부분에서 저도 테스트 코드 작성하는 방법 배워갑니다!

그런데 click하는 부분이랑 검증하는 부분이랑 나눠져있었다면 어땠을까요?

)

it("renders form of calculator", () => {
cy.visit('/');
cy.get('#total').should('contain', '0');

cy.get('.calculator').contains('0');
cy.get('.digit').contains('1');
cy.get('.digit').contains('2');
cy.get('.digit').contains('3');
cy.get('.digit').contains('4');
cy.get('.digit').contains('5');
cy.get('.digit').contains('6');
cy.get('.digit').contains('7');
cy.get('.digit').contains('8');
cy.get('.digit').contains('9');

cy.get('.modifier').contains('AC');

cy.get('.operation').contains('+');
cy.get('.operation').contains('-');
cy.get('.operation').contains('X');
cy.get('.operation').contains('/');
cy.get('.operation').contains('=');
});

it("show numbers when digit button clicked", () => {
cy.reload();
testClickResult('12', '12');

cy.reload();
testClickResult('694', '694');

cy.reload();
testClickResult('000', '0');

cy.reload();
testClickResult('0001', '1');

cy.reload();
testClickResult('00404', '404');
});

it("cannot input more than 3 digits", () => {
cy.reload();
testClickResult('1234', '123');

cy.reload();
testClickResult('0013007', '130');

cy.reload();
testClickResult('0987654321', '987');
});

it("calculate plus operator", () => {
cy.reload();
testClickResult('1+3=', '4');

cy.reload();
testClickResult('1+3+5=', '9');

cy.reload();
testClickResult('10000+200000=', '300');

cy.reload();
testClickResult('10000+200000=+3211111=', '621');
});

it("calculate minus operator", () => {
cy.reload();
testClickResult('3-1=', '2');

cy.reload();
testClickResult('3333333-11111111=', '222');

cy.reload();
testClickResult('332-99999999=', '-667');
});

it("calculate multiple operator", () => {
cy.reload();
testClickResult('1X2X4X4=', '32');

cy.reload();
testClickResult('1X2X4X0X2=', '0');

cy.reload();
testClickResult('123X456=', '56088');
});

it("calculate divide operator", () => {
cy.reload();
testClickResult('752/2=', '376');

cy.reload();
testClickResult('1/454231234=', '0');

cy.reload();
testClickResult('4632345/1234=', '3');

cy.reload();
testClickResult('123/0=', 'Infinity');
});

it("don't calculate before next operator", () => {
cy.reload();
testClickResult('1+3', '3');

cy.reload();
testClickResult('34X0012', '12');

cy.reload();
testClickResult('2X20+0', '0');
});

it("calculate last operator when multiple operator input", () => {
cy.reload();
testClickResult('1+X/-2=', '-1');

cy.reload();
testClickResult('3+++++++-2=', '1');

cy.reload();
testClickResult('34651-X0=', '0');
});

it("calculate with zero when operator button is pressed for the first time", () => {
cy.reload();
testClickResult('X3=', '0');

cy.reload();
testClickResult('-10=', '-10');
});

it("operate AC button", () => {
cy.get('.modifier').click().get('#total').should((elem) => {
expect(elem.text()).to.equal('0');
});

testClickResult('123+123X', '246')
.get('.modifier').click()
.get('#total').should((elem) => {
expect(elem.text()).to.equal('0');
})
.get('.operation').contains('X').click()
.get('.digit').contains('3').click()
.get('.operation').contains('=').click()
.get('#total').should((elem) => {
expect(elem.text()).to.equal('0');
});
});
});

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

꼼꼼한테스트 저도 본받아야겠습니다.

22 changes: 22 additions & 0 deletions cypress/plugins/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/// <reference types="cypress" />
// ***********************************************************
// This example plugins/index.js can be used to load plugins
//
// You can change the location of this file or turn off loading
// the plugins file with the 'pluginsFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/plugins-guide
// ***********************************************************

// This function is called when a project is opened or re-opened (e.g. due to
// the project's config changing)

/**
* @type {Cypress.PluginConfig}
*/
// eslint-disable-next-line no-unused-vars
module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
}
25 changes: 25 additions & 0 deletions cypress/support/commands.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add('login', (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })
20 changes: 20 additions & 0 deletions cypress/support/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// ***********************************************************
// This example support/index.js is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************

// Import commands.js using ES2015 syntax:
import './commands'

// Alternatively you can use CommonJS syntax:
// require('./commands')
8 changes: 8 additions & 0 deletions cypress/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["es5", "dom"],
"types": ["cypress"]
},
"include": ["**/*.ts"]
}
Comment on lines +1 to +8

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cypress에서도 tsconfig 파일이 필요했군요...! 알아갑니다 👍

15 changes: 15 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
## 기능 구현 목록
- [x] 개발 환경 구축
- [x] eslint-airbnb + typescript 환경 구축
- [x] cypress 환경 구축
- [x] 테스트 작성
- [x] 입력에 관련된 테스트를 작성
- [x] 기본적인 연산에 대한 테스트를 작성
- [x] AC 버튼에 대한 테스트를 작성
- [x] 기능 요구사항 구현
- [x] 숫자 버튼을 눌렀을 때 숫자가 입력되야함
- [x] 3자리수 초과 숫자는 입력되지 않아야 함
- [x] 기본적인 계산에 대한 기능 구현
- [x] 계산 결과가 예상 범위 밖 (예. NaN)에 대한 에러 처리
- [x] 나온 결과를 연속으로 계산할 수 있는 기능 구현
- [x] AC 버튼 기능 구현
1 change: 1 addition & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,6 @@ <h1 id="total">0</h1>
</div>
</div>
</div>
<script type="module" src="src/js/index.js"></script>
</body>
</html>
22 changes: 22 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "javascript-calculator",
"version": "1.0.0",
"main": "index.html",
"repository": "https://github.com/cos18/javascript-calculator.git",
"author": "Sungwoo Park <[email protected]>",
"license": "MIT",
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^4.28.0",
"@typescript-eslint/parser": "^4.28.0",
"cypress": "^7.6.0",
"eslint": "^7.29.0",
"eslint-config-airbnb-base": "^14.2.1",
"eslint-plugin-import": "^2.23.4",
"typescript": "^4.3.4"
},
"scripts": {
"build": "yarn tsc --watch",
"lint": "yarn eslint",
"test": "yarn cypress open"
}
}
3 changes: 3 additions & 0 deletions src/ts/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import calculator from './module/calculator.js';

calculator();
47 changes: 47 additions & 0 deletions src/ts/module/calculator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import operateResult from "../util/operate.js";

export default function calculator() {
let prevVal: number | undefined = undefined;
let currVal: number | undefined = undefined;
let op = '';

const totalH1 = document.getElementById('total');

function onDigitClicked(e: Event) {
if (currVal === undefined || op === '=')
currVal = 0;
if (100 <= currVal && currVal < 1000)
return;
if (e.target instanceof HTMLElement) {
currVal *= 10;
currVal += Number(e.target.innerHTML);
}
totalH1!.innerHTML = String(currVal);
}

function onOperationClicked(e: Event) {
if (currVal !== undefined) {
prevVal = operateResult(prevVal ?? 0, currVal ?? 0, op);
Copy link

@kmin-283 kmin-283 Jun 28, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

operateResult에서 prevVal, currVal의 기본값으로 0을 받도록 하면 더 깔끔해질 것 같습니다!

currVal = undefined;
totalH1!.innerHTML = String(prevVal);
}
if (e.target instanceof HTMLElement) {
op = e.target.innerHTML;
if (op === '=') {
currVal = prevVal;
prevVal = undefined;
}
}
}

function onACClicked() {
prevVal = undefined;
currVal = undefined;
op = '';
totalH1!.innerHTML = '0';
}

document.getElementsByClassName('digits')[0].addEventListener('click', onDigitClicked);
document.getElementsByClassName('operations')[0].addEventListener('click', onOperationClicked);
document.getElementsByClassName('modifier')[0].addEventListener('click', onACClicked);
}
Loading