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
23 changes: 21 additions & 2 deletions src/task_1/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -21,8 +39,9 @@ class Calculator {
this.b = b;
}
}

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

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

}
}
15 changes: 14 additions & 1 deletion src/task_2/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "";
}

Choose a reason for hiding this comment

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

3 бала


Expand Down
61 changes: 47 additions & 14 deletions src/task_3/index.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,61 @@
/** Задача 3
* Ниже представлен код в котором, пропущены участки кода.
* Требуется дописать участки кода так, чтобы программа компилировалась.
* Использование типа any допустимо только в Control<any>.
* Переопределенные методы getValue и setValue в классах TextBox и SelectBox должны
* принимать и возвращать только свой результирующий тип (string и SelectItem)
* Методы register и getInstance класса FactoryControl. Должны принимать и возвращать только те типы,
* которые унаследованы от класса Control<T>.
*/

/**Базовый класс для контролов */
abstract class Control<T> {
public name: string = "";

protected value: T;

constructor(value: T, name: string) {
this.name = name;
this.value = value;
}
/**взять значение из контрола */
public abstract getValue(): T;
/**установить значение в контрол */
public abstract setValue(val: T): void;
}
/**Класс описывает TextBox контрол */
class TextBox extends Control<string> {
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<SelectItem> {
private item: SelectItem;
public getValue(): SelectItem {
return this.item;
}
public setValue(val: SelectItem): void {
this.item = val;
}
}

class Container {
public instance: Control<any>;
public type: string;

constructor(instance: Control<any>, type: string) {
this.instance = instance;
this.type = type;
}
}

/**Фабрика которая отвечает за создание экземпляров контролов */
Expand All @@ -45,13 +67,24 @@ class FactoryControl {
this._collection = [];
}

public register<?>(type: ?) {
public register(type: Function) {

Choose a reason for hiding this comment

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

почему убрал использование generic-типа?
теперь в этот метод можно передать любой класс, который будет не унаследован от Control

const typeStr = type.name;
if (!this.existType(typeStr)) {
this._collection.push(new Container(type(), typeStr))
}
}

public getInstance<?>(type: ?): ? {
public getInstance(type: Function): Control<any> {
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;
}
}
Expand All @@ -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 пропускает
6 changes: 4 additions & 2 deletions src/task_4/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}

const x = undefined;
const x = {
m: "",
};

Choose a reason for hiding this comment

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

3 бала


console.log(getProperty(x, "m"));
console.log(getProperty(x, "m"));
77 changes: 52 additions & 25 deletions src/task_5/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {

Choose a reason for hiding this comment

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

Сюда приходит не тип а объект, для проверки типа недо было использовать generic тип устанавливаемый в момент инициализации объекта.

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;
}

Choose a reason for hiding this comment

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

прикладываю правильное решение
function validate<T, P extends keyof T>(type: new () => T, prop: P): (target: Object, propertyKey: string | symbol) => any {
let temp: T;
return (target: Object, propertyKey: string | symbol): PropertyDescriptor => {
let descriptor: PropertyDescriptor = {
get: function () {
return temp;
},
set: function (val: T) {
if (!(val instanceof type)) {
throw new Error("Устанавливается значение которое не соотвтетсвует типу");
}
if (temp[prop]) {
throw new Error("У требуемого поля не верный примитивный тип");
}
console.log("value valid");
temp = val;
}
};

    return descriptor;
};

}

class ValueExample1 {
public value: string;
public id: number;
}

class ValueExample2 {
public prop3: undefined;
public prop2: boolean;
}

class Example {
@Validate(ValueExample1, "id1")
public propValueExample1: any;

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

}

let ex1 = new Example();

let objValExample = new ValueExample1();
objValExample.id = 1;
objValExample.value = "qwe";
ex1.propValueExample1 = objValExample;

ex1.propValueExample2 = false;