Skip to content

Commit 26cdc63

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

File tree

5 files changed

+214
-117
lines changed

5 files changed

+214
-117
lines changed

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

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,26 @@
11
// Этот блок кода удалить и раскомментировать код ниже
2-
it('remove it', () => {
3-
expect(true).toBe(true);
4-
});
5-
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-
// });
2+
// it('remove it', () => {
3+
// expect(true).toBe(true);
264
// });
5+
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+
});
Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,46 @@
11
/**
22
* Нужно превратить файл в ts и указать типы аргументов и типы возвращаемого значения
33
* */
4-
export const removePlus = (string) => string.replace(/^\+/, '');
4+
export const removePlus = (string: string) => string.replace(/^\+/, '');
55

6-
export const addPlus = (string) => `+${string}`;
6+
export const addPlus = (string: string) => `+${string}`;
77

8-
export const removeFirstZeros = (value) => value.replace(/^(-)?[0]+(-?\d+.*)$/, '$1$2');
8+
export const removeFirstZeros = (value: string) => value.replace(/^(-)?[0]+(-?\d+.*)$/, '$1$2');
99

10-
export const getBeautifulNumber = (value, separator = ' ') =>
10+
export const getBeautifulNumber = (value: string, separator = ' ') =>
1111
value?.toString().replace(/\B(?=(\d{3})+(?!\d))/g, separator);
1212

13-
export const round = (value, accuracy = 2) => {
13+
export const round = (value: number, accuracy = 2) => {
1414
const d = 10 ** accuracy;
1515
return Math.round(value * d) / d;
1616
};
1717

1818
const transformRegexp =
1919
/(matrix\(-?\d+(\.\d+)?, -?\d+(\.\d+)?, -?\d+(\.\d+)?, -?\d+(\.\d+)?, )(-?\d+(\.\d+)?), (-?\d+(\.\d+)?)\)/;
2020

21-
export const getTransformFromCss = (transformCssString) => {
21+
export const getTransformFromCss = (transformCssString: string) => {
2222
const data = transformCssString.match(transformRegexp);
2323
if (!data) return { x: 0, y: 0 };
2424
return {
2525
x: parseInt(data[6], 10),
2626
y: parseInt(data[8], 10),
2727
};
2828
};
29-
30-
export const getColorContrastValue = ([red, green, blue]) =>
29+
//кортеж
30+
export const getColorContrastValue = ([red, green, blue]: [number, number, number]) =>
3131
// http://www.w3.org/TR/AERT#color-contrast
3232
Math.round((red * 299 + green * 587 + blue * 114) / 1000);
3333

34-
export const getContrastType = (contrastValue) => (contrastValue > 125 ? 'black' : 'white');
34+
export const getContrastType = (contrastValue: number) => (contrastValue > 125 ? 'black' : 'white');
3535

3636
export const shortColorRegExp = /^#[0-9a-f]{3}$/i;
3737
export const longColorRegExp = /^#[0-9a-f]{6}$/i;
3838

39-
export const checkColor = (color) => {
39+
export const checkColor = (color: string) => {
4040
if (!longColorRegExp.test(color) && !shortColorRegExp.test(color)) throw new Error(`invalid hex color: ${color}`);
4141
};
4242

43-
export const hex2rgb = (color) => {
43+
export const hex2rgb = (color: string) => {
4444
checkColor(color);
4545
if (shortColorRegExp.test(color)) {
4646
const red = parseInt(color.substring(1, 2), 16);
@@ -54,11 +54,23 @@ export const hex2rgb = (color) => {
5454
return [red, green, blue];
5555
};
5656

57-
export const getNumberedArray = (arr) => arr.map((value, number) => ({ value, number }));
58-
export const toStringArray = (arr) => arr.map(({ value, number }) => `${value}_${number}`);
57+
export const getNumberedArray = (arr: Array<number>) => arr.map((value, number) => ({ value, number }));
58+
export const toStringArray = (arr: { value: string; number: string }[]) =>
59+
arr.map(({ value, number }) => `${value}_${number}`);
60+
61+
type TCustomer = {
62+
id: number;
63+
name: string;
64+
age: number;
65+
isSubscribed: boolean;
66+
};
67+
68+
type TCustomerMap = {
69+
[key: TCustomer['id']]: Omit<TCustomer, 'id'>;
70+
};
5971

60-
export const transformCustomers = (customers) => {
61-
return customers.reduce((acc, customer) => {
72+
export const transformCustomers = (customers: Array<TCustomer>) => {
73+
return customers.reduce<TCustomerMap>((acc, customer) => {
6274
acc[customer.id] = { name: customer.name, age: customer.age, isSubscribed: customer.isSubscribed };
6375
return acc;
6476
}, {});

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: 33 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,35 @@
11
// Этот блок кода удалить и раскомментировать код ниже
2-
it('remove it', () => {
3-
expect(true).toBe(true);
4-
});
5-
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-
// });
2+
// it('remove it', () => {
3+
// expect(true).toBe(true);
354
// });
5+
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+
});

0 commit comments

Comments
 (0)