-
Notifications
You must be signed in to change notification settings - Fork 14
Дюкин Петр // ts-2 #7
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
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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,34 @@ 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 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: any): any { | ||
|
|
||
| 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: any): any { | ||
|
|
||
| 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; | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 1 балов |
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,49 +1,50 @@ | ||
| /** Задача 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 {UserSettingOptions} from '../enums'; | ||
| import {BankOffice, IBankUser} 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 TryToChangeUser(property : string, value : string) : boolean { | ||
| if (this._user && value.length > 0) { | ||
| this[property] = value; | ||
| return true; | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| private changeUserSurname(newSurname: any): any { | ||
|
|
||
| private changeUserName(newName: string): boolean { | ||
| return this.TryToChangeUser("name", newName); | ||
| } | ||
|
|
||
| private registerForUserNewCard(newCardId: any): any { | ||
|
|
||
| private changeUserSurname(newSurname: string): boolean { | ||
| return this.TryToChangeUser("surname", newSurname); | ||
| } | ||
|
|
||
| public changeUserSettings(option: UserSettingOptions, argsForChangeFunction: any): any { | ||
| private registerForUserNewCard(newCardId: string): boolean { | ||
| 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 { | ||
| switch (option) { | ||
| case UserSettingOptions.name: | ||
| return this.changeUserName(argsForChangeFunction); | ||
| case UserSettingOptions.newCard: | ||
| return this.registerForUserNewCard(argsForChangeFunction); | ||
| case UserSettingOptions.surname: | ||
| return this.changeUserSurname(argsForChangeFunction); | ||
| } | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 1 балл |
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,30 +1,25 @@ | ||
| /** Задача 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 {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): 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 0; | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 1 балл |
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,25 +1,8 @@ | ||
| /** Задача 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 { 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; | ||
|
|
@@ -35,23 +18,33 @@ class BankTerminal { | |
| this._currencyConverterModule = new CurrencyConverterModule(initMoneyRepository); | ||
| } | ||
|
|
||
| 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)) { | ||
| this._authorizedUser = user; | ||
| return true; | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| public takeUsersMoney(moneyUnits: any): any { | ||
|
|
||
| public takeUsersMoney(moneyUnits: IMoneyUnit[]): void { | ||
| if (this._authorizedUser) this._moneyRepository.takeMoney(moneyUnits); | ||
| } | ||
|
|
||
| public giveOutUsersMoney(count: any): any { | ||
|
|
||
| public giveOutUsersMoney(count: number, currency : Currency): boolean { | ||
| if (this._authorizedUser) | ||
| return this._moneyRepository.giveOutMoney(count, currency); | ||
| return false; | ||
| } | ||
|
|
||
| public changeAuthorizedUserSettings(option: UserSettingOptions, argsForChangeFunction: any): any { | ||
|
|
||
| public changeAuthorizedUserSettings(option: UserSettingOptions, argsForChangeFunction: string): boolean { | ||
| if (this._authorizedUser) | ||
| return this._userSettingsModule.changeUserSettings(option, argsForChangeFunction) | ||
| return false; | ||
| } | ||
|
|
||
| public convertMoneyUnits(fromCurrency: Currency, toCurrency: Currency, moneyUnits: any): any { | ||
|
|
||
| public convertMoneyUnits(fromCurrency: Currency, toCurrency: Currency, moneyUnits: IMoneyUnit) : boolean { | ||
| if (this._authorizedUser) | ||
| return Boolean(this._currencyConverterModule.convertMoneyUnits(fromCurrency, toCurrency, moneyUnits)); | ||
| return false; | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 1 балл |
||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
зачтено 1 балл