From ca762ca23bc656067c6d68c0ebc65c7261e6c33a Mon Sep 17 00:00:00 2001 From: Sergey Melyukov Date: Mon, 27 Feb 2023 12:00:16 +0300 Subject: [PATCH 1/3] week-2 --- projects/array-objects/index.js | 49 ++++++++ projects/array-objects/index.spec.js | 78 ++++++++++++ projects/exceptions/index.js | 91 ++++++++++++++ projects/exceptions/index.spec.js | 178 +++++++++++++++++++++++++++ projects/loft-photo-1/friends.json | 32 +++++ projects/loft-photo-1/index.js | 0 projects/loft-photo-1/model.js | 9 ++ projects/loft-photo-1/photos.json | 72 +++++++++++ projects/loft-photo-1/readme.md | 71 +++++++++++ 9 files changed, 580 insertions(+) create mode 100644 projects/array-objects/index.js create mode 100644 projects/array-objects/index.spec.js create mode 100644 projects/exceptions/index.js create mode 100644 projects/exceptions/index.spec.js create mode 100644 projects/loft-photo-1/friends.json create mode 100644 projects/loft-photo-1/index.js create mode 100644 projects/loft-photo-1/model.js create mode 100644 projects/loft-photo-1/photos.json create mode 100644 projects/loft-photo-1/readme.md diff --git a/projects/array-objects/index.js b/projects/array-objects/index.js new file mode 100644 index 000000000..ca1ebc4c6 --- /dev/null +++ b/projects/array-objects/index.js @@ -0,0 +1,49 @@ +/* ДЗ 2 - работа с массивами и объектами */ + +/* + Задание 1: + + Напишите аналог встроенного метода forEach для работы с массивами. + Посмотрите как работает forEach и повторите это поведение для массива, который будет передан в параметре array + + Пример: + forEach([1, 2, 3], (el) => console.log(el)); // выведет каждый элемент массива + */ +function forEach() {} + +/* + Задание 2: + + Напишите аналог встроенного метода map для работы с массивами. + Посмотрите как работает map и повторите это поведение для массива, который будет передан в параметре array + + Пример: + const newArray = map([1, 2, 3], (el) => el ** 2); + console.log(newArray); // выведет [1, 4, 9] + */ +function map() {} + +/* + Задание 3: + + Напишите аналог встроенного метода reduce для работы с массивами. + Посмотрите как работает reduce и повторите это поведение для массива, который будет передан в параметре array + + Пример: + const sum = reduce([1, 2, 3], (all, current) => all + current); + console.log(sum); // выведет 6 + */ +function reduce() {} + +/* + Задание 4: + + Функция должна перебрать все свойства объекта, преобразовать их имена в верхний регистр и вернуть в виде массива + + Пример: + const keys = upperProps({ name: 'Сергей', lastName: 'Петров' }); + console.log(keys) // выведет ['NAME', 'LASTNAME'] + */ +function upperProps() {} + +export { forEach, map, reduce, upperProps }; diff --git a/projects/array-objects/index.spec.js b/projects/array-objects/index.spec.js new file mode 100644 index 000000000..eddc0bfdc --- /dev/null +++ b/projects/array-objects/index.spec.js @@ -0,0 +1,78 @@ +import { forEach, map, reduce, upperProps } from './index'; + +describe('ДЗ 3 - объекты и массивы', () => { + describe('forEach', () => { + it('должна вызывать функцию для каждого элемента массива', () => { + const array = [1, 2, 3]; + const fn = jest.fn(); + + forEach(array, fn); + + for (let i = 0; i < array.length; i++) { + expect(fn).nthCalledWith(i + 1, array[i], i, array); + } + }); + }); + + describe('map', () => { + it('должна вызывать функцию для каждого элемента массива и не изменять оригинальный массив', () => { + const originalArray = [4, 5, 6]; + const array = [...originalArray]; + const modified = array.map((el) => el ** 2); + const fn = jest.fn((el) => el ** 2); + + expect(map(array, fn)).toEqual(modified); + expect(array).toEqual(originalArray); + + for (let i = 0; i < array.length; i++) { + expect(fn).nthCalledWith(i + 1, array[i], i, array); + } + }); + }); + + describe('reduce', () => { + it('должна вызывать функцию для каждого элемента и передавать предыдущий результат первым аргументом', () => { + const originalArray = [7, 8, 9]; + const array = [...originalArray]; + const modified = array.reduce((all, current) => all + current); + const fn = jest.fn((all, current) => all + current); + + expect(reduce(array, fn)).toEqual(modified); + expect(array).toEqual(originalArray); + + let sum = array[0]; + + for (let i = 1; i < array.length; i++) { + expect(fn).nthCalledWith(i, sum, array[i], i, array); + sum += array[i]; + } + }); + + it('должна учитывать initial', () => { + const originalArray = [1, 3, 5]; + const array = [...originalArray]; + const modified = array.reduce((all, current) => all + current, 10); + const fn = jest.fn((all, current) => all + current); + + expect(reduce(array, fn, 10)).toEqual(modified); + expect(array).toEqual(originalArray); + + let sum = 10; + + for (let i = 0; i < array.length; i++) { + expect(fn).nthCalledWith(i + 1, sum, array[i], i, array); + sum += array[i]; + } + }); + }); + + describe('upperProps', () => { + it('должна возвращать массив с именами свойств и преобразовывать эти имена в верхний регистр', () => { + const obj = { a: 1, b: 2 }; + const target = ['A', 'B']; + const result = upperProps(obj); + + expect(result).toEqual(target); + }); + }); +}); diff --git a/projects/exceptions/index.js b/projects/exceptions/index.js new file mode 100644 index 000000000..d09b05496 --- /dev/null +++ b/projects/exceptions/index.js @@ -0,0 +1,91 @@ +/* ДЗ 3 - работа с исключениями и отладчиком */ + +/* + Задание 1: + + 1.1: Функция isAllTrue принимает массив в параметре array и другую функцию в параметре fn. + Нужно по-очереди запустить функцию fn для всех элементов массива. + isAllTrue должна вернуть true только если fn вернула true для всех элементов массива. + Если хотя бы для одного из элементов массива fn вернула false, то и isAllTrue должна вернуть false. + + 1.2: Необходимо выбрасывать исключение в случаях: + - array не массив или пустой массив (с текстом "empty array") + для проверки на массив вам может помочь функция Array.isArray() + - fn не является функцией (с текстом "fn is not a function") + для проверки на функцию вам может помочь оператор typeof + + Запрещено использовать встроенные методы для работы с массивами + + Пример: + isAllTrue([1, 2, 3, 4, 5], n => n < 10) // вернет true (потому что все элементы массива меньше 10) + isAllTrue([100, 2, 3, 4, 5], n => n < 10) // вернет false (потому что как минимум первый элемент больше 10) + */ +function isAllTrue(array, fn) {} + +/* + Задание 2: + + 2.1: Функция isSomeTrue принимает массив в параметре array и функцию в параметре fn. + Нужно по-очереди запустить функцию fn для всех элементов массива. + isSomeTrue должна вернуть true только если fn вернула true хотя бы для одного из элементов массива. + Если fn не вернула true ни для одного элементов массива, то и isSomeTrue должна вернуть false. + + 2.2: Необходимо выбрасывать исключение в случаях: + - array не массив или пустой массив (с текстом "empty array") + для проверки на массив вам может помочь функция Array.isArray() + - fn не является функцией (с текстом "fn is not a function") + для проверки на функцию вам может помочь оператор typeof + + Запрещено использовать встроенные методы для работы с массивами + + Пример: + isSomeTrue([1, 2, 30, 4, 5], n => n > 20) // вернет true (потому что в массиве есть хотя бы один элемент больше 20) + isSomeTrue([1, 2, 3, 4, 5], n => n > 20) // вернет false (потому что в массиве нет ни одного элемента больше 20) + */ +function isSomeTrue(array, fn) {} + +/* + Задание 3: + + 3.1: Функция returnBadArguments принимает заранее неизвестное количество аргументов, первым из которых является функция fn + returnBadArguments должна поочередно запустить fn для каждого переданного аргумента (кроме самой fn) + + 3.2: returnBadArguments должна вернуть массив аргументов, для которых fn выбросила исключение + + 3.3: Необходимо выбрасывать исключение в случаях: + - fn не является функцией (с текстом "fn is not a function") + для проверки на функцию вам может помочь оператор typeof + */ +function returnBadArguments() {} + +/* + Задание 4: + + 4.1: Функция calculator имеет параметр number (по умолчанию - 0) + + 4.2: Функция calculator должна вернуть объект, у которого должно быть несколько методов: + - sum - складывает number с переданными аргументами + - dif - вычитает из number переданные аргументы + - div - делит number на первый аргумент. Результат делится на следующий аргумент (если передан) и так далее + - mul - умножает number на первый аргумент. Результат умножается на следующий аргумент (если передан) и так далее + + Количество передаваемых в методы аргументов заранее неизвестно + + 4.3: Необходимо выбрасывать исключение в случаях: + - number не является числом (с текстом "number is not a number") + - какой-либо из аргументов div является нулем (с текстом "division by 0") + + Пример: + const myCalc = calculator(10); + + console.log(calc.sum(1, 2, 3)); // выведет 16 (10 + 1 + 2 + 3) + console.log(calc.dif(1, 2, 3)); // выведет 5 (10 - 1 - 2 - 3) + console.log(calc.mul(1, 2, 3)); // выведет 60 (10 * 1 * 2 * 3) + console.log(calc.div(2, 2)); // выведет 2.5 (10 / 2 / 2) + console.log(calc.div(2, 0)); // выбросит исключение, потому что один из аргументов равен 0 + */ +function calculator(number) {} + +/* При решении задач, постарайтесь использовать отладчик */ + +export { isAllTrue, isSomeTrue, returnBadArguments, calculator }; diff --git a/projects/exceptions/index.spec.js b/projects/exceptions/index.spec.js new file mode 100644 index 000000000..bb9b4d0c1 --- /dev/null +++ b/projects/exceptions/index.spec.js @@ -0,0 +1,178 @@ +import { calculator, isAllTrue, isSomeTrue, returnBadArguments } from './index'; + +describe('ДЗ 2 - работа с исключениями и отладчиком', () => { + describe('isAllTrue', () => { + it('должна вызывать fn для всех элементов массива', () => { + const array = ['l', 's']; + const pass = []; + + isAllTrue(array, (e) => pass.push(e)); + + expect(pass).toEqual(array); + }); + + it('должна вернуть true, если fn вернула true для всех элементов массива', () => { + const array = [1, 2, 3]; + const result = isAllTrue(array, Number.isFinite); + + expect(result); + }); + + it('должна вернуть false, если fn вернула false хотя бы для одного элемента массива', () => { + const array = [1, 2, 3]; + + array.push('ls'); + const result = isAllTrue(array, Number.isFinite); + + expect(!result); + }); + + it('должна выбросить исключение, если передан пустой массив', () => { + expect(() => isAllTrue([], () => {})).toThrow('empty array'); + }); + + it('должна выбросить исключение, если передан не массив', () => { + expect(() => isAllTrue(':(', () => {})).toThrow('empty array'); + expect(() => isAllTrue({}, () => {})).toThrow('empty array'); + }); + + it('должна выбросить исключение, если fn не функция', () => { + const array = [1, 2, 3]; + + expect(() => isAllTrue(array, ':(')).toThrow('fn is not a function'); + }); + }); + + describe('isSomeTrue', () => { + it('должна вернуть true, если fn вернула true хотя бы для одного элемента массива', () => { + const array = ['l', 's', 3]; + const result = isSomeTrue(array, Number.isFinite); + + expect(result); + }); + + it('должна вернуть false, если fn не вернула true хотя бы для одного элемента массива', () => { + const array = ['l', 's']; + const result = isSomeTrue(array, Number.isFinite); + + expect(!result); + }); + + it('должна выбросить исключение, если передан пустой массив', () => { + expect(() => isSomeTrue([], () => {})).toThrow('empty array'); + }); + + it('должна выбросить исключение, если передан не массив', () => { + expect(() => isSomeTrue(':(', () => {})).toThrow('empty array'); + expect(() => isSomeTrue({}, () => {})).toThrow('empty array'); + }); + + it('должна выбросить исключение, если fn не функция', () => { + const array = [1, 2, 3]; + + expect(() => isSomeTrue(array, ':(')).toThrow('fn is not a function'); + }); + }); + + describe('returnBadArguments', () => { + it('должна вызывать fn для всех элементов массива', () => { + const array = [1, 2, 3]; + const pass = []; + + returnBadArguments((e) => pass.push(e), ...array); + + expect(pass).toEqual(array); + }); + + it('должна вернуть массив с аргументами, для которых fn выбрасила исключение', () => { + const evenNumbers = [2, 4, 6]; + const oddNumbers = [1, 3, 5]; + const fn = (a) => { + if (a % 2 !== 0) { + throw new Error('not even'); + } + }; + const result = returnBadArguments(fn, ...evenNumbers, ...oddNumbers); + + expect(result).toEqual(oddNumbers); + }); + + it('должна вернуть массив пустой массив, если не передано дополнительных аргументов', () => { + const fn = () => ':)'; + const result = returnBadArguments(fn); + + expect(result.length).toBe(0); + }); + + it('должна выбросить исключение, если fn не функция', () => { + expect(() => returnBadArguments(':(')).toThrow('fn is not a function'); + }); + }); + + describe('calculator', () => { + it('должна возвращать объект с методами', () => { + const calc = calculator(); + + expect(Object.keys(calc)).toEqual(['sum', 'dif', 'div', 'mul']); + }); + + it('метод sum должен складывать аргументы', () => { + const initialValue = 20; + const calc = calculator(initialValue); + const args = [1, 2, 3]; + + expect(calc.sum(...args)).toBe( + args.reduce((prev, current) => prev + current, initialValue) + ); + }); + + it('метод dif должен вычитать аргументы', () => { + const initialValue = 10; + const calc = calculator(initialValue); + const args = [1, 2, 3]; + + expect(calc.dif(...args)).toBe( + args.reduce((prev, current) => prev - current, initialValue) + ); + }); + + it('метод div должен делить аргументы', () => { + const initialValue = 20; + const calc = calculator(initialValue); + const args = [1, 2]; + + expect(calc.div(...args)).toBe( + args.reduce((prev, current) => prev / current, initialValue) + ); + }); + + it('метод div должен выбрасывать исключение, если хотя бы один из аргументов равен 0', () => { + const initialValue = 20; + const calc = calculator(initialValue); + const args = [1, 2, 0]; + + expect(() => calc.div(...args)).toThrow('division by 0'); + }); + + it('метод mul должен умножать аргументы', () => { + const initialValue = 10; + const calc = calculator(initialValue); + const args = [1, 2]; + + expect(calc.mul(...args)).toBe( + args.reduce((prev, current) => prev * current, initialValue) + ); + }); + + it('функция должна выбрасывать исключение, если number не является числом', () => { + expect(() => calculator(':(')).toThrow('number is not a number'); + }); + + it('значение по умолчанию для аргумента number должно быть равно 0', () => { + const calc = calculator(); + const args = [1, 2]; + + expect(calc.sum(...args)).toBe(args.reduce((prev, current) => prev + current)); + }); + }); +}); diff --git a/projects/loft-photo-1/friends.json b/projects/loft-photo-1/friends.json new file mode 100644 index 000000000..b861e0c00 --- /dev/null +++ b/projects/loft-photo-1/friends.json @@ -0,0 +1,32 @@ +[ + { + "id": 0, + "avatar": "https://via.placeholder.com/100?text=avatar", + "firstName": "Adrian", + "lastName": "Norman" + }, + { + "id": 1, + "avatar": "https://via.placeholder.com/100?text=avatar", + "firstName": "Gail", + "lastName": "Norton" + }, + { + "id": 2, + "avatar": "https://via.placeholder.com/100?text=avatar", + "firstName": "Molina", + "lastName": "Rodgers" + }, + { + "id": 3, + "avatar": "https://via.placeholder.com/100?text=avatar", + "firstName": "Adams", + "lastName": "Parrish" + }, + { + "id": 4, + "avatar": "https://via.placeholder.com/100?text=avatar", + "firstName": "Mercer", + "lastName": "Wiggins" + } +] \ No newline at end of file diff --git a/projects/loft-photo-1/index.js b/projects/loft-photo-1/index.js new file mode 100644 index 000000000..e69de29bb diff --git a/projects/loft-photo-1/model.js b/projects/loft-photo-1/model.js new file mode 100644 index 000000000..1e31e33b3 --- /dev/null +++ b/projects/loft-photo-1/model.js @@ -0,0 +1,9 @@ +// eslint-disable-next-line no-unused-vars +import photosDB from './photos.json'; +// eslint-disable-next-line no-unused-vars +import friendsDB from './friends.json'; + +export default { + getRandomElement(array) {}, + getNextPhoto() {}, +}; diff --git a/projects/loft-photo-1/photos.json b/projects/loft-photo-1/photos.json new file mode 100644 index 000000000..a299e6057 --- /dev/null +++ b/projects/loft-photo-1/photos.json @@ -0,0 +1,72 @@ +{ + "0": [ + { + "id": 10, + "url": "https://via.placeholder.com/360x680?text=photo 1 for Adrian Norman" + }, + { + "id": 11, + "url": "https://via.placeholder.com/360x680?text=photo 2 for Adrian Norman" + }, + { + "id": 12, + "url": "https://via.placeholder.com/360x680?text=photo 3 for Adrian Norman" + } + ], + "1": [ + { + "id": 20, + "url": "https://via.placeholder.com/360x680?text=photo 1 for Gail Norton" + }, + { + "id": 21, + "url": "https://via.placeholder.com/360x680?text=photo 2 for Gail Norton" + }, + { + "id": 22, + "url": "https://via.placeholder.com/360x680?text=photo 3 for Gail Norton" + } + ], + "2": [ + { + "id": 30, + "url": "https://via.placeholder.com/360x680?text=photo 1 for Molina Rodgers" + }, + { + "id": 31, + "url": "https://via.placeholder.com/360x680?text=photo 2 for Molina Rodgers" + }, + { + "id": 32, + "url": "https://via.placeholder.com/360x680?text=photo 3 for Molina Rodgers" + } + ], + "3": [ + { + "id": 40, + "url": "https://via.placeholder.com/360x680?text=photo 1 for Adams Parrish" + }, + { + "id": 41, + "url": "https://via.placeholder.com/360x680?text=photo 2 for Adams Parrish" + }, + { + "id": 42, + "url": "https://via.placeholder.com/360x680?text=photo 3 for Adams Parrish" + } + ], + "4": [ + { + "id": 50, + "url": "https://via.placeholder.com/360x680?text=photo 1 for Mercer Wiggins" + }, + { + "id": 51, + "url": "https://via.placeholder.com/360x680?text=photo 2 for Mercer Wiggins" + }, + { + "id": 52, + "url": "https://via.placeholder.com/360x680?text=photo 3 for Mercer Wiggins" + } + ] +} \ No newline at end of file diff --git a/projects/loft-photo-1/readme.md b/projects/loft-photo-1/readme.md new file mode 100644 index 000000000..cd26a9f0e --- /dev/null +++ b/projects/loft-photo-1/readme.md @@ -0,0 +1,71 @@ +## Массивы и объекты + +Реализуйте объект с двумя методами: + +- `getRandomElement(array)` +- `getNextPhoto()` + +### `getRandomElement(array)` + +Метод принимает массив в параметре `array` и должен вернуть **случайный** элемент из этого масства при каждом вызове. + +Например: + +```js +const fruits = ['банан', 'яблоко', 'груша']; + +console.log(getRandomElement(fruits)); // груша +console.log(getRandomElement(fruits)); // банан +console.log(getRandomElement(fruits)); // банан +``` + +Для получения случайного числа может пригодиться метод [Math.random()](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Math/random). Этот метод возвращает случайное число между 0 и 1 (например 0.548) + +Вот так можно получить число от 0 до 10 (например): + +```js +console.log(Math.random() * 10); // 5.754356 +console.log(Math.random() * 10); // 2.12864 +``` + +А при помощи [parseInt](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/parseInt) можно убрать дробную часть: + +```js +console.log(parseInt(Math.random() * 10)); // 8 +console.log(parseInt(Math.random() * 10)); // 3 +``` + +### `getNextPhoto()` + +При каждом вызове метод должен вернуть информацию со случайным другом и случайной его фотографией. + +Информация должна быть возвращена в виде объекта из двух полей: `friend` и `url`. + +Например: + +```js +let photo = getNextPhoto(); + +console.log(photo.friend); // { firstName: 'Иван' } +console.log(photo.url); // https://... + +photo = getNextPhoto(); + +console.log(photo.friend); // { firstName: 'Сергей' } +console.log(photo.url); // https://... +``` + +Пример списка друзей и фотографий можно найти в файлах [friends.json](friends.json) и [photos.json](photos.json). + +В файле [friends.json](friends.json) хранится массив со списком друзей. У каждого друга есть имя, фамилия и идентификатор. + +В файле [photos.json](photos.json) хранится объект, ключами которого являются идентификаторы друзей, а значениями - массив фотографий этого друга. +У каждой фотографии есть идентификатор и url. + +Вот так, например, можно получить все фотографии друга с идентификатором `1`: + +```js +const photosDB = require('./photos.json'); + +console.log(photosDB[1]) // [ ... ] +``` From 66be795965be6989f03aa11591114dbd3f0a404b Mon Sep 17 00:00:00 2001 From: Sorokin Evgeniy Date: Sun, 25 Feb 2024 12:02:16 +0700 Subject: [PATCH 2/3] =?UTF-8?q?=D0=92=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5=D0=BD?= =?UTF-8?q?=D0=BD=D0=B0=D1=8F=20=D0=94=D0=97=20=D0=BD=D0=B5=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D1=8F=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package-lock.json | 16 ++-- package.json | 4 +- projects/array-objects/index.js | 51 ++++++++++- projects/exceptions/index.js | 155 ++++++++++++++++++++++++++++++-- projects/loft-photo-1/model.js | 18 +++- 5 files changed, 225 insertions(+), 19 deletions(-) diff --git a/package-lock.json b/package-lock.json index 15211bdad..6769605fe 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4210,9 +4210,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001442", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001442.tgz", - "integrity": "sha512-239m03Pqy0hwxYPYR5JwOIxRJfLTWtle9FV8zosfV5pHg+/51uD4nxcUlM8+mWWGfwKtt8lJNHnD3cWw9VZ6ow==", + "version": "1.0.30001589", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001589.tgz", + "integrity": "sha512-vNQWS6kI+q6sBlHbh71IIeC+sRwK2N3EDySc/updIGhIee2x5z00J4c1242/5/d6EpEMdOnk/m+6tuk4/tcsqg==", "dev": true, "funding": [ { @@ -4222,6 +4222,10 @@ { "type": "tidelift", "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" } ] }, @@ -15497,9 +15501,9 @@ "dev": true }, "caniuse-lite": { - "version": "1.0.30001442", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001442.tgz", - "integrity": "sha512-239m03Pqy0hwxYPYR5JwOIxRJfLTWtle9FV8zosfV5pHg+/51uD4nxcUlM8+mWWGfwKtt8lJNHnD3cWw9VZ6ow==", + "version": "1.0.30001589", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001589.tgz", + "integrity": "sha512-vNQWS6kI+q6sBlHbh71IIeC+sRwK2N3EDySc/updIGhIee2x5z00J4c1242/5/d6EpEMdOnk/m+6tuk4/tcsqg==", "dev": true }, "chalk": { diff --git a/package.json b/package.json index 88a301fd2..e653aff8d 100644 --- a/package.json +++ b/package.json @@ -29,10 +29,10 @@ "@babel/preset-env": "^7.20.2", "@babel/preset-typescript": "^7.21.0", "@babel/runtime": "^7.21.0", - "@typescript-eslint/eslint-plugin": "^5.49.0", - "@typescript-eslint/parser": "^5.49.0", "@types/jest": "^29.4.0", "@types/node": "^16.18.13", + "@typescript-eslint/eslint-plugin": "^5.49.0", + "@typescript-eslint/parser": "^5.49.0", "babel-jest": "^29.4.3", "babel-loader": "^9.1.2", "css-loader": "^6.7.3", diff --git a/projects/array-objects/index.js b/projects/array-objects/index.js index ca1ebc4c6..95ff94aba 100644 --- a/projects/array-objects/index.js +++ b/projects/array-objects/index.js @@ -9,7 +9,16 @@ Пример: forEach([1, 2, 3], (el) => console.log(el)); // выведет каждый элемент массива */ -function forEach() {} + +function forEach(array, fn) { + for (let i = 0; i < array.length; i++) { + fn(array[i], i, array); + } + //function fn(item, i, array) { + //console.log(item, i, array); + //return item; + //}; +} /* Задание 2: @@ -21,8 +30,22 @@ function forEach() {} const newArray = map([1, 2, 3], (el) => el ** 2); console.log(newArray); // выведет [1, 4, 9] */ -function map() {} +function map(array, fn) { + const newArr = []; + let a; + for (let i = 0; i < array.length; i++) { + a = fn(array[i], i, array); + newArr.push(a); + } + //function fn(item) { + //item = item ** 2; + // newArr.push(item); + //}; + // console.log(newArr); + return newArr; +} +//map([4,5,6], (el) => el ** 2); /* Задание 3: @@ -33,7 +56,20 @@ function map() {} const sum = reduce([1, 2, 3], (all, current) => all + current); console.log(sum); // выведет 6 */ -function reduce() {} +function reduce(array, fn, initial) { + //let s = sum; + let s = initial || array[0], + i = initial ? 0 : 1; + for (; i < array.length; i++) { + s = fn(s, array[i], i, array); + } + //function fn(sum, item) { + //sum += item; + // }; + //console.log(s); + return s; +} +//reduce([4, 5, 6], (el) => el + el, 10); /* Задание 4: @@ -44,6 +80,13 @@ function reduce() {} const keys = upperProps({ name: 'Сергей', lastName: 'Петров' }); console.log(keys) // выведет ['NAME', 'LASTNAME'] */ -function upperProps() {} +function upperProps(obj) { + const arr = []; + for (let key in obj) { + key = key.toUpperCase(); + arr.push(key); + } + return arr; +} export { forEach, map, reduce, upperProps }; diff --git a/projects/exceptions/index.js b/projects/exceptions/index.js index d09b05496..44bbdcf4b 100644 --- a/projects/exceptions/index.js +++ b/projects/exceptions/index.js @@ -1,5 +1,7 @@ /* ДЗ 3 - работа с исключениями и отладчиком */ +//import { error } from 'console'; + /* Задание 1: @@ -20,7 +22,38 @@ isAllTrue([1, 2, 3, 4, 5], n => n < 10) // вернет true (потому что все элементы массива меньше 10) isAllTrue([100, 2, 3, 4, 5], n => n < 10) // вернет false (потому что как минимум первый элемент больше 10) */ -function isAllTrue(array, fn) {} +function isAllTrue(array, fn) { + let tr = 0; + let fal = 0; + //try { + if (!Array.isArray(array) || array.length === 0) { + throw new Error('empty array'); + } + if (typeof fn !== 'function') { + throw new Error('fn is not a function'); + } + + for (let i = 0; i < array.length; i++) { + const z = fn(array[i], i, array); + if (z === true) { + tr++; + } else if (z === false) { + fal++; + } + } + + if (tr === array.length) { + console.log(true); + return true; + } else if (fal > 0) { + console.log(false); + return false; + } + //} catch (e) { + // console.log(e.message); + //}; +} +//isAllTrue([], 10); /* Задание 2: @@ -42,7 +75,38 @@ function isAllTrue(array, fn) {} isSomeTrue([1, 2, 30, 4, 5], n => n > 20) // вернет true (потому что в массиве есть хотя бы один элемент больше 20) isSomeTrue([1, 2, 3, 4, 5], n => n > 20) // вернет false (потому что в массиве нет ни одного элемента больше 20) */ -function isSomeTrue(array, fn) {} +function isSomeTrue(array, fn) { + let tr = 0; + let fal = 0; + //try { + if (!Array.isArray(array) || array.length === 0) { + throw new Error('empty array'); + } + if (typeof fn !== 'function') { + throw new Error('fn is not a function'); + } + + for (let i = 0; i < array.length; i++) { + const z = fn(array[i], i, array); + if (z === true) { + tr++; + } else if (z === false) { + fal++; + } + } + + if (tr > 0) { + console.log(true); + return true; + } else if (fal === array.length) { + console.log(false); + return false; + } + //} catch (e) { + //console.log(e.message); + //}; +} +//isSomeTrue([1, 2, 30, 4, 5], 20); /* Задание 3: @@ -56,7 +120,35 @@ function isSomeTrue(array, fn) {} - fn не является функцией (с текстом "fn is not a function") для проверки на функцию вам может помочь оператор typeof */ -function returnBadArguments() {} +function returnBadArguments(fn, ...args) { + const array = []; + //try { + if (typeof fn !== 'function') { + throw new Error('fn is not a function'); + } + + for (const arg of args) { + try { + fn(arg); + } catch { + array.push(arg); + } + } + /*for (var i = 1; i < args.length; i++) { + if (fn(args[i], i, args)) { + array.push(args[i]); + };*/ + /*try { + argument = fn(args[i]); + } catch (e) { + array.push(args[i]) + };*/ + return array; +} + +//} catch (e) { +// console.log(e.message); +//}; /* Задание 4: @@ -84,8 +176,61 @@ function returnBadArguments() {} console.log(calc.div(2, 2)); // выведет 2.5 (10 / 2 / 2) console.log(calc.div(2, 0)); // выбросит исключение, потому что один из аргументов равен 0 */ -function calculator(number) {} - +function calculator(number = 0) { + if (typeof number !== 'number') { + throw new Error('number is not a number'); + } + + return { + sum(...args) { + return args.reduce((all, curr) => all + curr, number); + /*for (var i = 0; i < args.length; i++) { + number += args[i]; + }; + return number;*/ + }, + + dif(...args) { + return args.reduce((all, curr) => all - curr, number); + /*for (var i = 0; i < args.length; i++) { + number -= args[i]; + }; + return number;*/ + }, + + div(...args) { + if (args.some((a) => a === 0)) { + throw new Error('division by 0'); + } + return args.reduce((all, curr) => all / curr, number); + //try { + /*for (var i = 0; i < args.length; i++) { + if (args[i] === 0) { + throw new Error("division by 0"); + }; + number /= args[i]; + }; + return number;*/ + //} catch (e) { + // console.log(e.message); + //}; + }, + + mul(...args) { + return args.reduce((all, curr) => all * curr, number); + /*for (var i = 0; i < args.length; i++) { + number *= args[i]; + }; + return number;*/ + }, + }; +} +/*const myCalc = calculator(); +console.log(myCalc.sum(1, 2, 3)); +console.log(myCalc.dif(1, 2, 3)); +console.log(myCalc.mul(1, 2, 3)); +console.log(myCalc.div(1, 2, 3)); +console.log(myCalc.div(2, 0));*/ /* При решении задач, постарайтесь использовать отладчик */ export { isAllTrue, isSomeTrue, returnBadArguments, calculator }; diff --git a/projects/loft-photo-1/model.js b/projects/loft-photo-1/model.js index 1e31e33b3..c753105c6 100644 --- a/projects/loft-photo-1/model.js +++ b/projects/loft-photo-1/model.js @@ -4,6 +4,20 @@ import photosDB from './photos.json'; import friendsDB from './friends.json'; export default { - getRandomElement(array) {}, - getNextPhoto() {}, + getRandomElement(array) { + if (!array.length) { + return null; + } + + const index = Math.round(Math.random() * (array.length - 1)); + return array[index]; + }, + + getNextPhoto() { + const friends = this.getRandomElement(friendsDB); + const photos = photosDB[friends.id]; + const photo = this.getRandomElement(photos); + + return { friends, url: photo.url }; + }, }; From 8d20eb12cf93af0a4dc5b6e10666fc3f79447911 Mon Sep 17 00:00:00 2001 From: Sorokin Evgeniy Date: Mon, 26 Feb 2024 10:28:36 +0700 Subject: [PATCH 3/3] =?UTF-8?q?=D0=A3=D1=81=D1=82=D1=80=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BD=D0=B5=D0=B4=D0=BE=D1=87=D1=91=D1=82=D1=8B=20?= =?UTF-8?q?=D0=B2=20=D0=94=D0=97=20=D0=BD=D0=B5=D0=B4=D0=B5=D0=BB=D1=8F-2?= =?UTF-8?q?=20=D0=A3=D0=B1=D1=80=D0=B0=D0=BB=20=D0=BB=D0=B8=D1=88=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=BA=D0=BE=D0=BC=D0=B5=D0=BD=D1=82=D0=B0=D1=80?= =?UTF-8?q?=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- projects/array-objects/index.js | 16 -------- projects/exceptions/index.js | 72 ++------------------------------- 2 files changed, 3 insertions(+), 85 deletions(-) diff --git a/projects/array-objects/index.js b/projects/array-objects/index.js index 95ff94aba..6c22cd3b0 100644 --- a/projects/array-objects/index.js +++ b/projects/array-objects/index.js @@ -14,10 +14,6 @@ function forEach(array, fn) { for (let i = 0; i < array.length; i++) { fn(array[i], i, array); } - //function fn(item, i, array) { - //console.log(item, i, array); - //return item; - //}; } /* @@ -37,15 +33,9 @@ function map(array, fn) { a = fn(array[i], i, array); newArr.push(a); } - //function fn(item) { - //item = item ** 2; - // newArr.push(item); - //}; - // console.log(newArr); return newArr; } -//map([4,5,6], (el) => el ** 2); /* Задание 3: @@ -57,19 +47,13 @@ function map(array, fn) { console.log(sum); // выведет 6 */ function reduce(array, fn, initial) { - //let s = sum; let s = initial || array[0], i = initial ? 0 : 1; for (; i < array.length; i++) { s = fn(s, array[i], i, array); } - //function fn(sum, item) { - //sum += item; - // }; - //console.log(s); return s; } -//reduce([4, 5, 6], (el) => el + el, 10); /* Задание 4: diff --git a/projects/exceptions/index.js b/projects/exceptions/index.js index 44bbdcf4b..c3163d921 100644 --- a/projects/exceptions/index.js +++ b/projects/exceptions/index.js @@ -1,7 +1,5 @@ /* ДЗ 3 - работа с исключениями и отладчиком */ -//import { error } from 'console'; - /* Задание 1: @@ -25,7 +23,6 @@ function isAllTrue(array, fn) { let tr = 0; let fal = 0; - //try { if (!Array.isArray(array) || array.length === 0) { throw new Error('empty array'); } @@ -35,25 +32,15 @@ function isAllTrue(array, fn) { for (let i = 0; i < array.length; i++) { const z = fn(array[i], i, array); - if (z === true) { - tr++; - } else if (z === false) { - fal++; - } + z ? tr++ : fal++; } if (tr === array.length) { - console.log(true); return true; } else if (fal > 0) { - console.log(false); return false; } - //} catch (e) { - // console.log(e.message); - //}; } -//isAllTrue([], 10); /* Задание 2: @@ -78,7 +65,6 @@ function isAllTrue(array, fn) { function isSomeTrue(array, fn) { let tr = 0; let fal = 0; - //try { if (!Array.isArray(array) || array.length === 0) { throw new Error('empty array'); } @@ -88,25 +74,15 @@ function isSomeTrue(array, fn) { for (let i = 0; i < array.length; i++) { const z = fn(array[i], i, array); - if (z === true) { - tr++; - } else if (z === false) { - fal++; - } + z ? tr++ : fal++; } if (tr > 0) { - console.log(true); return true; } else if (fal === array.length) { - console.log(false); return false; } - //} catch (e) { - //console.log(e.message); - //}; } -//isSomeTrue([1, 2, 30, 4, 5], 20); /* Задание 3: @@ -122,7 +98,6 @@ function isSomeTrue(array, fn) { */ function returnBadArguments(fn, ...args) { const array = []; - //try { if (typeof fn !== 'function') { throw new Error('fn is not a function'); } @@ -134,22 +109,9 @@ function returnBadArguments(fn, ...args) { array.push(arg); } } - /*for (var i = 1; i < args.length; i++) { - if (fn(args[i], i, args)) { - array.push(args[i]); - };*/ - /*try { - argument = fn(args[i]); - } catch (e) { - array.push(args[i]) - };*/ return array; } -//} catch (e) { -// console.log(e.message); -//}; - /* Задание 4: @@ -184,18 +146,10 @@ function calculator(number = 0) { return { sum(...args) { return args.reduce((all, curr) => all + curr, number); - /*for (var i = 0; i < args.length; i++) { - number += args[i]; - }; - return number;*/ }, dif(...args) { return args.reduce((all, curr) => all - curr, number); - /*for (var i = 0; i < args.length; i++) { - number -= args[i]; - }; - return number;*/ }, div(...args) { @@ -203,34 +157,14 @@ function calculator(number = 0) { throw new Error('division by 0'); } return args.reduce((all, curr) => all / curr, number); - //try { - /*for (var i = 0; i < args.length; i++) { - if (args[i] === 0) { - throw new Error("division by 0"); - }; - number /= args[i]; - }; - return number;*/ - //} catch (e) { - // console.log(e.message); - //}; }, mul(...args) { return args.reduce((all, curr) => all * curr, number); - /*for (var i = 0; i < args.length; i++) { - number *= args[i]; - }; - return number;*/ }, }; } -/*const myCalc = calculator(); -console.log(myCalc.sum(1, 2, 3)); -console.log(myCalc.dif(1, 2, 3)); -console.log(myCalc.mul(1, 2, 3)); -console.log(myCalc.div(1, 2, 3)); -console.log(myCalc.div(2, 0));*/ + /* При решении задач, постарайтесь использовать отладчик */ export { isAllTrue, isSomeTrue, returnBadArguments, calculator };