Juni_Dev_log

(200128_TIL) 'Bank Account' 본문

CodingTest/Exercism

(200128_TIL) 'Bank Account'

Juni_K 2021. 1. 28. 10:47

▶ Bank Account

 

Bank Account

(Problem)

Introduction

Simulate a bank account supporting opening/closing, withdrawals, and deposits of money. Watch out for concurrent transactions!

A bank account can be accessed in multiple ways. Clients can make deposits and withdrawals using the internet, mobile phones, etc. Shops can charge against the account.

Create an account that can be accessed from multiple threads/processes (terminology depends on your programming language).

It should be possible to close an account; operations against a closed account must fail.

 

- 은행 계좌에 개설/폐쇄, 인출, 예금 등을 가정해보자.

- 동시적으로 거래하는 것을 지켜보자.

 

Tip)

1. open() 을 통해서 은행 계좌를 먼저 열어야한다.

2. deposit(100)은, 100원을 예금하는 것이다.

3. withdraw(50)은, 50원을 인출하는 것이다.

4. open() 이후에 close()를 하고서 accout.balance 를 호출하면, "ValueError"를 보여준다.

5. close() 이후에 deposit / withdraw를 하면 "ValueError"를 반환한다.

6. open() 을 하지않고, close()를 하면 "ValueError"를 반환한다.

7. open() 을 하고, 또 open()을 하면 "ValueError"를 반환한다.

8. open() -> close() -> open() 하면, 다시 은행 돈은 0으로 된다.

9. 예금한 돈보다 더 큰 돈을 인출하려고하면, "ValueError"를 반환한다.

10. withdraw()의 매개변수 값으로는 "-"가 들어가지 못한다.

11. deposit()의 매개변수 값으로는 "-" 가 들어가지 못한다.

 

(Solution)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//
// This is only a SKELETON file for the 'Bank Account' exercise. It's been provided as a
// convenience to get you started writing code faster.
//
 
export class BankAccount {
  constructor() {
    // Initial value starts with 0. (_balance is 0)
    this._balance = 0;
    // Initial status starts with false.
    this.status = false;
  }
 
  open() {
    // When open() again after open(), the if statement to check.
    if(this.status === true){
        // throw ValueError as an error
        throw new ValueError();
    }
    // changes status to true.
    this.status = true;
  }
 
  close() {
    // ① without open(), call close() ② close() twice
    if(this.status === false){
        // throw ValueError as an error.
        throw new ValueError();
    }
    // changes status to false and set Initial value to 0.
    this.status = false;
    this._balance = 0;
  }
 
  deposit(money) {
    // ① money is negative (<0) ② no open()
    if((money < 0)|| (this.status === false)){
        // throw ValueError as an error.
        throw new ValueError;
    }
    // add money to _balance.
    this._balance += money;
  }
 
  withdraw(money) {
    // ① money is negative (<0) ② no open() ③ Withdrawing more money than you have
    if((money < 0|| (this.status === false|| (this._balance < money)){
        // throw ValueError as an error.
        throw new ValueError;
    }
    // subtract money to _balance.
    this._balance -= money;
  }
 
  get balance() {
    // when status is false, throw ValueError.
    if (this.status === false){
        throw new ValueError;
    }
    // return _balance
    return this._balance;
  }
}
 
export class ValueError extends Error {
  constructor() {
    super('Bank account error');
  }
}
 
cs

- class 를 만들어서 작성하는 코드이다. 

(클래스로 작성하는 이유는 코드를 재사용하기 쉽기 때문에 class 안에 자주 사용하는 코드를 메서드로 정의하고 재사용하는 것이 훨씬 더 편하다.)

 

developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes

 

Classes - JavaScript | MDN

Class는 객체를 생성하기 위한 템플릿입니다. 클래스는 데이터와 이를 조작하는 코드를 하나로 추상화합니다. 자바스크립트에서 클래스는 프로토타입을 이용해서 만들어졌지만 ES5의 클래스 의

developer.mozilla.org

- class를 실행할 때, _balance (해당 사용자가 가지고 있는 돈 합계) 를 0으로 만들고, status (해당 계좌 상태) 를 false로 설정한다. (constructor() 에 들어가는 코드)

 

-  BankAccount 클래스 안에 있는 메서드 open()을 사용하면, if문을 통해서 status를 true로 바꿔주고, 만약 false라면 해당 문제에서 에러를 반환하는 ValueError()를 호출해준다.

 

- close() 메서드를 사용하면, status를 false로 바꿔주고, 가지고 있던 돈(_balance)을 다시 0으로 만든다.

(open()없이 close()를 했을 때, close()를 두번했을 때 status가 false일 때 에러를 보여준다.)

 

- deposit(money) 를 사용하면, _balance에 money를 더해준다. deposit 을 할때는 open() 이후에 해야하기에, status가 false일때 오류를 보여준다. 또한 money는 음수가 되면 안된다.

 

- withdraw(money) 메서드를 사용하면, _balance에 money를 뺀다. 만약, status가 false이거나, money가 음수이거나, 가지고 있는 돈(_balance)보다 인출하려는 돈(money)이 많을 때, 에러를 반환한다.

 

- balance() 메서드를 사용해서, 기존에 했었던 open() / close() / deposit() / withdraw() 를 통해서 만들어진 _balance 값 (해당 은행에 들어있는 돈)을 반환한다.

 

(참고)

opentutorials.org/module/532/4724

 

조건문 - JavaScript

Boolean '비교 수업'에서 비교 연산의 결과로 참(true)이나 거짓(false)을 얻을 수 있다고 배웠다. 여기서 참과 거짓은 '숫자와 문자 수업'에서 배운 숫자와 문자처럼 언어에서 제공하는 데이터 형이다

opentutorials.org

guswnsxodlf.github.io/javascript-equal-operator

 

Javascript '=='와 '===' 연산자 차이

’==’와 ‘===’의 차이

guswnsxodlf.github.io

 

'CodingTest > Exercism' 카테고리의 다른 글

(200131_TIL) 'Leap'  (0) 2021.01.31
(200130_TIL) 'Matrix'  (0) 2021.01.30
(200127_TIL) 'Pangram'  (0) 2021.01.27
(200126_TIL) 'Space Age'  (0) 2021.01.26
(200125_TIL) 'Gigasecond', 'RNA Transcription'  (0) 2021.01.25
Comments