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
22 changes: 20 additions & 2 deletions src/task_1/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,23 @@
* результат в виде строки на английском языке:
* result of the addition operation ${a} + ${b} = ${рассчитанное значение}
*/
function DecorateRu(target: Object, method: string, descriptor: PropertyDescriptor){
let original = descriptor.value;
descriptor.value = function(...args: any){
let result = original.apply(this, args);
console.log(`результат сложения ${args[0]} + ${args[1]} = ${result}`)
return descriptor;
}
}

function DecorateEn(target: Object, method: string, descriptor: PropertyDescriptor){
let original = descriptor.value;
descriptor.value = function(...args: any){
let result = original.apply(this, args);
console.log(`result of the addition operation ${args[0]} + ${args[1]} = ${result}`)
return descriptor;
}
}

class Calculator {
protected a: number = 0;
Expand All @@ -21,8 +38,9 @@ class Calculator {
this.b = b;
}
}

@DecorateEn
@DecorateRu
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

}
22 changes: 21 additions & 1 deletion src/task_2/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,31 @@
* Когда присваивается корректный e-mail в консоль выводится сообщение email valid.
* Когда присваивается некорректный e-mail возбуждается ошибка.
*/
function emailCheck(target: Object, propertyKey: string): any {
let email = "";
let descriptor: PropertyDescriptor = {
get: function(){
return email;
},
set: function(newEmail: string) {
let reg = /\w*@[a-z]+\.[a-z]{2,}/;
if (reg.test(newEmail)){
email = newEmail;
console.log("email valid")
}
else{
throw new Error();
}
}
};
return descriptor;
}

class Example {
@emailCheck
public email: string = "";
}

let exampleInstance = new Example();
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 бала

9 changes: 7 additions & 2 deletions src/task_4/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}

const x = undefined;

class C {
public m: string;
constructor(){
this.m = "hello";
}
}

Choose a reason for hiding this comment

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

3 бала

let x = new C();
console.log(getProperty(x, "m"));
22 changes: 18 additions & 4 deletions src/task_5/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,24 @@
* 2) Проверять у передаваемого объекта наличие заполненного поля.
* Если поле не заполнено, то генерируется эксепшен.
*/
function validate<T>(type: T, prop: string){
return function(target: Object, propertyKey: string | symbol) : any{
let descriptor: PropertyDescriptor = {
set: function(val: any){
if (typeof val === typeof type)

Choose a reason for hiding this comment

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

val = объект
type = функция
значит это выражение будет всегда false

this.value = val;
else
throw new Error();

if (!(prop in val))
throw new Error();
}
}

Choose a reason for hiding this comment

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

Нужно ещё сделать return descriptor , иначе он не будет работать. Метод set не будет вызываться

}
}
class ValueExample1 {
public value: string;
public id: number;
public value: string | undefined;
public id: number | undefined;
public constructor(value?: string, id?: number) {
this.value = value;
this.id = id;
Expand All @@ -18,14 +32,14 @@ class ValueExample1 {

class ValueExample2 {
public undefinedProp: undefined;
public booleanProp: boolean;
public booleanProp: boolean | undefined;
public constructor(undefinedProp?: undefined, booleanProp?: boolean) {
this.undefinedProp = undefinedProp;
this.booleanProp = booleanProp;
}
}

class Example {
class Example1 {
@validate(ValueExample1, "id")
public propValueExample1: 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;

Expand Down