From aedf8d7c79c177fb4adc725156f5c464ae563b15 Mon Sep 17 00:00:00 2001 From: "petr.diukin" Date: Thu, 8 Apr 2021 14:46:28 +0500 Subject: [PATCH 1/3] =?UTF-8?q?=D0=94=D1=8E=D0=BA=D0=B8=D0=BD=20=D0=9F?= =?UTF-8?q?=D0=B5=D1=82=D1=80=20-=20ts2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/task_1/index.ts | 60 +++++++++++++++++++++++------------------- src/task_2/index.ts | 37 +++++++------------------- src/task_3/index.ts | 48 ++++++++++++---------------------- src/task_4/index.ts | 33 +++++++++--------------- src/task_5/index.ts | 63 +++++++++++++++++++++++---------------------- 5 files changed, 104 insertions(+), 137 deletions(-) diff --git a/src/task_1/index.ts b/src/task_1/index.ts index 5827d9c..e24f468 100644 --- a/src/task_1/index.ts +++ b/src/task_1/index.ts @@ -1,46 +1,52 @@ -/** Задача 1 - MoneyRepository - * Имеется класс денежного хранилища - MoneyRepository. - * Который должен хранить денежные единицы - * разных валют, разного номинала и в разном количестве. - * Требуется: - * 1) Реализовать классу MoneyRepository 2 метода: - * 1.1) giveOutMoney - позволяет достать денежные единицы из хранилища по принципу жадного алгоритма: - * сумма 1350RUB будет выдана - * одной купюрой номиналом 1000RUB, - * одной купюрой номиналом 200RUB, - * одной купюрой номиналом 100RUB, - * одной купюрой номиналом 50RUB - * с учетом, что все эти купюры будут находится в хранилище. - * Принимает аргументы count - сумма, требуемая к выдаче, currency - валюта - * Если сумма была собрана и выдана, то метод возвращает true, иначе false - * 1.2) takeMoney - позволяет положить в хранилище денежные единицы разных номиналов и разного количества - * 2) Типизировать все свойства и методы класса MoneyRepository, - * пользуясь уже предоставленными интерфейсами (избавиться от всех any типов) -*/ - import { Currency } from '../enums'; - interface IMoneyInfo { denomination: string; currency: Currency; } - export interface IMoneyUnit { moneyInfo: IMoneyInfo; count: number; } export class MoneyRepository { - private _repository: any; - constructor(initialRepository: any) { + private _repository: Array; + constructor(initialRepository: Array) { this._repository = initialRepository; } - public giveOutMoney(count: any, currency: any): any { - + private order(a: IMoneyUnit, b: IMoneyUnit): number{ + return a.moneyInfo.denomination.length > b.moneyInfo.denomination.length ? -1 : + a.moneyInfo.denomination.length < b.moneyInfo.denomination.length ? 1 : + a.moneyInfo.denomination > b.moneyInfo.denomination ? -1 : 1; } - public takeMoney(moneyUnits: any): any { + public giveOutMoney(count: number, currency: Currency): boolean { + let temp = count; + const dollars = [1, 2, 5, 10, 20, 50, 100]; + const rubles = [10, 50, 100, 500, 1000, 5000]; + this._repository.forEach(e => { + for (let key in e) + if (e['moneyInfo']['currency'] === currency && temp >= e['count'] + && (rubles.includes(e['count']) || dollars.includes(e['count']))) { + temp -= e['count']; + e['count'] = 0; + } + }); + return temp === 0; + } + public takeMoney(moneyUnits: Array): number { + moneyUnits.sort(this.order); + let res = 0; + for (let e of moneyUnits){ + const currency = e.moneyInfo.currency.toString(); + for (let moneyUnitInRepo of this._repository[currency]) + if (e.moneyInfo.denomination === moneyUnitInRepo.moneyInfo.denomination) { + moneyUnitInRepo.count += e.count; + res += e.count; + break; + } + } + return res; } } \ No newline at end of file diff --git a/src/task_2/index.ts b/src/task_2/index.ts index fe95180..a4926ce 100644 --- a/src/task_2/index.ts +++ b/src/task_2/index.ts @@ -1,23 +1,6 @@ -/** Задача 1 - BankOffice - * Имеется класс BankOffice. Который должен хранить пользователей и банковские карты. - * Пользователи банка могу иметь карту, а могут не иметь. - * Карты могут иметь своего владельца, а могут не иметь. - * Требуется: - * 1) Реализовать классу BankOffice 3 метода: - * 1.1) authorize - позволяет авторизировать пользователя: - * Пользователь считается авторизованым, если карта принадлежит ему и пин-код введен корректно - * Принимает аргументы userId - id пользователя, cardId - id банковской карты, cardPin - пин-код карты - * Если пользователь был успешно авторизован, то метод возвращает true, иначе false - * 1.2) getCardById - позволяет получить объект банковской карты из хранилища по id карты - * 1.3) isCardTiedToUser - позволяет по id карты узнать, привзяана ли карта к какому-нибудь пользователю - * возвращает true - если карта привязана к какому-нибудь пользователю, false в ином случае - * 2) Типизировать все свойства и методы класса MoneyRepository, - * пользуясь уже предоставленными интерфейсами (избавиться от всех any типов) -*/ - import { Currency } from '../enums'; -interface ICard { +export interface ICard { id: string; balance: number; currency: Currency, @@ -32,23 +15,23 @@ export interface IBankUser { } export class BankOffice { - private _users: any; - private _cards: any; + private _users: IBankUser; + private _cards: ICard; - constructor(users: any, cards: any) { + constructor(users: IBankUser, cards: ICard) { this._users = users; this._cards = cards; } - public authorize(userId: any, cardId: any, cardPin: any): any { - + public authorize(userId: string, cardId: string, cardPin: string): boolean { + return cardId === userId && this._cards.pin === cardPin; } - public getCardById(cardId: any): any { - + public getCardById(cardId: string): ICard { + if (cardId === this._cards['id']) return this._cards; } - public isCardTiedToUser(cardId: any): any { - + public isCardTiedToUser(cardId: string): boolean { + return this._users.cards[0].toString() === cardId } } \ No newline at end of file diff --git a/src/task_3/index.ts b/src/task_3/index.ts index 9020644..76267cc 100644 --- a/src/task_3/index.ts +++ b/src/task_3/index.ts @@ -1,49 +1,35 @@ -/** Задача 3 - UserSettingsModule - * Имеется класс UserSettingsModule. Который должен отвечать за - * изменение настроек пользователя. - * Требуется: - * 1) Реализовать классу UserSettingsModule 4 метода: - * 1.1) changeUserName - метод, заменяющий имя пользователя на переданное в аргументе - * возвращает true, если операция удалась и false в ином случае - * 1.2) changeUserSurname - метод, заменяющий фамилию пользователя на переданную в аргументе - * возвращает true, если операция удалась и false в ином случае - * 1.3) registerForUserNewCard - метод, привязывающий пользователю банковскую - * Карта считается успешно привязанной, если она существует и она не привязана ни к одному пользователю - * возвращает true, если операция удалась и false в ином случае - * 1.4) changeUserSettings - управляющий метод - * который возвращает резльтат работы одного из методов из 1.1 - 1.3 - * на основе переданных аргументов - * 2) Типизировать все свойства и методы класса UserSettingsModule, - * пользуясь уже предоставленными интерфейсами (избавиться от всех any типов) -*/ - import { UserSettingOptions } from '../enums'; +import { IBankUser, BankOffice } from '../task_2'; export class UserSettingsModule { - private _bankOffice: any; - private _user: any; + private _bankOffice: BankOffice; + private _user: IBankUser; - public set user(user: any) { + public set user(user: IBankUser) { this._user = user; } - constructor(initialBankOffice: any) { + constructor(initialBankOffice: BankOffice) { this._bankOffice = initialBankOffice; } - private changeUserName(newName: any): any { - + private changeUserName(newName: string): boolean { + return newName === this._user.name; } - private changeUserSurname(newSurname: any): any { - + private changeUserSurname(newSurname: string): boolean { + return newSurname === this._user.surname; } - private registerForUserNewCard(newCardId: any): any { - + private registerForUserNewCard(newCardId: string): boolean { + if(this._bankOffice.isCardTiedToUser(newCardId) || !this._user.cards) return false; + this._user.cards[0]['id'] = newCardId; + return true; } - public changeUserSettings(option: UserSettingOptions, argsForChangeFunction: any): any { - + public changeUserSettings(option: UserSettingOptions, argsForChangeFunction: string): boolean { + return argsForChangeFunction === option[0] ? this.changeUserName(argsForChangeFunction) : + argsForChangeFunction === option[1] ? this.changeUserSurname(argsForChangeFunction) : + this.registerForUserNewCard(argsForChangeFunction); } } \ No newline at end of file diff --git a/src/task_4/index.ts b/src/task_4/index.ts index bdd7528..7456910 100644 --- a/src/task_4/index.ts +++ b/src/task_4/index.ts @@ -1,30 +1,21 @@ -/** Задача 4 - CurrencyConverterModule - * Имеется класс CurrencyConverterModule. Который должен отвечать за - * конвертацию валют. - * Требуется: - * 1) Реализовать классу CurrencyConverterModule 1 метод - convert - * метод должен принимать 3 аргумента: - * 1.1) fromCurrency - валюта, из которой происходит конвертация - * 1.2) toCurrency - валюта, в которую происходит конвертация - * 1.3) moneyUnits - денежные единицы, полностью соответствующие валюте, - * из которой происходит конвертация - * Метод должен возвращать набор денежных единиц в той валюте, в которую происходит конвертация - * Для простоты реализации будем считать, что банкомат конвертирует только по курсу - * 1USD = 70RUB и кратные курсу суммы (т.е. банкомат не может сконвертировать 100RUB, может только 70, 140 и т.д.) - * 2) Типизировать все свойства и методы класса UserSettingsModule, - * пользуясь уже предоставленными интерфейсами (избавиться от всех any типов) -*/ - import { Currency } from '../enums'; +import { IMoneyUnit, MoneyRepository } from '../task_1'; export class CurrencyConverterModule { - private _moneyRepository: any; + private _moneyRepository: MoneyRepository; - constructor(initialMoneyRepository: any) { + constructor(initialMoneyRepository: MoneyRepository) { this._moneyRepository = initialMoneyRepository; } - public convertMoneyUnits(fromCurrency: Currency, toCurrency: Currency, moneyUnits: any): any { - + public convertMoneyUnits(fromCurrency: Currency, toCurrency: Currency, moneyUnits: IMoneyUnit[]): IMoneyUnit[] { + const K = fromCurrency === Currency.RUB ? 70 : 1/70; + let res: IMoneyUnit[] = []; + for (var e of moneyUnits) { + res.push({ count: e.count, moneyInfo: { + currency: toCurrency, denomination: (K * +e.moneyInfo.denomination).toString() + }}); + } + return res; } } \ No newline at end of file diff --git a/src/task_5/index.ts b/src/task_5/index.ts index 3c99ee2..d851aff 100644 --- a/src/task_5/index.ts +++ b/src/task_5/index.ts @@ -1,23 +1,6 @@ -/** Задача 5 - BankTerminal - * Имеется класс BankTerminal. Класс представляет банковский терминал. - * Требуется: - * 1) Реализовать классу BankTerminal 5 методjd: - * 1.1) authorize - позволяет авторизировать пользователя c помощью авторизации в BankOffice - * 1.2) takeUsersMoney - позволяет авторизованному пользователю положить денежные единицы - * в хранилище и пополнить свой баланс на карте - * 1.3) giveOutUsersMoney - позволяет авторизованному пользователю снять денежные единицы - * с карты и получить их наличными из хранилища - * 1.4) changeAuthorizedUserSettings - позволяет авторизованному пользователю изменить свои - * настройки с помощью методов UserSettingsModule - * 1.5) convertMoneyUnits - позволяет авторизованному пользователю конвертировать валюту - * с помощью методов CurrencyConverterModule - * 2) Типизировать все свойства и методы класса BankTerminal, - * пользуясь уже предоставленными интерфейсами (избавиться от всех any типов) -*/ - import { Currency, UserSettingOptions } from '../enums'; -import { MoneyRepository } from '../task_1'; -import { BankOffice, IBankUser } from '../task_2'; +import { IMoneyUnit, MoneyRepository } from '../task_1'; +import { BankOffice, IBankUser, ICard } from '../task_2'; import { UserSettingsModule } from '../task_3'; import { CurrencyConverterModule } from '../task_4'; @@ -27,31 +10,49 @@ class BankTerminal { private _userSettingsModule: UserSettingsModule; private _currencyConverterModule: CurrencyConverterModule; private _authorizedUser: IBankUser; + private _usersCard: ICard; - constructor(initBankOffice: any, initMoneyRepository: any) { + constructor(initBankOffice: BankOffice, initMoneyRepository: MoneyRepository) { this._moneyRepository = initMoneyRepository; - this._bankOffice = initBankOffice; this._userSettingsModule = new UserSettingsModule(initBankOffice); this._currencyConverterModule = new CurrencyConverterModule(initMoneyRepository); + this._bankOffice = initBankOffice; } - public authorizeUser(user: any, card: any, cardPin: any): any { - + public authorizeUser(user: IBankUser, card: ICard, cardPin: string): boolean { + if (!this._bankOffice.authorize(user.id, card.id, cardPin)) return false; + this._authorizedUser = user; + this._usersCard = card; + return true; } - public takeUsersMoney(moneyUnits: any): any { - + public takeUsersMoney(moneyUnits: IMoneyUnit[]): boolean { + if (!this._authorizedUser) return false; + this._moneyRepository.takeMoney(moneyUnits); + const sum = moneyUnits.reduce((sum, unit) => { + return sum + unit.count * (+unit.moneyInfo.denomination.match(/\d/g).join(''));}, 0); + this._usersCard.balance += sum; + return true; } - public giveOutUsersMoney(count: any): any { - + public giveOutUsersMoney(count: number): boolean { + if (!this._authorizedUser || this._usersCard.balance < count) return false; + this._usersCard.balance -= count; + return true; } - public changeAuthorizedUserSettings(option: UserSettingOptions, argsForChangeFunction: any): any { - + public changeAuthorizedUserSettings(option: UserSettingOptions, argsForChangeFunction: string): boolean { + if (!this._authorizedUser) return false; + if (this._userSettingsModule.changeUserSettings(option, argsForChangeFunction)) return true; + this._userSettingsModule.user = this._authorizedUser; + return this._userSettingsModule.changeUserSettings(option, argsForChangeFunction); } - public convertMoneyUnits(fromCurrency: Currency, toCurrency: Currency, moneyUnits: any): any { - + public convertMoneyUnits(fromCurrency: Currency, toCurrency: Currency, moneyUnits: IMoneyUnit[]): boolean { + const sum = moneyUnits.reduce((sum, unit) => { + return sum + unit.count * (+unit.moneyInfo.denomination.match(/\d/g).join(''));}, 0); + if (!this.giveOutUsersMoney(sum)) return false; + return this.takeUsersMoney(this._currencyConverterModule + .convertMoneyUnits(fromCurrency, toCurrency, moneyUnits)); } } \ No newline at end of file From 86291eb1eaebc4537fa4f3b6f1920274b21c60e8 Mon Sep 17 00:00:00 2001 From: "petr.diukin" Date: Thu, 8 Apr 2021 14:48:15 +0500 Subject: [PATCH 2/3] =?UTF-8?q?=D0=94=D1=8E=D0=BA=D0=B8=D0=BD=20=D0=9F?= =?UTF-8?q?=D0=B5=D1=82=D1=80=20//=20ts-2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/task_1/index.ts | 2 +- src/task_2/index.ts | 2 +- src/task_3/index.ts | 2 +- src/task_4/index.ts | 2 +- src/task_5/index.ts | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/task_1/index.ts b/src/task_1/index.ts index e24f468..cb60472 100644 --- a/src/task_1/index.ts +++ b/src/task_1/index.ts @@ -49,4 +49,4 @@ export class MoneyRepository { } return res; } -} \ No newline at end of file +} diff --git a/src/task_2/index.ts b/src/task_2/index.ts index a4926ce..cb93e07 100644 --- a/src/task_2/index.ts +++ b/src/task_2/index.ts @@ -34,4 +34,4 @@ export class BankOffice { public isCardTiedToUser(cardId: string): boolean { return this._users.cards[0].toString() === cardId } -} \ No newline at end of file +} diff --git a/src/task_3/index.ts b/src/task_3/index.ts index 76267cc..91ded4f 100644 --- a/src/task_3/index.ts +++ b/src/task_3/index.ts @@ -32,4 +32,4 @@ export class UserSettingsModule { argsForChangeFunction === option[1] ? this.changeUserSurname(argsForChangeFunction) : this.registerForUserNewCard(argsForChangeFunction); } -} \ No newline at end of file +} diff --git a/src/task_4/index.ts b/src/task_4/index.ts index 7456910..e9dbe64 100644 --- a/src/task_4/index.ts +++ b/src/task_4/index.ts @@ -18,4 +18,4 @@ export class CurrencyConverterModule { } return res; } -} \ No newline at end of file +} diff --git a/src/task_5/index.ts b/src/task_5/index.ts index d851aff..3e2ae4d 100644 --- a/src/task_5/index.ts +++ b/src/task_5/index.ts @@ -55,4 +55,4 @@ class BankTerminal { return this.takeUsersMoney(this._currencyConverterModule .convertMoneyUnits(fromCurrency, toCurrency, moneyUnits)); } -} \ No newline at end of file +} From 7f0ab2bfe98a0fe5ef64313f215fa44fc734b979 Mon Sep 17 00:00:00 2001 From: diukin9 Date: Tue, 18 May 2021 11:02:36 +0500 Subject: [PATCH 3/3] =?UTF-8?q?=D0=94=D1=8E=D0=BA=D0=B8=D0=BD=20=D0=9F?= =?UTF-8?q?=D0=B5=D1=82=D1=80=20ts-2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/task_1/index.ts | 60 ++++++++++++++++++++------------------------- src/task_2/index.ts | 31 +++++++++++++++-------- src/task_3/index.ts | 35 ++++++++++++++++++-------- src/task_4/index.ts | 26 +++++++++++--------- src/task_5/index.ts | 60 ++++++++++++++++++++------------------------- 5 files changed, 113 insertions(+), 99 deletions(-) diff --git a/src/task_1/index.ts b/src/task_1/index.ts index cb60472..b0b8f01 100644 --- a/src/task_1/index.ts +++ b/src/task_1/index.ts @@ -1,52 +1,44 @@ import { Currency } from '../enums'; + interface IMoneyInfo { denomination: string; currency: Currency; } + export interface IMoneyUnit { moneyInfo: IMoneyInfo; count: number; } export class MoneyRepository { - private _repository: Array; - constructor(initialRepository: Array) { + private _repository: IMoneyUnit[]; + constructor(initialRepository: IMoneyUnit[]) { this._repository = initialRepository; } - private order(a: IMoneyUnit, b: IMoneyUnit): number{ - return a.moneyInfo.denomination.length > b.moneyInfo.denomination.length ? -1 : - a.moneyInfo.denomination.length < b.moneyInfo.denomination.length ? 1 : - a.moneyInfo.denomination > b.moneyInfo.denomination ? -1 : 1; - } - public giveOutMoney(count: number, currency: Currency): boolean { - let temp = count; - const dollars = [1, 2, 5, 10, 20, 50, 100]; - const rubles = [10, 50, 100, 500, 1000, 5000]; - this._repository.forEach(e => { - for (let key in e) - if (e['moneyInfo']['currency'] === currency && temp >= e['count'] - && (rubles.includes(e['count']) || dollars.includes(e['count']))) { - temp -= e['count']; - e['count'] = 0; - } - }); - return temp === 0; + this._repository = this._repository.sort((a, b) => + parseInt(a.moneyInfo.denomination) > parseInt(b.moneyInfo.denomination) ? 1 : 0); + for (let unit of this._repository) { + if (unit.moneyInfo.currency !== currency) continue; + if (count === 0) break; + let denomination: number = parseInt(unit.moneyInfo.denomination) + while (count >= denomination && unit.count !== 0) { + count -= denomination; + unit.count--; + } + } + return count === 0; } - public takeMoney(moneyUnits: Array): number { - moneyUnits.sort(this.order); - let res = 0; - for (let e of moneyUnits){ - const currency = e.moneyInfo.currency.toString(); - for (let moneyUnitInRepo of this._repository[currency]) - if (e.moneyInfo.denomination === moneyUnitInRepo.moneyInfo.denomination) { - moneyUnitInRepo.count += e.count; - res += e.count; - break; - } - } - return res; + public takeMoney(moneyUnits: IMoneyUnit[]): void { + moneyUnits.forEach(unit => { + let unitsFromRepository : IMoneyUnit[] = this._repository.filter( + x => x.moneyInfo.currency === unit.moneyInfo.currency + && x.moneyInfo.denomination === unit.moneyInfo.denomination) + if (unitsFromRepository.length !== 0) + unitsFromRepository[0].count++; + else this._repository.push(unit); + }) } -} +} \ No newline at end of file diff --git a/src/task_2/index.ts b/src/task_2/index.ts index cb93e07..ee5d1db 100644 --- a/src/task_2/index.ts +++ b/src/task_2/index.ts @@ -15,23 +15,34 @@ export interface IBankUser { } export class BankOffice { - private _users: IBankUser; - private _cards: ICard; + private _users: IBankUser[]; + private _cards: ICard[]; - constructor(users: IBankUser, cards: ICard) { + constructor(users: IBankUser[], cards: ICard[]) { this._users = users; this._cards = cards; } - public authorize(userId: string, cardId: string, cardPin: string): boolean { - return cardId === userId && this._cards.pin === cardPin; + public getCardById(cardId: string): ICard | undefined { + let temp : ICard[] = this._cards.filter(x => x.id === cardId); + return temp.length === 0 ? undefined : temp[0]; } - public getCardById(cardId: string): ICard { - if (cardId === this._cards['id']) return this._cards; + public isCardTiedToUser(cardId: string): boolean { + let flag = false; + let card : ICard | undefined = this.getCardById(cardId); + if (typeof card === "undefined") return false; + for (let user of this._users) + if (typeof card !== "undefined" && user.cards.indexOf(card) !== -1) + return true; + return flag; } - public isCardTiedToUser(cardId: string): boolean { - return this._users.cards[0].toString() === cardId + public authorize(userId: string, cardId: string, cardPin: string): boolean { + let card : ICard; + let user : IBankUser = this._users.filter(x => x.id === userId)[0]; + if (typeof user === "undefined") return false + card = user.cards.filter(x => x.id === cardId)[0]; + return typeof card !== "undefined" ? cardPin === card.pin : false; } -} +} \ No newline at end of file diff --git a/src/task_3/index.ts b/src/task_3/index.ts index 91ded4f..f9cbaeb 100644 --- a/src/task_3/index.ts +++ b/src/task_3/index.ts @@ -1,5 +1,5 @@ -import { UserSettingOptions } from '../enums'; -import { IBankUser, BankOffice } from '../task_2'; +import {UserSettingOptions} from '../enums'; +import {BankOffice, IBankUser} from "../task_2"; export class UserSettingsModule { private _bankOffice: BankOffice; @@ -13,23 +13,38 @@ export class UserSettingsModule { this._bankOffice = initialBankOffice; } + private TryToChangeUser(property : string, value : string) : boolean { + if (this._user && value.length > 0) { + this[property] = value; + return true; + } + return false; + } + private changeUserName(newName: string): boolean { - return newName === this._user.name; + return this.TryToChangeUser("name", newName); } private changeUserSurname(newSurname: string): boolean { - return newSurname === this._user.surname; + return this.TryToChangeUser("surname", newSurname); } private registerForUserNewCard(newCardId: string): boolean { - if(this._bankOffice.isCardTiedToUser(newCardId) || !this._user.cards) return false; - this._user.cards[0]['id'] = newCardId; + let card = this._bankOffice.getCardById(newCardId); + if (!this._user || !card || this._bankOffice.isCardTiedToUser(newCardId)) + return false; + this._user.cards.push(card); return true; } public changeUserSettings(option: UserSettingOptions, argsForChangeFunction: string): boolean { - return argsForChangeFunction === option[0] ? this.changeUserName(argsForChangeFunction) : - argsForChangeFunction === option[1] ? this.changeUserSurname(argsForChangeFunction) : - this.registerForUserNewCard(argsForChangeFunction); + switch (option) { + case UserSettingOptions.name: + return this.changeUserName(argsForChangeFunction); + case UserSettingOptions.newCard: + return this.registerForUserNewCard(argsForChangeFunction); + case UserSettingOptions.surname: + return this.changeUserSurname(argsForChangeFunction); + } } -} +} \ No newline at end of file diff --git a/src/task_4/index.ts b/src/task_4/index.ts index e9dbe64..834a11b 100644 --- a/src/task_4/index.ts +++ b/src/task_4/index.ts @@ -1,5 +1,5 @@ -import { Currency } from '../enums'; -import { IMoneyUnit, MoneyRepository } from '../task_1'; +import {Currency} from '../enums'; +import {IMoneyUnit, MoneyRepository} from "../task_1"; export class CurrencyConverterModule { private _moneyRepository: MoneyRepository; @@ -8,14 +8,18 @@ export class CurrencyConverterModule { this._moneyRepository = initialMoneyRepository; } - public convertMoneyUnits(fromCurrency: Currency, toCurrency: Currency, moneyUnits: IMoneyUnit[]): IMoneyUnit[] { - const K = fromCurrency === Currency.RUB ? 70 : 1/70; - let res: IMoneyUnit[] = []; - for (var e of moneyUnits) { - res.push({ count: e.count, moneyInfo: { - currency: toCurrency, denomination: (K * +e.moneyInfo.denomination).toString() - }}); + public convertMoneyUnits(fromCurrency: Currency, toCurrency: Currency, moneyUnits: IMoneyUnit): number { + if (fromCurrency === toCurrency) return 0; + let denomination = parseInt(moneyUnits.moneyInfo.denomination); + switch (fromCurrency) { + case Currency.RUB: + if (this._moneyRepository.giveOutMoney(moneyUnits.count * denomination / 70, toCurrency)) + return moneyUnits.count * denomination / 70; + break; + case Currency.USD: + if (this._moneyRepository.giveOutMoney(moneyUnits.count * denomination * 70, toCurrency)) + return moneyUnits.count * denomination * 70; } - return res; + return 0; } -} +} \ No newline at end of file diff --git a/src/task_5/index.ts b/src/task_5/index.ts index 3e2ae4d..b15e683 100644 --- a/src/task_5/index.ts +++ b/src/task_5/index.ts @@ -1,8 +1,8 @@ -import { Currency, UserSettingOptions } from '../enums'; -import { IMoneyUnit, MoneyRepository } from '../task_1'; -import { BankOffice, IBankUser, ICard } from '../task_2'; -import { UserSettingsModule } from '../task_3'; -import { CurrencyConverterModule } from '../task_4'; +import {Currency, UserSettingOptions} from '../enums'; +import {IMoneyUnit, MoneyRepository} from '../task_1'; +import {BankOffice, IBankUser, ICard} from '../task_2'; +import {UserSettingsModule} from '../task_3'; +import {CurrencyConverterModule} from '../task_4'; class BankTerminal { private _bankOffice: BankOffice; @@ -10,49 +10,41 @@ class BankTerminal { private _userSettingsModule: UserSettingsModule; private _currencyConverterModule: CurrencyConverterModule; private _authorizedUser: IBankUser; - private _usersCard: ICard; - constructor(initBankOffice: BankOffice, initMoneyRepository: MoneyRepository) { + constructor(initBankOffice: any, initMoneyRepository: any) { this._moneyRepository = initMoneyRepository; + this._bankOffice = initBankOffice; this._userSettingsModule = new UserSettingsModule(initBankOffice); this._currencyConverterModule = new CurrencyConverterModule(initMoneyRepository); - this._bankOffice = initBankOffice; } public authorizeUser(user: IBankUser, card: ICard, cardPin: string): boolean { - if (!this._bankOffice.authorize(user.id, card.id, cardPin)) return false; - this._authorizedUser = user; - this._usersCard = card; - return true; + if (this._bankOffice.authorize(user.id, card.id, cardPin)) { + this._authorizedUser = user; + return true; + } + return false; } - public takeUsersMoney(moneyUnits: IMoneyUnit[]): boolean { - if (!this._authorizedUser) return false; - this._moneyRepository.takeMoney(moneyUnits); - const sum = moneyUnits.reduce((sum, unit) => { - return sum + unit.count * (+unit.moneyInfo.denomination.match(/\d/g).join(''));}, 0); - this._usersCard.balance += sum; - return true; + public takeUsersMoney(moneyUnits: IMoneyUnit[]): void { + if (this._authorizedUser) this._moneyRepository.takeMoney(moneyUnits); } - public giveOutUsersMoney(count: number): boolean { - if (!this._authorizedUser || this._usersCard.balance < count) return false; - this._usersCard.balance -= count; - return true; + public giveOutUsersMoney(count: number, currency : Currency): boolean { + if (this._authorizedUser) + return this._moneyRepository.giveOutMoney(count, currency); + return false; } public changeAuthorizedUserSettings(option: UserSettingOptions, argsForChangeFunction: string): boolean { - if (!this._authorizedUser) return false; - if (this._userSettingsModule.changeUserSettings(option, argsForChangeFunction)) return true; - this._userSettingsModule.user = this._authorizedUser; - return this._userSettingsModule.changeUserSettings(option, argsForChangeFunction); + if (this._authorizedUser) + return this._userSettingsModule.changeUserSettings(option, argsForChangeFunction) + return false; } - public convertMoneyUnits(fromCurrency: Currency, toCurrency: Currency, moneyUnits: IMoneyUnit[]): boolean { - const sum = moneyUnits.reduce((sum, unit) => { - return sum + unit.count * (+unit.moneyInfo.denomination.match(/\d/g).join(''));}, 0); - if (!this.giveOutUsersMoney(sum)) return false; - return this.takeUsersMoney(this._currencyConverterModule - .convertMoneyUnits(fromCurrency, toCurrency, moneyUnits)); + public convertMoneyUnits(fromCurrency: Currency, toCurrency: Currency, moneyUnits: IMoneyUnit) : boolean { + if (this._authorizedUser) + return Boolean(this._currencyConverterModule.convertMoneyUnits(fromCurrency, toCurrency, moneyUnits)); + return false; } -} +} \ No newline at end of file