Skip to content
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

[holee] typescript-calculator #2

Open
wants to merge 25 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
2b4c4cc
chore: gitignore, prettierc, tsconfing, package.json, cypress
hochan222 Jun 1, 2021
a7106a8
docs: cypress examples 둘러보기 완료
hochan222 Jun 1, 2021
22e4a32
chore: config typescript setting
hochan222 Jun 1, 2021
13f5f8d
tsconfig.json: Build:No inputs were found in config file
hochan222 Jun 1, 2021
e4cd2a7
feat: add initial value & Render digit when button clicked & Render d…
hochan222 Jun 1, 2021
3c7d913
chore: typescript를 시작하기위한 기본 설정 설정 완료
hochan222 Jun 1, 2021
62f2112
test: 0 부터 9까지 버튼 클릭 후 값출력 완료
hochan222 Jun 1, 2021
5269a22
test: make case: Max input length 3
hochan222 Jun 1, 2021
2e706bd
feat: add Max input length 3
hochan222 Jun 1, 2021
517bbe2
refactor: testcase 함수로 묶어서 리펙토링함
hochan222 Jun 1, 2021
8f301d1
test: add case Calculate two input when button click
hochan222 Jun 1, 2021
aaf5cbb
feat: add operator
hochan222 Jun 1, 2021
e0c8df6
feat: add Calculate two input when button click
hochan222 Jun 1, 2021
9207148
refactor: test case, = 버튼도 눌르게 변경
hochan222 Jun 1, 2021
185e02f
feat: 연산자 기능 구현 완료
hochan222 Jun 1, 2021
85bf0ed
feat: 계산 결과를 표현할 때 소수점 이하는 버림한다.
hochan222 Jun 1, 2021
1ab968c
chore: add test case 계산 결과를 표현할 때 소수점 이하는 버림한다.
hochan222 Jun 1, 2021
2a78429
feat: AC(All Clear) 버튼을 누를때 total을 0으로 변경한다.
hochan222 Jun 1, 2021
33ea372
feat: operator가 연속으로 나왔을때 한개만 적용되도록 처리
hochan222 Jun 1, 2021
d00ae27
feat: operator가 2번이상 나왔을때 한개만 적용되도록 처리
hochan222 Jun 1, 2021
6b7a4c5
refactor: 함수 파일별로 나누기
hochan222 Jun 1, 2021
b07c74b
feat: add init func
hochan222 Jun 1, 2021
91944e8
feat: 정규표현시 할당 된 변수 타입 구체적으로 변경
hochan222 Jun 2, 2021
041dfb5
feat: 정규표현시 할당 된 변수 타입 구체적으로 변경
hochan222 Jun 2, 2021
04b7bbe
fix: Uncaught TypeError: Cannot read property '1' of null(…)
hochan222 Jun 2, 2021
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
15 changes: 15 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"env": {
"browser": true,
"es2021": true
},
"extends": ["airbnb-base"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"plugins": ["@typescript-eslint"],
"ignorePatterns": ["dist/", "node_modules/"],
"rules": {}
}
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
# Created by https://www.toptal.com/developers/gitignore/api/vscode,node,intellij
# Edit at https://www.toptal.com/developers/gitignore?templates=vscode,node,intellij

.vscode/

### macOS ###
# General
.DS_Store
Expand Down Expand Up @@ -249,7 +251,6 @@ typings/

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
Expand Down
5 changes: 5 additions & 0 deletions .prettierc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"parser": "typescript",
"singleQuote": true,
"trailingComma": "all"
}
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"
}
192 changes: 192 additions & 0 deletions cypress/integration/counter.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
const testInputClickEvent = (first, result) => {
for (let item of first) {
cy.get('.digit')
.contains(item)
.click();
}
cy.get('#total').should('have.text', result);
};
Comment on lines +1 to +8
Copy link

Choose a reason for hiding this comment

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

함수로 분리하니까 훨씬 깔끔하고 좋네요


const testTwoInputCalculateEvent = (first, oper, second, result) => {
for (let item of first) {
cy.get('.digit')
.contains(item)
.click();
}
for (let item of oper) {
cy.get('.operations')
.contains(item)
.click();
}
for (let item of second) {
cy.get('.digit')
.contains(item)
.click();
}
cy.get('.operations')
.contains('=')
.click();
cy.get('#total').should('have.text', result);
};

describe('initial value', () => {
beforeEach(() => {
cy.visit('/javascript-calculator/');
});
it('total value', () => {
cy.get('#total').should('have.text', '0');
});
});

describe('Render digit when button clicked', () => {
beforeEach(() => {
cy.visit('/javascript-calculator/');
});
it('button 0', () => {
testInputClickEvent([0], '0');
});
it('button 1', () => {
testInputClickEvent([1], '1');
});
it('button 2', () => {
testInputClickEvent([2], '2');
});
it('button 3', () => {
testInputClickEvent([3], '3');
});
it('button 4', () => {
testInputClickEvent([4], '4');
});
it('button 5', () => {
testInputClickEvent([5], '5');
});
it('button 6', () => {
testInputClickEvent([6], '6');
});
it('button 7', () => {
testInputClickEvent([7], '7');
});
it('button 8', () => {
testInputClickEvent([8], '8');
});
it('button 9', () => {
testInputClickEvent([9], '9');
});
});

describe('Render max input length 3 when button click', () => {
beforeEach(() => {
cy.visit('/javascript-calculator/');
});
it('button 1 2', () => {
testInputClickEvent([1, 2], '12');
});
it('button 4 2', () => {
testInputClickEvent([4, 2], '42');
});
it('button 0 2', () => {
testInputClickEvent([0, 2], '2');
});
it('button 1 2 3', () => {
testInputClickEvent([1, 2, 3], '123');
});
it('button 1 2 3 4', () => {
testInputClickEvent([1, 2, 3, 4], '123');
});
});

describe('Calculate two input when button click', () => {
beforeEach(() => {
cy.visit('/javascript-calculator/');
});
it('button 1 + 2', () => {
testTwoInputCalculateEvent([1], ['+'], [2], '3');
});
it('button 1234567 + 1234567', () => {
testTwoInputCalculateEvent(
[1, 2, 3, 4, 5, 6, 7],
['+'],
[1, 2, 3, 4, 5, 6, 7],
'246'
);
});
it('button 42424242 + 42424242', () => {
testTwoInputCalculateEvent(
[4, 2, 4, 2, 4, 2, 4, 2],
['+'],
[4, 2, 4, 2, 4, 2, 4, 2],
'848'
);
});
});

describe('계산 결과를 표현할 때 소수점 이하는 버림한다.', () => {
beforeEach(() => {
cy.visit('/javascript-calculator/');
});
it('button 1 / 3', () => {
testTwoInputCalculateEvent([1], ['/'], [3], '0');
});
it('button 3 / 2', () => {
testTwoInputCalculateEvent([3], ['/'], [2], '1');
});
it('button 5 / 2', () => {
testTwoInputCalculateEvent([5], ['/'], [2], '2');
});
});

describe('AC(All Clear) 버튼을 누를때 total을 0으로 변경한다.', () => {
beforeEach(() => {
cy.visit('/javascript-calculator/');
});
it('button 1 / 3', () => {
testTwoInputCalculateEvent([5], ['/'], [2], '2');
cy.get('.modifier').click();
cy.get('#total').should('have.text', '0');
});
it('button 1234567 + 1234567', () => {
testTwoInputCalculateEvent([1, 2, 3, 4], ['+'], [1, 2, 3, 4], '246');
cy.get('.modifier').click();
cy.get('#total').should('have.text', '0');
});
});

describe('operator가 연속으로 나왔을때 한개만 적용되도록 처리', () => {
beforeEach(() => {
cy.visit('/javascript-calculator/');
});
it('button 1 /// 3', () => {
testTwoInputCalculateEvent([5], ['/', '/', '/'], [2], '2');
cy.get('.modifier').click();
cy.get('#total').should('have.text', '0');
});
it('button 4 +++++ 2', () => {
testTwoInputCalculateEvent([4], ['+', '+', '+', '+', '+'], [2], '6');
cy.get('.modifier').click();
cy.get('#total').should('have.text', '0');
});
});

describe('operator가 2번이상 나왔을때 한개만 적용되도록 처리', () => {
beforeEach(() => {
cy.visit('/javascript-calculator/');
});
it('button 1 + 3 + =', () => {
cy.get('.digit')
.contains('4')
.click();
cy.get('.operations')
.contains('+')
.click();
cy.get('.digit')
.contains('2')
.click();
cy.get('.operations')
.contains('+')
.click();
cy.get('.operations')
.contains('=')
.click();
cy.get('#total').should('have.text', '6');
});
});
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')
File renamed without changes.
File renamed without changes
File renamed without changes
22 changes: 22 additions & 0 deletions dist/js/calculate-util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const calculateOperator = (total, operator, num) => {
let result = 0;
if (operator === '+')
result = total + num;
if (operator === '/')
result = total / num;
if (operator === '%')
result = total % num;
Comment on lines +7 to +8
Copy link

Choose a reason for hiding this comment

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

프로그램에서 % 연산이 쓰이는 것 같진 않네요

Copy link
Member Author

Choose a reason for hiding this comment

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

앗앗 맞아요 ㅎㅎ 예전에 쓰던 함수를 그대로 긁어와서 레거시가 생겼네요..!

if (operator === '-')
result = total - num;
if (operator === 'X')
result = total * num;
return result;
};
const calculateResult = (total) => {
const result = total.match(new RegExp('(\\-?[\\d]{1,3})(X|\\-|\\+|\\/|\\=)(\\-?[\\d]{1,3})'));
if (result) {
return calculateOperator(Number(result[1]), result[2], Number(result[3]));
}
return 0;
};
export { calculateResult };
16 changes: 16 additions & 0 deletions dist/js/check.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export const checkValidInput = (total) => {
const result = total.match(new RegExp('(\\-?[\\d]{1,3})(X|\\-|\\+|\\/|\\=)?(\\-?[\\d]{1,3})?'));
if (!result) {
return '';
}
if (result[2] === undefined) {
if (result[1] === undefined) {
return '';
}
return result[1];
}
if (result[3] === undefined) {
return result[1] + result[2];
}
return result[1] + result[2] + result[3];
};
40 changes: 40 additions & 0 deletions dist/js/controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { getCountOperationdataSet, setCountOperationdataSet } from './operation-data-set.js';
import { checkValidInput } from './check.js';
import { calculateResult } from './calculate-util.js';
const digitClickEvent = (e) => {
const eventTarget = e.target;
const totalTarget = document.getElementById('total');
if (Number(totalTarget.innerText) === 0) {
document.getElementById('total').innerText = eventTarget.innerText;
}
else {
const result = checkValidInput(document.getElementById('total').innerText + eventTarget.innerText);
if (result === '') {
return;
}
document.getElementById('total').innerText = result;
}
};
const operatorEvent = (e) => {
const eventTarget = e.target;
const totalTarget = document.getElementById('total');
if (eventTarget.innerText === '=') {
setCountOperationdataSet('0');
document.getElementById('total').innerText = String(Math.floor(calculateResult(document.getElementById('total').innerText)));
return;
}
if (Number(totalTarget.innerText) === 0) {
return;
}
else if (!['/', '-', 'X', '+'].includes(totalTarget.innerText[totalTarget.innerText.length - 1])) {
Copy link
Member

Choose a reason for hiding this comment

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

이 부분도 정규표현식을 이용할 수 있지 않을까요?

Copy link
Member Author

Choose a reason for hiding this comment

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

오.. 맞아요 test 문법을 사용하면 간단하게 표현가능할 수 있을것 같아요!

if (getCountOperationdataSet() === '1') {
return;
}
setCountOperationdataSet('1');
document.getElementById('total').innerText += eventTarget.innerText;
}
};
const ACEvent = () => {
document.getElementById('total').innerText = '0';
};
export { digitClickEvent, operatorEvent, ACEvent };
Loading