Skip to content
Merged
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
89 changes: 89 additions & 0 deletions src/homeworks/ts1/1_base.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/**
* Нужно превратить файл в ts и указать типы аргументов и типы возвращаемого значения
* */
export const removePlus = (string: string): string => string.replace(/^\+/, '');

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

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

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

export const round = (value: number, accuracy: number = 2): number => {
const d = 10 ** accuracy;
return Math.round(value * d) / d;
};

const transformRegexp: RegExp =
/(matrix\(-?\d+(\.\d+)?, -?\d+(\.\d+)?, -?\d+(\.\d+)?, -?\d+(\.\d+)?, )(-?\d+(\.\d+)?), (-?\d+(\.\d+)?)\)/;

type TransformedRegexp = {

Choose a reason for hiding this comment

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

Прекрасно

x: number;
y: number;
};

export const getTransformFromCss = (transformCssString: string): TransformedRegexp => {
const data = transformCssString.match(transformRegexp);
if (!data) return { x: 0, y: 0 };
return {
x: parseInt(data[6], 10),
y: parseInt(data[8], 10),
};
};

type Colors = [red: number, green: number, blue: number];

export const getColorContrastValue = ([red, green, blue]: Colors): number =>
// http://www.w3.org/TR/AERT#color-contrast
Math.round((red * 299 + green * 587 + blue * 114) / 1000);

type BlackOrWhite = 'black' | 'white';

Choose a reason for hiding this comment

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

Отличное решение которое в дальнейшем может сэкономить уйму сил, времени и денег


export const getContrastType = (contrastValue: number): BlackOrWhite => (contrastValue > 125 ? 'black' : 'white');

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

export const checkColor = (color: string): void | never => {
if (!longColorRegExp.test(color) && !shortColorRegExp.test(color)) throw new Error(`invalid hex color: ${color}`);
};

export const hex2rgb = (color: string): Colors => {
checkColor(color);
if (shortColorRegExp.test(color)) {
const red = parseInt(color.substring(1, 2), 16);
const green = parseInt(color.substring(2, 3), 16);
const blue = parseInt(color.substring(3, 4), 16);
return [red, green, blue];
}
const red = parseInt(color.substring(1, 3), 16);
const green = parseInt(color.substring(3, 5), 16);
const blue = parseInt(color.substring(5, 8), 16);
return [red, green, blue];
};

type NumberedArrayItem<T> = {
value: T;
number: number;
};

export const getNumberedArray = <T>(arr: T[]): NumberedArrayItem<T>[] =>
arr.map((value, number) => ({ value, number }));
export const toStringArray = <T>(arr: NumberedArrayItem<T>[]) => arr.map(({ value, number }) => `${value}_${number}`);

type Customer = {
id: number;
name: string;
age: number;
isSubscribed: boolean;
};

type TransformedCustomer = Record<number, Omit<Customer, 'id'>>;

export const transformCustomers = (customers: Customer[]): TransformedCustomer => {
return customers.reduce((acc: TransformedCustomer, customer) => {
acc[customer.id] = { name: customer.name, age: customer.age, isSubscribed: customer.isSubscribed };
return acc;
}, {});
};
86 changes: 44 additions & 42 deletions src/homeworks/ts1/2_repair.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,48 @@
* Здесь код с ошибками типов. Нужно их устранить
* */

// // Мы это не проходили, но по тексту ошибки можно понять, как это починить
// export const getFakeApi = async (): void => {
// const result = await fetch('https://jsonplaceholder.typicode.com/todos/1').then((response) => response.json());
// console.log(result);
// };
// Мы это не проходили, но по тексту ошибки можно понять, как это починить
export const getFakeApi = async (): Promise<void> => {
const result = await fetch('https://jsonplaceholder.typicode.com/todos/1').then((response) => response.json());
console.log(result);
};
//
// // Мы это не проходили, но по тексту ошибки можно понять, как это починить
// export class SomeClass {
// constructor() {
// this.set = new Set([1]);
// this.channel = new BroadcastChannel('test-broadcast-channel');
// }
// }
//
// export type Data = {
// type: 'Money' | 'Percent';
// value: DataValue;
// };
//
// export type DataValue = Money | Percent;
//
// export type Money = {
// currency: string;
// amount: number;
// };
//
// export type Percent = {
// percent: number;
// };
//
// // Здесь, возможно, нужно использовать as, возможно в switch передавать немного по-другому
// const getDataAmount = (data: Data): number => {
// switch (data.type) {
// case 'Money':
// return data.value.amount;
//
// default: {
// // eslint-disable-next-line @typescript-eslint/no-unused-vars
// const unhandled: never = data; // здесь, возможно, нужно использовать нечто другое. :never должен остаться
// throw new Error(`unknown type: ${data.type}`);
// }
// }
// };
// Мы это не проходили, но по тексту ошибки можно понять, как это починить
export class SomeClass {
readonly set: Set<number>;
readonly channel: BroadcastChannel;
constructor() {
this.set = new Set([1]);
this.channel = new BroadcastChannel('test-broadcast-channel');
}
}

export type Money = {
currency: string;
amount: number;
};

export type Percent = {
percent: number;
};

export type DataValue = Money | Percent;

export type Data = {
type: 'Money' | 'Percent';
value: DataValue;
};

// Здесь, возможно, нужно использовать as, возможно в switch передавать немного по-другому
const getDataAmount = (data: Data): number | never => {
switch (data.type) {
case 'Money':
return (data.value as Money).amount;

default: {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const unhandled: never = data as never; // здесь, возможно, нужно использовать нечто другое. :never должен остаться
throw new Error(`unknown type: ${data.type}`);
}
}
};
97 changes: 97 additions & 0 deletions src/homeworks/ts1/3_write.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,103 @@
* Поэтому в идеале чтобы функции возвращали случайные данные, но в то же время не абракадабру.
* В целом сделайте так, как вам будет удобно.
* */
import crypto from 'crypto';
import { names, photos, nouns, adjectives } from './data';

type Category = {
id: string;
name: string;
photo?: string;
};

type Product = {
id: string;
name: string;
photo: string;
desc?: string;
createdAt: string;
oldPrice?: number;
price: number;
category: Category;
};

type Operation = Cost | Profit;

type Cost = {
id: string;
name: string;
desc?: string;
createdAt: string;
amount: number;
category: Category;
type: 'Cost';
};

type Profit = {
id: string;
name: string;
desc?: string;
createdAt: string;
amount: number;
category: Category;
type: 'Profit';
};

const getRandomItemFromArray = <T>(arr: T[]): T => arr[Math.floor(Math.random() * arr.length)];
const getRandomNumber = (min: number, max: number): number => Math.floor(Math.random() * (max - min + 1)) + min;
const getRandomDescription = (nouns: string[], adjectives: string[]): string => {
const fourAdjectives = [...Array(4)].map(() => getRandomItemFromArray(adjectives)).join(' ');
const noun = getRandomItemFromArray(nouns);
return `${fourAdjectives} ${noun}`;
};
const getRandomId = crypto.randomUUID;
const createRandomCategory = (): Category => ({
id: getRandomId(),
name: getRandomItemFromArray(names),
photo: getRandomItemFromArray(photos),
});

const createRandomCost = (createdAt: string): Cost => ({
id: getRandomId(),
name: getRandomItemFromArray(names),
desc: getRandomDescription(nouns, adjectives),
createdAt,
amount: getRandomNumber(100, 1000),
category: createRandomCategory(),
type: 'Cost',
});

const createRandomProfit = (createdAt: string): Profit => ({
id: getRandomId(),
name: getRandomItemFromArray(names),
desc: getRandomDescription(nouns, adjectives),
createdAt,
amount: getRandomNumber(100, 1000),
category: createRandomCategory(),
type: 'Profit',
});

export const createRandomOperation = (createdAt: string): Operation => {
type OperationsMap = Record<number, (createdAt: string) => Operation>;
const operationsMap: OperationsMap = {
0: createRandomCost,
1: createRandomProfit,
};
const randomNumber = getRandomNumber(0, Object.keys(operationsMap).length - 1);

return operationsMap[randomNumber](createdAt);
};

export const createRandomProduct = (createdAt: string): Product => ({
id: getRandomId(),
name: getRandomItemFromArray(names),
photo: getRandomItemFromArray(photos),
desc: getRandomDescription(nouns, adjectives),
createdAt,
oldPrice: getRandomNumber(100, 1000),
price: getRandomNumber(100, 1000),
category: createRandomCategory(),
});

/**
* Нужно создать тип Category, он будет использоваться ниже.
Expand Down
Loading