Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
25 changes: 25 additions & 0 deletions src/task_1/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,25 @@
* result of the addition operation ${a} + ${b} = ${рассчитанное значение}
*/

function DecorateRu(target: Object, method: string, descriptor: PropertyDescriptor) {
let exec = descriptor.value;
descriptor.value = function(...args: any) {
let returnValue = exec.apply(this, args);
console.log(`результат сложения ${this.a} + ${this.b} = ${returnValue}`)
return returnValue;
}
}

function DecorateEn(target: Object, method: string, descriptor: PropertyDescriptor) {
let exec = descriptor.value;
descriptor.value = function(...args: any) {
let returnValue = exec.apply(this, args);
console.log(`result of the addition operation ${this.a} + ${this.b} = ${returnValue}`)
return returnValue;
}

}

class Calculator {
protected a: number = 0;
protected b: number = 0;
Expand All @@ -22,7 +41,13 @@ class Calculator {
}
}

@DecorateEn
@DecorateRu
public exec(): string {
return (this.a + this.b).toString();
}
}

const test = new Calculator(10, 20);
test.exec();

Choose a reason for hiding this comment

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

Это не паттерн декоратор.
https://refactoring.guru/ru/design-patterns/decorator/typescript/example


36 changes: 32 additions & 4 deletions src/task_2/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,38 @@
* Когда присваивается некорректный e-mail возбуждается ошибка.
*/

class Example {
public email: string = "";
function validator(target: Object, propertyKey: string | symbol) {
let _val = this[propertyKey];

let descriptor: PropertyDescriptor = {
get() {
return _val;
},
set(newValue: string) {
_val = newValue;
if (!new RegExp(/^([a-z0-9_\.-])+@[a-z0-9-]+\.([a-z]{2,4}\.)?[a-z]{2,4}$/i).test(newValue)) {
console.log('invalid email');
} else {
console.log('valid email');
}
return _val;
}
}

Object.defineProperty(target, propertyKey, {

Choose a reason for hiding this comment

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

Это не обязательно делать.

get: descriptor.get,
set: descriptor.set
});

}

class Example1 {

@validator
public email: string;

}

let exampleInstance = new Example();
let exampleInstance = new Example1();
exampleInstance.email = "fkkldfjg"; // генерирует эксепшен
exampleInstance.email = "misha@mail.ru"; // выводит в консоль e-mail valid
exampleInstance.email = "misha@mail.ru"; // выводит в консоль e-mail valid

Choose a reason for hiding this comment

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

3 бала

33 changes: 31 additions & 2 deletions src/task_3/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ abstract class Control<T> {
}
/**Класс описывает TextBox контрол */
class TextBox extends Control<string> {
protected value: string;

Choose a reason for hiding this comment

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

Зачем переопределил? это поле имеет шаблонный тип в базовом классе.


public getValue(): string {
return this.value;
}

public setValue(val: string): void {
this.value = val;
}
}
/**value контрола selectBox */
class SelectItem {
Expand All @@ -29,6 +38,15 @@ class SelectItem {

/**Класс описывает SelectBox контрол */
class SelectBox extends Control<SelectItem> {
protected value: SelectItem;

Choose a reason for hiding this comment

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

Зачем переопределил? это поле имеет шаблонный тип в базовом классе.


public getValue(): SelectItem {
return this.value;
}

public setValue(val: SelectItem): void {
this.value = val;
}
}

class Container {
Expand All @@ -45,10 +63,21 @@ class FactoryControl {
this._collection = [];
}

public register<?>(type: ?) {
public register<T extends Control<any>>(type: new () => T): void {
const instanceType: string = type.name;
if (this.existType(instanceType)) {
console.log('error');
}

let instance = new type();

this._collection.push({ type: instanceType, instance: instance});
}

public getInstance<?>(type: ?): ? {
public getInstance<R>(type: new () => Control<R>): Control<R> {
const typeInst: Control<R> = new type();
const instance = this._collection.filter(element => element.type === typeInst.name);

Choose a reason for hiding this comment

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

Можно использовать find

return instance[0].instance;
}

Choose a reason for hiding this comment

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

Метод можно было сделать проще вот так
public getInstance<T extends Control>(type: new () => T): T {
const instance = this._collection.find(element => element.type === type.name);
return instance.instance as T;
}


Choose a reason for hiding this comment

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

работает всё верно, 3 бала

private existType(type: string) {
Expand Down
2 changes: 1 addition & 1 deletion src/task_4/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}

const x = undefined;
const x = {m: 'some value'};

console.log(getProperty(x, "m"));

Choose a reason for hiding this comment

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

3 бала

39 changes: 39 additions & 0 deletions src/task_5/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,36 @@
* Если поле не заполнено, то генерируется эксепшен.
*/

function validate<T>(type: T, value: string) {
return function validate(target: Object, propertyName: string) {
let propertyValue: T;

let descriptor: PropertyDescriptor = {
get() {
return propertyValue;
},
set(newVal: T) {
if (newVal === type) {

Choose a reason for hiding this comment

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

тут надо проверять тип передаваемого объекта вот так
newVal.constructor.name

console.log('valid type');
propertyValue = newVal;
} else {
throw 'exception';
}
if (!propertyName[value]) {
throw 'field is empty';
}
return propertyValue;
}
}

Object.defineProperty(target, propertyName, {

Choose a reason for hiding this comment

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

Это не обязательно

get: descriptor.get,
set: descriptor.set
});

}
}

class ValueExample1 {
public value: string;
public id: number;
Expand All @@ -31,4 +61,13 @@ class Example {

@validate(ValueExample2, "booleanProp")
public propValueExample2: any;

constructor (propValueExample1: any, propValueExample2: any) {
this.propValueExample1 = propValueExample1;
this.propValueExample2 = propValueExample2;
}
}

const example = new Example(ValueExample1, ValueExample2);

Choose a reason for hiding this comment

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

Не правильно.
Цель данной задачи состояла в том , что бы понять как работает декоратор свойств и полей класса. В данном случае ты в свойство пытаешься установить тип, зачем?

В поле надо устанавливать объект, т.е. проверять это надо было вот так:

const example = new Example();
example.propValueExample1 = new ValueExample1("21", 21);
example.propValueExample2 = new ValueExample2();

const e1 = new ValueExample1("21", 21);
const e2 = new ValueExample2();
6 changes: 6 additions & 0 deletions src/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"compilerOptions": {
"target": "ES6",
"experimentalDecorators": true
}
}