Browse Source

HW 2 done

suslov-dmytro 1 year ago
parent
commit
293166612a

+ 23 - 0
02/.gitignore

@@ -0,0 +1,23 @@
+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
+
+# dependencies
+/node_modules
+/.pnp
+.pnp.js
+
+# testing
+/coverage
+
+# production
+/build
+
+# misc
+.DS_Store
+.env.local
+.env.development.local
+.env.test.local
+.env.production.local
+
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*

+ 70 - 0
02/README.md

@@ -0,0 +1,70 @@
+# Getting Started with Create React App
+
+This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
+
+## Available Scripts
+
+In the project directory, you can run:
+
+### `npm start`
+
+Runs the app in the development mode.\
+Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
+
+The page will reload when you make changes.\
+You may also see any lint errors in the console.
+
+### `npm test`
+
+Launches the test runner in the interactive watch mode.\
+See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
+
+### `npm run build`
+
+Builds the app for production to the `build` folder.\
+It correctly bundles React in production mode and optimizes the build for the best performance.
+
+The build is minified and the filenames include the hashes.\
+Your app is ready to be deployed!
+
+See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
+
+### `npm run eject`
+
+**Note: this is a one-way operation. Once you `eject`, you can't go back!**
+
+If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
+
+Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
+
+You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
+
+## Learn More
+
+You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
+
+To learn React, check out the [React documentation](https://reactjs.org/).
+
+### Code Splitting
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
+
+### Analyzing the Bundle Size
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
+
+### Making a Progressive Web App
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
+
+### Advanced Configuration
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
+
+### Deployment
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
+
+### `npm run build` fails to minify
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

File diff suppressed because it is too large
+ 28088 - 0
02/package-lock.json


+ 38 - 0
02/package.json

@@ -0,0 +1,38 @@
+{
+  "name": "02",
+  "version": "0.1.0",
+  "private": true,
+  "dependencies": {
+    "@testing-library/jest-dom": "^5.16.4",
+    "@testing-library/react": "^13.3.0",
+    "@testing-library/user-event": "^13.5.0",
+    "react": "^18.1.0",
+    "react-dom": "^18.1.0",
+    "react-scripts": "5.0.1",
+    "web-vitals": "^2.1.4"
+  },
+  "scripts": {
+    "start": "react-scripts start",
+    "build": "react-scripts build",
+    "test": "react-scripts test",
+    "eject": "react-scripts eject"
+  },
+  "eslintConfig": {
+    "extends": [
+      "react-app",
+      "react-app/jest"
+    ]
+  },
+  "browserslist": {
+    "production": [
+      ">0.2%",
+      "not dead",
+      "not op_mini all"
+    ],
+    "development": [
+      "last 1 chrome version",
+      "last 1 firefox version",
+      "last 1 safari version"
+    ]
+  }
+}

BIN
02/public/favicon.ico


+ 43 - 0
02/public/index.html

@@ -0,0 +1,43 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8" />
+    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
+    <meta name="viewport" content="width=device-width, initial-scale=1" />
+    <meta name="theme-color" content="#000000" />
+    <meta
+      name="description"
+      content="Web site created using create-react-app"
+    />
+    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
+    <!--
+      manifest.json provides metadata used when your web app is installed on a
+      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
+    -->
+    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
+    <!--
+      Notice the use of %PUBLIC_URL% in the tags above.
+      It will be replaced with the URL of the `public` folder during the build.
+      Only files inside the `public` folder can be referenced from the HTML.
+
+      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
+      work correctly both with client-side routing and a non-root public URL.
+      Learn how to configure a non-root public URL by running `npm run build`.
+    -->
+    <title>React App</title>
+  </head>
+  <body>
+    <noscript>You need to enable JavaScript to run this app.</noscript>
+    <div id="root"></div>
+    <!--
+      This HTML file is a template.
+      If you open it directly in the browser, you will see an empty page.
+
+      You can add webfonts, meta tags, or analytics to this file.
+      The build step will place the bundled scripts into the <body> tag.
+
+      To begin the development, run `npm start` or `yarn start`.
+      To create a production bundle, use `npm run build` or `yarn build`.
+    -->
+  </body>
+</html>

BIN
02/public/logo192.png


BIN
02/public/logo512.png


+ 25 - 0
02/public/manifest.json

@@ -0,0 +1,25 @@
+{
+  "short_name": "React App",
+  "name": "Create React App Sample",
+  "icons": [
+    {
+      "src": "favicon.ico",
+      "sizes": "64x64 32x32 24x24 16x16",
+      "type": "image/x-icon"
+    },
+    {
+      "src": "logo192.png",
+      "type": "image/png",
+      "sizes": "192x192"
+    },
+    {
+      "src": "logo512.png",
+      "type": "image/png",
+      "sizes": "512x512"
+    }
+  ],
+  "start_url": ".",
+  "display": "standalone",
+  "theme_color": "#000000",
+  "background_color": "#ffffff"
+}

+ 3 - 0
02/public/robots.txt

@@ -0,0 +1,3 @@
+# https://www.robotstxt.org/robotstxt.html
+User-agent: *
+Disallow:

+ 38 - 0
02/src/App.css

@@ -0,0 +1,38 @@
+.App {
+  text-align: center;
+}
+
+.App-logo {
+  height: 40vmin;
+  pointer-events: none;
+}
+
+@media (prefers-reduced-motion: no-preference) {
+  .App-logo {
+    animation: App-logo-spin infinite 20s linear;
+  }
+}
+
+.App-header {
+  background-color: #282c34;
+  min-height: 100vh;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+  font-size: calc(10px + 2vmin);
+  color: white;
+}
+
+.App-link {
+  color: #61dafb;
+}
+
+@keyframes App-logo-spin {
+  from {
+    transform: rotate(0deg);
+  }
+  to {
+    transform: rotate(360deg);
+  }
+}

+ 333 - 0
02/src/App.js

@@ -0,0 +1,333 @@
+
+function App() {
+
+  // Сформируйте объект с массивами и массив с объектами с осмысленными данными.
+
+  var MarketShelf = {
+    Candies: ['red', 'green', 'blue'],
+    Cookies: ['chocolate', 'raisin', 'cream'],
+    Soda: ['Pepsi', 'Fanta', 'Sprite']
+  }
+
+  var Collegues = [
+    { name: 'Sasha', age: '35', occupation: 'PM' },
+    { name: 'Slava', age: '20', occupation: 'Front End Developer' },
+    { name: 'Bohdan', age: '40', occupation: 'Back End Developer' }
+  ]
+
+  // Добавьте условие отрицательного возраста в пример выше.
+  // Расставьте недостающие(но синтаксически необязательные) фигурные скобки.
+
+
+  var age = +prompt("Сколько вам лет?", "");
+
+  if (age < 0) {
+    alert("ты вообще жив?");
+  }
+  else {
+    if (age < 18) {
+      alert("школьник");
+    }
+    else {
+      if (age > 18 && age < 30) {
+        alert("молодежь");
+      }
+      else {
+        if (age > 30 && age < 45) {
+          alert("зрелость");
+        }
+        else {
+          if (age > 45 && age < 60) {
+            alert("закат");
+          }
+          else {
+            if (age > 60) {
+              alert("как пенсия?");
+            }
+            else {
+              alert("то ли киборг, то ли ошибка");
+            }
+          }
+        }
+      }
+    }
+  }
+
+  // Перепишите пример выше, используя if-else
+
+  var color = prompt("Введите цвет", "");
+
+  if (color == 'red') {
+    document.write("<div style='background-color: red;'>красный</div>");
+  }
+  else if (color == "black") {
+    document.write("<div style='background-color: black; color: white;'>черный</div>");
+  }
+  else if (color == "blue") {
+    document.write("<div style='background-color: blue;'>синий</div>");
+  }
+  else if (color == "green") {
+    document.write("<div style='background-color: green;'>зеленый</div>");
+  }
+  else {
+    document.write("<div style='background-color: gray;'>Я не понял</div>");
+  }
+
+  // Напишите бессмысленное выражение, используя максимум усвоенных на текущий момент знаний.
+
+  /*
+  do {
+    var a = [a, b, c, d, e];
+    if (someVariable != 1 || otherVariable === 12) {
+      alert('alert1');
+    }
+    else if ([a] != 5) {
+      var j = 7 ? seven : notSeven;
+    }
+    else {
+      switch (nthVariable) {
+        case 1: alert('Glory to Ukraine');
+          break;
+        case 2: alert('Glory to Heroes!');
+          break;
+        default: alert('Death to Enemies!');
+      }
+    }
+  }
+  while (a <= 7 && b !== 3, 14)
+  */
+
+  // assign: evaluation
+
+  // Исследуйте код, найдите выражения в нём. 
+  // Расставьте скобки так, что бы код не изменил своего поведения (работал так же как и сейчас). 
+  // Объясните как и в каком порядке вычисляются выражения и подвыражения.
+
+  var a = (5); //5 - выражение
+  var b, c;
+  b = ((a) * 5); // выражение
+  b = (c = (b / 2)); // выражение
+
+  // 1. Сначала объявляется переменная а, ей присваевается значение 5.
+  // 2. Затем объявляются переменные b и c.
+  // 3. Переменная b высчитывается на третьей строчке кода и ей присваевавается вычисленное значение.
+  // 4. На четвёртой строчке кода в переменной b вычисляется переменная c, исполльзуя значение раннее вычесленной переменной b.
+  // 5. В переменную b присваевается значение переменной c и выводится в консоли.
+
+  // semicolon: error
+
+  // Сделайте несколько примеров кода, отсутствие ; в которых приводит к синтаксической ошибке
+
+  /*
+  var a = 6 var b = 14;
+  prompt('message') alert('warning');
+  */
+
+  // semicolon: mistake
+
+  // Сделайте несколько примеров кода, наличиe или отсутствие ; в которых приводит к логической ошибке 
+  // (т. е. код выполняется без синтаксических ошибок, но делает не то, что задумано)
+
+
+
+  // Number: age
+
+  // С помощью prompt спросить у пользователя его возраст и подсчитать год рождения. Год рождения вывести с помощью alert.
+
+  var age = +prompt('Сколько вам сейчас лет?');
+  var YearOfBirth = 2022 - age;
+  alert('Ваш год рождения: ' + YearOfBirth);
+
+  // Number: temperature
+
+  // С помощью prompt спросить у пользователя температуру в градусах Цельсия и перевести их в Фаренгейты и/или наоборот.
+
+  var DegCelcium = prompt('Введите температуру по шкале Цельсия:');
+  var DegFahrenheit = (DegCelcium * 1.8) + 32;
+  alert('Температура по шкале Фаренгейта равна: ' + DegFahrenheit);
+
+  // Number: divide
+
+  // Сделайте калькулятор для расчета деления нацело двух чисел. Используйте Math.floor или альтернативы.
+
+  var a = prompt('Enter the first number: ');
+  var b = prompt('Enter the second number: ');
+  alert('Result:' + Math.floor(a / b));
+
+  // Number: odd
+
+  // С помощью prompt узнайте число, введенное пользователем. С помощью if проверьте что число корректно преобразовано из строки. 
+  // В случае ошибки выведите сообщение. Выведите четное число или нет, используя if.
+
+  var Number = +prompt('Введите число: ');
+  if (isNaN(Number)) {
+    alert('Введенное значение не является числом!');
+  }
+  else {
+    if (Number % 2 === 0) {
+      alert('Число чётное.');
+    }
+    else {
+      alert('Число нечётное.');
+    }
+  }
+
+  // String: greeting
+
+  // Спросите у пользователя имя, и поприветствуйте его с помощью alert.
+
+  var Name = prompt('What is your name, stranger?');
+  alert('May the Force be with you, ' + Name + '!');
+
+  // String: lexics
+
+  // Спросите у пользователя текст, и проверьте его на наличие некорректного слова или нескольких некорректных слов. 
+  // Используйте метод indexOf (или includes) строки.
+
+  var SampleText = prompt('Enter some text...');
+  if (SampleText.includes('fuck')) {
+    alert('Hey, that is way too rude!');
+  }
+  else {
+    alert('Okay, that is kinda interesting.')
+  }
+
+  // confirm
+
+  // Поэкспериментируйте с confirm, определите тип данных, который он возвращает, и конкретные значения этого типа данных.
+
+  console.log(typeof window.confirm()) // 'funciton', возвращает true или false
+
+  // Boolean
+
+  // Напишите код, который спрашивает те или иные вопросы с ответом "да"/"нет" с помощью confirm, и сохраняет ответы в переменных.
+
+  var question = window.confirm('Are you a human?')
+  console.log(question);
+
+  // Boolean: if
+
+  // Расширьте предыдущее задание условиями по полученным переменным условиями (if else). 
+  // Например, если вы спрашиваете пол пользователя с помощью confirm, то по условию сделайте alert("Вы женщина") и alert("Вы мужчина").
+
+  var sex = window.confirm('Are you a dishwasher?')
+  if (sex == true) {
+    alert("Вы женщина");
+  }
+  else {
+    alert("Вы мужчина");
+  }
+
+  // Array: real
+
+  // Понаходите в вашей жизни вещи, которые похожи на массивы, и другие вещи, которые можно смоделировать с помощью массивов.
+
+  var documents = ['ID card', 'Driver license', 'Military ID'];
+  var classMates = ['Vasya', 'Danya', 'Kostya'];
+  var pencilBox = ['red', 'green', 'blue', 'cyan', 'magnetta', 'yellow', 'black'];
+
+  // Array: booleans
+
+  // Создайте массив с переменными из заданий Boolean и Boolean if.
+
+  var Boolean = [question];
+  var BooleanIf = [sex];
+
+  // Array: plus
+
+  // Напишите код, который складывает первые два элемента массива и заносит это в элемент с индексом 2. Исследуйте полученный массив.
+
+  var arr = [1, 2];
+  arr[2] = arr[0] + arr[1];
+  console.log(arr);
+
+  // Array: plus string
+
+  // Что будет, если в предыдущий примере использовать строки вместо чисел? 
+  // Сделайте версию для сложения 3х значений. Подумайте, зачем нужна эта возможность в наших примерах.
+
+  var arr = ['hi ', 'hello ', 'how do you do'];
+  arr[3] = arr[0] + arr[1] + arr[2];
+  console.log(arr);
+
+  // Object: real
+
+  // Найдите те или иные реальные объекты и найдите их свойства. 
+  // Например у маркера это цвет, толщина, уровень зарядки (количество краски), 
+  // у автомобиля - бренд, модель, мощность двигателя, цвет и так далее. Создайте объекты с помощью {}. 
+  // В качестве образца посмотрите объект персоны из материала предыдущего занятия
+
+  var Mercedes = {
+    model: 'AMG GT Coupe',
+    color: 'gray',
+    year: '2022',
+    volume: '4,0 l',
+    power: '522 HP',
+  }
+
+  // Object: change
+
+  // Поменяйте значения свойств в ваших объектах, используя [] и . и присвоения.
+
+  Mercedes['model'] = 'G63';
+  Mercedes.power = '577 HP';
+
+  // Comparison: sizes
+
+  // Сделайте перевод перевод из нашей системы размеров в американскую или любую на выбор. 
+  // Используйте prompt, условия сравнения и alert.
+
+  var clothesSize = +prompt('Введите размер одежды по украинским меркам:');
+  if (clothesSize >= 40 && clothesSize < 42) {
+    alert('S');
+  }
+  else if (clothesSize >= 42 && clothesSize < 46) {
+    alert('M');
+  }
+  else if (clothesSize >= 46 && clothesSize < 50) {
+    alert('L');
+  }
+  else if (clothesSize >= 50 && clothesSize < 54) {
+    alert('XL');
+  }
+  else if (clothesSize == 54) {
+    alert('XXL');
+  }
+  else {
+    alert('Тут что-то не так...')
+  }
+
+  // Comparison: object
+
+  // Подумайте о том, как можно применить объекты к предыдущем заданию.
+
+  var Size = {
+    S: [40, 41],
+    M: [42, 43, 44, 45],
+    L: [46, 47, 48, 49],
+    XL: [50, 51, 52, 53],
+    XXL: [54],
+  }
+
+  // Ternary
+
+  // Спросите у пользователя пол (confirm). Выведите с помощью alert "Вы мужчина" или "Вы женщина". 
+  // Сделайте это оператором alert. Используйте тернарный оператор.
+
+  var sex = window.confirm('Are you a dishwasher?') ? alert("Вы женщина") : alert("Вы мужчина");
+
+  // Синий пояс Number: flats
+
+  // Сделайте калькулятор, который позволит вам исходя из информации о количества 
+  // этажей в доме и количества квартир на этаже находить подъезд и этаж определенной квартиры по её номеру. 
+  // Например для 9-этажного дома по 4 квартиры на этаж 81 квартира находится на 3м этаже третьего подъезда.
+
+  var FloorNumber = prompt('Enter the number of floors:');
+  var FlatsPerFloor = prompt('How many flats are on the one floor?');
+  var FlatNumber = prompt('Enter the flat number:');
+  var Section = Math.floor((FlatNumber - 1) / (FloorNumber * FlatsPerFloor) + 1);
+  var Floor = Math.floor(((FlatNumber - (Section - 1) * FloorNumber * FlatsPerFloor) - 1) / FlatsPerFloor + 1);
+  alert('Your flat is on the ' + (Section) + ' section on the ' + (Floor) + ' floor.');
+}
+
+export default App;

+ 8 - 0
02/src/App.test.js

@@ -0,0 +1,8 @@
+import { render, screen } from '@testing-library/react';
+import App from './App';
+
+test('renders learn react link', () => {
+  render(<App />);
+  const linkElement = screen.getByText(/learn react/i);
+  expect(linkElement).toBeInTheDocument();
+});

+ 13 - 0
02/src/index.css

@@ -0,0 +1,13 @@
+body {
+  margin: 0;
+  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
+    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
+    sans-serif;
+  -webkit-font-smoothing: antialiased;
+  -moz-osx-font-smoothing: grayscale;
+}
+
+code {
+  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
+    monospace;
+}

+ 17 - 0
02/src/index.js

@@ -0,0 +1,17 @@
+import React from 'react';
+import ReactDOM from 'react-dom/client';
+import './index.css';
+import App from './App';
+import reportWebVitals from './reportWebVitals';
+
+const root = ReactDOM.createRoot(document.getElementById('root'));
+root.render(
+  <React.StrictMode>
+    <App />
+  </React.StrictMode>
+);
+
+// If you want to start measuring performance in your app, pass a function
+// to log results (for example: reportWebVitals(console.log))
+// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
+reportWebVitals();

File diff suppressed because it is too large
+ 1 - 0
02/src/logo.svg


+ 13 - 0
02/src/reportWebVitals.js

@@ -0,0 +1,13 @@
+const reportWebVitals = onPerfEntry => {
+  if (onPerfEntry && onPerfEntry instanceof Function) {
+    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
+      getCLS(onPerfEntry);
+      getFID(onPerfEntry);
+      getFCP(onPerfEntry);
+      getLCP(onPerfEntry);
+      getTTFB(onPerfEntry);
+    });
+  }
+};
+
+export default reportWebVitals;

+ 5 - 0
02/src/setupTests.js

@@ -0,0 +1,5 @@
+// jest-dom adds custom jest matchers for asserting on DOM nodes.
+// allows you to do things like:
+// expect(element).toHaveTextContent(/react/i)
+// learn more: https://github.com/testing-library/jest-dom
+import '@testing-library/jest-dom';