From f46bcdfcb29d2862a136f0702196bef5febfbb99 Mon Sep 17 00:00:00 2001 From: JIiCeHoK Date: Sat, 17 Apr 2021 14:21:10 +0500 Subject: [PATCH] =?UTF-8?q?=D0=9C=D0=BE=D0=B8=D1=81=D0=B5=D0=B5=D0=B2=20?= =?UTF-8?q?=D0=9C=D0=B8=D1=85=D0=B0=D0=B8=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/task_1/index.ts | 23 ++++++++++++-- src/task_2/index.ts | 15 ++++++++- src/task_3/index.ts | 61 ++++++++++++++++++++++++++--------- src/task_4/index.ts | 6 ++-- src/task_5/index.ts | 77 ++++++++++++++++++++++++++++++--------------- 5 files changed, 138 insertions(+), 44 deletions(-) diff --git a/src/task_1/index.ts b/src/task_1/index.ts index 53a04d7..32246de 100644 --- a/src/task_1/index.ts +++ b/src/task_1/index.ts @@ -9,6 +9,24 @@ * result of the addition operation ${a} + ${b} = ${рассчитанное значение} */ +function DecorateRu(target: Object, method: string, descriptor: PropertyDescriptor) { + let originalMethod = descriptor.value; + descriptor.value = function () { + let returnValue = originalMethod.apply(this); + console.log(`результат сложения ${this.a} + ${this.b} = ${returnValue}`) + return returnValue; + } +} + +function DecorateEn(target: Object, method: string, descriptor: PropertyDescriptor) { + let originalMethod = descriptor.value; + descriptor.value = function () { + let returnValue = originalMethod.apply(this); + console.log(`result of the addition operation ${this.a} + ${this.b} = ${returnValue}`) + return returnValue; + } +} + class Calculator { protected a: number = 0; protected b: number = 0; @@ -21,8 +39,9 @@ class Calculator { this.b = b; } } - + @DecorateRu + @DecorateEn public exec(): string { return (this.a + this.b).toString(); } -} +} \ No newline at end of file diff --git a/src/task_2/index.ts b/src/task_2/index.ts index 06535aa..fb67995 100644 --- a/src/task_2/index.ts +++ b/src/task_2/index.ts @@ -4,8 +4,21 @@ * Когда присваивается корректный e-mail в консоль выводится сообщение email valid. * Когда присваивается некорректный e-mail возбуждается ошибка. */ - +function decorEmail(target: object, propertyKey: string): any { + let regExp = /[a-z]+@[a-z]+\.[a-z]+/gi; + let property: PropertyDescriptor = { + set: (value: string) => { + if (regExp.test(value)) { + console.log("e-mail valid"); + } else { + console.log("Error"); + } + } + }; + return property; +} class Example { + @decorEmail public email: string = ""; } diff --git a/src/task_3/index.ts b/src/task_3/index.ts index afa588c..29daab4 100644 --- a/src/task_3/index.ts +++ b/src/task_3/index.ts @@ -1,18 +1,13 @@ -/** Задача 3 - * Ниже представлен код в котором, пропущены участки кода. - * Требуется дописать участки кода так, чтобы программа компилировалась. - * Использование типа any допустимо только в Control. - * Переопределенные методы getValue и setValue в классах TextBox и SelectBox должны - * принимать и возвращать только свой результирующий тип (string и SelectItem) - * Методы register и getInstance класса FactoryControl. Должны принимать и возвращать только те типы, - * которые унаследованы от класса Control. -*/ - /**Базовый класс для контролов */ abstract class Control { public name: string = ""; protected value: T; + + constructor(value: T, name: string) { + this.name = name; + this.value = value; + } /**взять значение из контрола */ public abstract getValue(): T; /**установить значение в контрол */ @@ -20,20 +15,47 @@ abstract class Control { } /**Класс описывает TextBox контрол */ class TextBox extends Control { + constructor(value: string = '', name: string) { + super(value, name); + } + + public getValue(): string { + return this.name; + } + public setValue(val: string): void { + this.name = val; + } } /**value контрола selectBox */ class SelectItem { public value: string; public id: number; + + constructor(value: string = "", id: number = 0) { + this.value = value; + this.id = id; + } } /**Класс описывает SelectBox контрол */ class SelectBox extends Control { + private item: SelectItem; + public getValue(): SelectItem { + return this.item; + } + public setValue(val: SelectItem): void { + this.item = val; + } } class Container { public instance: Control; public type: string; + + constructor(instance: Control, type: string) { + this.instance = instance; + this.type = type; + } } /**Фабрика которая отвечает за создание экземпляров контролов */ @@ -45,13 +67,24 @@ class FactoryControl { this._collection = []; } - public register(type: ?) { + public register(type: Function) { + const typeStr = type.name; + if (!this.existType(typeStr)) { + this._collection.push(new Container(type(), typeStr)) + } } - public getInstance(type: ?): ? { + public getInstance(type: Function): Control { + const typeStr = type.name; + const container = this._collection.find(x => x.type === typeStr); + if (container) { + return container.instance; + } + this.register(type); + return this._collection[this._collection.length - 1].instance; } - private existType(type: string) { + private existType(type: string): boolean { return this._collection.filter(g => g.type === type).length > 0; } } @@ -61,5 +94,5 @@ factory.register(SelectBox); const selectBoxInstance = factory.getInstance(SelectBox); -selectBoxInstance.setValue("sdfsdf") // компилятор TS не пропускает +//selectBoxInstance.setValue("sdfsdf") // компилятор TS не пропускает selectBoxInstance.setValue(new SelectItem()) // компилятор TS пропускает diff --git a/src/task_4/index.ts b/src/task_4/index.ts index dc0e179..19c8b16 100644 --- a/src/task_4/index.ts +++ b/src/task_4/index.ts @@ -6,6 +6,8 @@ function getProperty(obj: T, key: K): T[K] { return obj[key]; } -const x = undefined; +const x = { + m: "", +}; -console.log(getProperty(x, "m")); \ No newline at end of file +console.log(getProperty(x, "m")); \ No newline at end of file diff --git a/src/task_5/index.ts b/src/task_5/index.ts index d9fea4b..dff7141 100644 --- a/src/task_5/index.ts +++ b/src/task_5/index.ts @@ -7,28 +7,55 @@ * Если поле не заполнено, то генерируется эксепшен. */ -class ValueExample1 { - public value: string; - public id: number; - public constructor(value?: string, id?: number) { - this.value = value; - this.id = id; - } -} - -class ValueExample2 { - public undefinedProp: undefined; - public booleanProp: boolean; - public constructor(undefinedProp?: undefined, booleanProp?: boolean) { - this.undefinedProp = undefinedProp; - this.booleanProp = booleanProp; - } -} - -class Example { - @validate(ValueExample1, "id") - public propValueExample1: any; - - @validate(ValueExample2, "booleanProp") - public propValueExample2: any; -} +function validate(type: object, propertyKey: string) { + return function validate(target: Object, propertyName: string){ + let descriptor: PropertyDescriptor = { + get() { + return type; + }, + set(newType) { + if (newType === type) { + console.log('valid type'); + type = newType; + } else { + throw 'exception'; + } + if (!propertyName[propertyKey]) { + throw 'field is empty'; + } + return type; + } + } + + Object.defineProperty(target, propertyName, { + get: descriptor.get, + set: descriptor.set + }); + } + } + + class ValueExample1 { + public value: string; + public id: number; + public constructor(value?: string, id?: number) { + this.value = value; + this.id = id; + } + } + + class ValueExample2 { + public undefinedProp: undefined; + public booleanProp: boolean; + public constructor(undefinedProp?: undefined, booleanProp?: boolean) { + this.undefinedProp = undefinedProp; + this.booleanProp = booleanProp; + } + } + + class Example { + @validate(ValueExample1, "id") + public propValueExample1: any; + + @validate(ValueExample2, "booleanProp") + public propValueExample2: any; + }