Skip to content

Commit c06008e

Browse files
author
Anton Rokunec
committed
homework_1: homework done
1 parent d18e6b8 commit c06008e

File tree

6 files changed

+267
-169
lines changed

6 files changed

+267
-169
lines changed

src/homeworks/ts1/1_base.js

Lines changed: 0 additions & 65 deletions
This file was deleted.

src/homeworks/ts1/1_base.test.js

Lines changed: 20 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,21 @@
1-
// Этот блок кода удалить и раскомментировать код ниже
2-
it('remove it', () => {
3-
expect(true).toBe(true);
4-
});
1+
import { transformCustomers } from './1_base';
2+
3+
describe('all', () => {
4+
it('transformCustomers', () => {
5+
const customers = [
6+
{ id: 1, name: 'John', age: 25, isSubscribed: true },
7+
{ id: 2, name: 'Mary', age: 40, isSubscribed: false },
8+
{ id: 3, name: 'Bob', age: 32, isSubscribed: true },
9+
{ id: 4, name: 'Alice', age: 22, isSubscribed: true },
10+
{ id: 5, name: 'David', age: 48, isSubscribed: false },
11+
];
512

6-
// import { transformCustomers } from './1_base';
7-
//
8-
// describe('all', () => {
9-
// it('transformCustomers', () => {
10-
// const customers = [
11-
// { id: 1, name: 'John', age: 25, isSubscribed: true },
12-
// { id: 2, name: 'Mary', age: 40, isSubscribed: false },
13-
// { id: 3, name: 'Bob', age: 32, isSubscribed: true },
14-
// { id: 4, name: 'Alice', age: 22, isSubscribed: true },
15-
// { id: 5, name: 'David', age: 48, isSubscribed: false },
16-
// ];
17-
//
18-
// expect(transformCustomers(customers)).toEqual({
19-
// 1: { name: 'John', age: 25, isSubscribed: true },
20-
// 2: { name: 'Mary', age: 40, isSubscribed: false },
21-
// 3: { name: 'Bob', age: 32, isSubscribed: true },
22-
// 4: { name: 'Alice', age: 22, isSubscribed: true },
23-
// 5: { name: 'David', age: 48, isSubscribed: false },
24-
// });
25-
// });
26-
// });
13+
expect(transformCustomers(customers)).toEqual({
14+
1: { name: 'John', age: 25, isSubscribed: true },
15+
2: { name: 'Mary', age: 40, isSubscribed: false },
16+
3: { name: 'Bob', age: 32, isSubscribed: true },
17+
4: { name: 'Alice', age: 22, isSubscribed: true },
18+
5: { name: 'David', age: 48, isSubscribed: false },
19+
});
20+
});
21+
});

src/homeworks/ts1/1_base.ts

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/**
2+
* Нужно превратить файл в ts и указать типы аргументов и типы возвращаемого значения
3+
* */
4+
export const removePlus = (string: string): string => string.replace(/^\+/, '');
5+
6+
export const addPlus = (string: string): string => `+${string}`;
7+
8+
export const removeFirstZeros = (value: string): string => value.replace(/^(-)?[0]+(-?\d+.*)$/, '$1$2');
9+
10+
export const getBeautifulNumber = (value: string, separator = ' '): string =>
11+
value?.toString().replace(/\B(?=(\d{3})+(?!\d))/g, separator);
12+
13+
export const round = (value: number, accuracy = 2): number => {
14+
const d = 10 ** accuracy;
15+
return Math.round(value * d) / d;
16+
};
17+
18+
const transformRegexp =
19+
/(matrix\(-?\d+(\.\d+)?, -?\d+(\.\d+)?, -?\d+(\.\d+)?, -?\d+(\.\d+)?, )(-?\d+(\.\d+)?), (-?\d+(\.\d+)?)\)/;
20+
21+
type TransformType = {
22+
x: number;
23+
y: number;
24+
};
25+
26+
export const getTransformFromCss = (transformCssString: string): TransformType => {
27+
const data = transformCssString.match(transformRegexp);
28+
if (!data) return { x: 0, y: 0 };
29+
return {
30+
x: parseInt(data[6], 10),
31+
y: parseInt(data[8], 10),
32+
};
33+
};
34+
//кортеж
35+
type Tuple = [number, number, number];
36+
37+
export const getColorContrastValue = ([red, green, blue]: Tuple) =>
38+
// http://www.w3.org/TR/AERT#color-contrast
39+
Math.round((red * 299 + green * 587 + blue * 114) / 1000);
40+
41+
export const getContrastType = (contrastValue: number): string => (contrastValue > 125 ? 'black' : 'white');
42+
43+
//Type RegExp trivially inferred from a RegExp literal, remove type annotation.
44+
// Тип RegExp не требует явной анотации
45+
export const shortColorRegExp = /^#[0-9a-f]{3}$/i;
46+
export const longColorRegExp = /^#[0-9a-f]{6}$/i;
47+
48+
export const checkColor = (color: string): void | never => {
49+
if (!longColorRegExp.test(color) && !shortColorRegExp.test(color)) throw new Error(`invalid hex color: ${color}`);
50+
};
51+
52+
export const hex2rgb = (color: string): Tuple => {
53+
checkColor(color);
54+
if (shortColorRegExp.test(color)) {
55+
const red = parseInt(color.substring(1, 2), 16);
56+
const green = parseInt(color.substring(2, 3), 16);
57+
const blue = parseInt(color.substring(3, 4), 16);
58+
return [red, green, blue];
59+
}
60+
const red = parseInt(color.substring(1, 3), 16);
61+
const green = parseInt(color.substring(3, 5), 16);
62+
const blue = parseInt(color.substring(5, 8), 16);
63+
return [red, green, blue];
64+
};
65+
66+
export const getNumberedArray = <T>(arr: Array<T>): { value: T; number: number }[] =>
67+
arr.map((value, number) => ({ value, number }));
68+
69+
export const toStringArray = (arr: { value: string | number; number: string | number }[]): string[] =>
70+
arr.map(({ value, number }) => `${value}_${number}`);
71+
72+
type TCustomer = {
73+
id: number;
74+
name: string;
75+
age: number;
76+
isSubscribed: boolean;
77+
};
78+
79+
type TCustomerMap = {
80+
[key: TCustomer['id']]: Omit<TCustomer, 'id'>;
81+
};
82+
83+
export const transformCustomers = (customers: Array<TCustomer>): TCustomerMap => {
84+
return customers.reduce<TCustomerMap>((acc, customer) => {
85+
acc[customer.id] = { name: customer.name, age: customer.age, isSubscribed: customer.isSubscribed };
86+
return acc;
87+
}, {});
88+
};

src/homeworks/ts1/2_repair.ts

Lines changed: 52 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -2,46 +2,55 @@
22
* Здесь код с ошибками типов. Нужно их устранить
33
* */
44

5-
// // Мы это не проходили, но по тексту ошибки можно понять, как это починить
6-
// export const getFakeApi = async (): void => {
7-
// const result = await fetch('https://jsonplaceholder.typicode.com/todos/1').then((response) => response.json());
8-
// console.log(result);
9-
// };
10-
//
11-
// // Мы это не проходили, но по тексту ошибки можно понять, как это починить
12-
// export class SomeClass {
13-
// constructor() {
14-
// this.set = new Set([1]);
15-
// this.channel = new BroadcastChannel('test-broadcast-channel');
16-
// }
17-
// }
18-
//
19-
// export type Data = {
20-
// type: 'Money' | 'Percent';
21-
// value: DataValue;
22-
// };
23-
//
24-
// export type DataValue = Money | Percent;
25-
//
26-
// export type Money = {
27-
// currency: string;
28-
// amount: number;
29-
// };
30-
//
31-
// export type Percent = {
32-
// percent: number;
33-
// };
34-
//
35-
// // Здесь, возможно, нужно использовать as, возможно в switch передавать немного по-другому
36-
// const getDataAmount = (data: Data): number => {
37-
// switch (data.type) {
38-
// case 'Money':
39-
// return data.value.amount;
40-
//
41-
// default: {
42-
// // eslint-disable-next-line @typescript-eslint/no-unused-vars
43-
// const unhandled: never = data; // здесь, возможно, нужно использовать нечто другое. :never должен остаться
44-
// throw new Error(`unknown type: ${data.type}`);
45-
// }
46-
// }
47-
// };
5+
// Мы это не проходили, но по тексту ошибки можно понять, как это починить
6+
export const getFakeApi = async (): Promise<void> => {
7+
const result = await fetch('https://jsonplaceholder.typicode.com/todos/1').then((response) => response.json());
8+
console.log(result);
9+
};
10+
11+
// Мы это не проходили, но по тексту ошибки можно понять, как это починить
12+
export class SomeClass {
13+
private set: Set<number>;
14+
private channel: BroadcastChannel;
15+
constructor() {
16+
this.set = new Set([1]);
17+
this.channel = new BroadcastChannel('test-broadcast-channel');
18+
}
19+
}
20+
21+
export type Data = DataMoney | DataPercent;
22+
23+
type DataMoney = {
24+
type: 'Money';
25+
value: Money;
26+
};
27+
28+
type DataPercent = {
29+
type: 'Percent';
30+
value: Percent;
31+
};
32+
33+
export type DataValue = Money | Percent;
34+
35+
export type Money = {
36+
currency: string;
37+
amount: number;
38+
};
39+
40+
export type Percent = {
41+
percent: number;
42+
};
43+
44+
const getDataAmount = (data: Data): number => {
45+
switch (data.type) {
46+
case 'Money':
47+
return data.value.amount;
48+
case 'Percent':
49+
return data.value.percent;
50+
default: {
51+
// Здесь TypeScript должен понимать, что этот код не должен быть достигнут
52+
const unhandled: never = data; // :never должен остаться
53+
throw new Error(`unknown type: ${data}`);
54+
}
55+
}
56+
};

src/homeworks/ts1/3_write.test.js

Lines changed: 29 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,30 @@
1-
// Этот блок кода удалить и раскомментировать код ниже
2-
it('remove it', () => {
3-
expect(true).toBe(true);
4-
});
1+
import { createRandomOperation, createRandomProduct } from './3_write';
2+
3+
describe('all', () => {
4+
it('operation', () => {
5+
const createdAt = '2023-06-06T12:06:56.957Z';
6+
const operation = createRandomOperation(createdAt);
7+
expect(operation).toHaveProperty('createdAt', createdAt);
8+
expect(operation).toHaveProperty('id');
9+
expect(operation).toHaveProperty('name');
10+
expect(operation).toHaveProperty('desc');
11+
expect(operation).toHaveProperty('createdAt');
12+
expect(operation).toHaveProperty('amount');
13+
expect(operation).toHaveProperty('category');
14+
expect(operation).toHaveProperty('type');
15+
});
516

6-
// import { createRandomOperation, createRandomProduct } from './3_write';
7-
//
8-
// describe('all', () => {
9-
// it('operation', () => {
10-
// const createdAt = '2023-06-06T12:06:56.957Z';
11-
// const operation = createRandomOperation(createdAt);
12-
// expect(operation).toHaveProperty('createdAt', createdAt);
13-
// expect(operation).toHaveProperty('id');
14-
// expect(operation).toHaveProperty('name');
15-
// expect(operation).toHaveProperty('desc');
16-
// expect(operation).toHaveProperty('createdAt');
17-
// expect(operation).toHaveProperty('amount');
18-
// expect(operation).toHaveProperty('category');
19-
// expect(operation).toHaveProperty('type');
20-
// });
21-
//
22-
// it('product', () => {
23-
// const createdAt = '2023-06-06T12:06:56.957Z';
24-
// const product = createRandomProduct(createdAt);
25-
// expect(product).toHaveProperty('createdAt', createdAt);
26-
// expect(product).toHaveProperty('id');
27-
// expect(product).toHaveProperty('name');
28-
// expect(product).toHaveProperty('photo');
29-
// expect(product).toHaveProperty('desc');
30-
// expect(product).toHaveProperty('createdAt');
31-
// expect(product).toHaveProperty('oldPrice');
32-
// expect(product).toHaveProperty('price');
33-
// expect(product).toHaveProperty('category');
34-
// });
35-
// });
17+
it('product', () => {
18+
const createdAt = '2023-06-06T12:06:56.957Z';
19+
const product = createRandomProduct(createdAt);
20+
expect(product).toHaveProperty('createdAt', createdAt);
21+
expect(product).toHaveProperty('id');
22+
expect(product).toHaveProperty('name');
23+
expect(product).toHaveProperty('photo');
24+
expect(product).toHaveProperty('desc');
25+
expect(product).toHaveProperty('createdAt');
26+
expect(product).toHaveProperty('oldPrice');
27+
expect(product).toHaveProperty('price');
28+
expect(product).toHaveProperty('category');
29+
});
30+
});

0 commit comments

Comments
 (0)