Browse Source

HW 4 done

suslov-dmytro 1 year ago
parent
commit
6d95592dc0

+ 23 - 0
04/.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
04/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
+ 28364 - 0
04/package-lock.json


+ 38 - 0
04/package.json

@@ -0,0 +1,38 @@
+{
+  "name": "04",
+  "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.2.0",
+    "react-dom": "^18.2.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
04/public/favicon.ico


+ 43 - 0
04/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
04/public/logo192.png


BIN
04/public/logo512.png


+ 25 - 0
04/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
04/public/robots.txt

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

+ 38 - 0
04/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);
+  }
+}

+ 384 - 0
04/src/App.js

@@ -0,0 +1,384 @@
+/* <body>
+        <div>
+            <span>Enter a data please:</span><br/>
+            <input type='text' id='name'>
+            <input type='text' id='surname'>
+        </div>
+        <div>
+            <button id='ok'>OK</button>
+            <button id='cancel'>Cancel</button>
+        </div>
+    </body>
+*/
+
+// Сделайте декларативную JSON-структуру для тэгов выше, в которой:
+//   каждый тэг будет объектом
+//   имя тэга будет полем tagName
+//   вложенные тэги будут в поле subTags
+//   текст в тэге будет в поле text
+//   набор аттрибутов тэга будет в поле attrs.
+
+// Выведите значения текста во второй кнопке, используя . и [].
+// Выведите значение атрибута id во втором input, используя . и [].
+
+let body = {
+  tagName: 'body',
+  subTags: {
+    div1: {
+      tagName: 'div',
+      subTags: {
+        span: {
+          tagName: 'span',
+          text: 'Enter a data please:',
+        },
+        br: {
+          tagName: 'br',
+        },
+        input: {
+          tagName: 'input',
+          attrs: {
+            type: 'text',
+            id: 'name',
+          },
+        },
+        input: {
+          tagName: 'input',
+          attrs: {
+            type: 'text',
+            id: 'surname',
+          },
+        },
+      },
+    },
+    div2: {
+      tagName: 'div',
+      subTags: {
+        button: {
+          tagName: 'button',
+          attrs: {
+            id: 'ok',
+          },
+          text: 'OK',
+        },
+        button: {
+          tagName: 'button',
+          attrs: {
+            id: 'cancel',
+          },
+          text: 'Cancel',
+        },
+      },
+    },
+  },
+}
+
+console.log(body.subTags.div2.subTags.button.text);
+console.log(body['subTags']['div2']['subTags']['button']['text']);
+
+console.log(body.subTags.div1.subTags.input.attrs.id);
+console.log(body['subTags']['div1']['subTags']['input']['attrs']['id']);
+
+// P.S. Не уверен, правильно ли менять названия тегов дива на див1 и див2, но так работает)
+
+// declarative fields
+
+// Как известно, элемент массива и объекта может быть любого типа данных JS, т. е. в коде может быть любое выражение, 
+// которое вычисляется в то или иное значение типа данных. 
+// А значит, мы можем применять функции для ввода данных типа confirm или prompt:
+
+// var text = "Enter a number";
+// var arr3 = [+prompt(text), +prompt(text), +prompt(text)]; //вводим числа.
+
+// Организуйте таким способом заполнение полей в объектах:
+
+var notebook = {
+  brand: "HP",
+  type: "440 G4",
+  model: "Y7Z75EA",
+  ram: 4,
+  size: "14",
+  weight: 1.8,
+  resolution: {
+    width: 1920,
+    height: 1080,
+  },
+};
+
+var phone = {
+  brand: "meizu",
+  model: "m2",
+  ram: 2,
+  color: "black",
+};
+
+var person = {
+  name: "Donald",
+  surname: "Trump",
+  married: true,
+}
+
+// Например:
+
+// var person = {
+//   name: prompt("Enter a name"),
+//   surname: prompt("Enter a surname"),
+// }
+
+// Используйте приведение к числу, prompt и confirm в зависимости от типов данных.
+
+var notebook = {
+  brand: prompt('Enter the laptop brand:'),
+  type: prompt('Enter the type of laptop:'),
+  model: prompt('Enter the model of the laptop:'),
+  ram: +prompt('Enter the value of RAM:'),
+  size: prompt('Enter the size of screen of laptop:'),
+  weight: +prompt('Enter the weight of laptop:'),
+  resolution: {
+    width: +prompt('Enter the width of the screen:'),
+    height: +prompt('Enter the height of the screen:'),
+  },
+};
+
+var phone = {
+  brand: prompt('Enter the cell phone brand:'),
+  model: prompt('Enter the cell phone model:'),
+  ram: +prompt('Enter the value of ram:'),
+  color: prompt('Enter the color of the cell phone: '),
+};
+
+var person = {
+  name: prompt('Enter the name of the person:'),
+  surname: prompt('Enter the surname of the person:'),
+  married: window.confirm('Is the person married?'),
+}
+
+// object links
+
+// Добавьте персоне гаджеты, используя новые поля smartphone и laptop в объекте персоны
+// Добавьте владельца в гаджеты, используя новое поле owner в объектах телефона и ноутбука.
+// обратите внимание на цикличность ссылок в объектах, если вы все сделали правильно, то
+
+// person.smartphone.owner.laptop.owner.smartphone == person.smartphone
+
+var notebook = {
+  brand: prompt('Enter the laptop brand:'),
+  type: prompt('Enter the type of laptop:'),
+  model: prompt('Enter the model of the laptop:'),
+  ram: +prompt('Enter the value of RAM:'),
+  size: prompt('Enter the size of screen of laptop:'),
+  weight: +prompt('Enter the weight of laptop:'),
+  resolution: {
+    width: +prompt('Enter the width of the screen:'),
+    height: +prompt('Enter the height of the screen:'),
+  },
+};
+
+var phone = {
+  brand: prompt('Enter the cell phone brand:'),
+  model: prompt('Enter the cell phone model:'),
+  ram: +prompt('Enter the value of ram:'),
+  color: prompt('Enter the color of the cell phone: '),
+};
+
+var person = {
+  name: prompt('Enter the name of the person:'),
+  surname: prompt('Enter the surname of the person:'),
+  married: window.confirm('Is the person married?'),
+}
+
+notebook.owner = person,
+  phone.owner = person,
+  person.smartphone = phone,
+  person.laptop = notebook,
+
+  alert(person.smartphone.owner.laptop.owner.smartphone == person.smartphone);
+
+// imperative array fill 3
+
+// Создайте пустой массив и добавьте в него три элемента, введенные пользователем (prompt), 
+// используя императивный подход (несколько операторов подряд)
+
+var arr = []
+arr[0] = prompt('Enter the element #1:');
+arr[1] = prompt('Enter the element #2:');
+arr[2] = prompt('Enter the element #3:');
+console.log(arr);
+
+// while confirm
+
+// Сделайте цикл с confirm, который продолжается по Отмена и заканчивается по ОК.
+
+var fact = false;
+while (fact == false) {
+  fact = window.confirm('putin lox?');
+}
+
+// array fill
+
+// Создайте пустой массив и добавляйте в него элементы, пока пользователь не нажмет Отмена в очередном prompt. 
+// Используйте push для удобства: push
+
+var arr = [];
+var add = '';
+while (add != null) {
+  add = prompt('Write anything here...');
+  arr.push(add);
+}
+console.log(arr);
+
+// array fill nopush
+
+// Сделайте предыдущее задание, не используя push, а обращаясь к элементам по индексу.
+
+var arr = [];
+var add = '';
+while (add != null) {
+  add = prompt('Write anything here...');
+  arr[arr.length] = add;
+}
+console.log(arr);
+
+// infinite probability
+
+// Создайте бесконечный цикл, который прерывается с помощью конструкции break, когда Math.random() > 0.9. 
+// Код должен подсчитывать количество итераций и вывести это число с помощью alert.
+
+var counter = 0;
+while (Math.random() < 0.9) {
+  counter++;
+  if (Math.random() > 0.9) {
+    break;
+  }
+}
+alert(counter);
+
+// empty loop
+
+// Сделайте цикл с prompt, который прерывается по нажатию OK и продолжается по нажатию "Отмена" c пустым телом цикла.
+
+for (var god = prompt('Do you believe in god?'); god == null; god = prompt('Do you believe in god?')) { }
+
+// progression sum
+
+// Подсчитать сумму арифметической прогрессии от 1 до N c шагом 3 (1,4,7....) используя цикл for.
+
+var sum;
+for (let i = 1, j = i + 3, n = +prompt('Enter the N:'); j < n; i = i + 3, j = i + 3, sum = i + j) { }
+alert(sum);
+
+// chess one line
+
+// Сформировать строку " # # # # # " с помощью цикла for. Длина строки может быть четной и нечетной, и указывается в одном месте в коде.
+
+var str;
+for (str = [''], n = +prompt('Enter the length of the string:'); str.length < (n / 2); str.push('#')) { }
+console.log(str.join(' '))
+
+// numbers
+
+// Сформировать строку c помощью вложенных циклов. Для перевода строки используйте \n.
+
+var arr1 = [];
+var arr2 = [0]
+for (let m = 0; m < 10; m++) {
+  for (arr2, n = 0; arr2.length < 10; arr2.push(n + 1), n++) { }
+  arr1 += ((arr2.join('')) + '\n');
+}
+console.log(arr1)
+
+// chess
+
+// Сформируйте строку с шахматной доской из вложенных циклов. Для перевода строки используйте \n. Код должен поддерживать легкое изменение размеров доски.
+
+// .#.#.#.#.#.#
+// #.#.#.#.#.#.
+// .#.#.#.#.#.#
+// #.#.#.#.#.#.
+// .#.#.#.#.#.#
+// #.#.#.#.#.#.
+// .#.#.#.#.#.#
+// #.#.#.#.#.#.
+// .#.#.#.#.#.#
+// #.#.#.#.#.#.
+
+var chessBoard = "";
+let rows = +prompt('Enter the amount of rows:');
+let cols = +prompt('Enter the amount of columns:');
+for (var j = 1; j <= cols; j += 1) {
+  if (j % 2 != 0) {
+    for (var i = 1; i <= rows; i += 1) {
+      if ((i % (cols + 1)) == 0) {
+        chessBoard += "\n";
+      } else if (i % 2 != 0) {
+        chessBoard += "#";
+      } else {
+        chessBoard += ".";
+      }
+    }
+    chessBoard += "\n";
+  }
+  else {
+    for (var i = 1; i <= rows; i += 1) {
+      if ((i % (cols + 1)) == 0) {
+        chessBoard += "\n";
+      } else if (i % 2 != 0) {
+        chessBoard += ".";
+      } else {
+        chessBoard += "#";
+      }
+    }
+    chessBoard += "\n";
+  }
+}
+console.log(chessBoard);
+
+// cubes
+
+// Сформируйте массив из N элементов, содержащий в себе кубы индексов, т. е:
+
+// [0,1,8,27,64...]
+
+var cubes = [];
+var n = prompt('Enter the amount of items:')
+for (i = 0; i < n; i++) {
+  cubes.push(Math.pow(i, 3));
+}
+console.log(cubes);
+
+// multiply table
+
+// C помощью вложенного цикла сформируйте массив массивов "таблица умножения". Для инициализации вложенных массивов используйте
+
+// arr[i] = [] //в i-тый элемент массива заносится новый пустой массив
+// arr[5][6] должен быть равен, соответственно, 30, arr[7][2] == 14 и так далее.
+
+var m = [];
+for (var i = 0; i < 10; i++) {
+  var n = [];
+  for (var j = 0; j < 10; j++) {
+    n.push(j * i);
+  }
+  m.push(n);
+}
+console.log(m[1][1]);
+
+// matrix to html table
+
+// Сделайте вложенный цикл, который формирует HTML-таблицу в переменной строкового типа из любого двумерного массива. 
+// Т. е. если в нём использовать результат работы предыдущего задания, то получится таблица умножения в HTML
+
+var table = "<table border='1'>";
+var m = [];
+for (var i = 0; i < 10; i++) {
+  var n = [];
+  table += `<tr>`;
+  for (var j = 0; j < 10; j++) {
+    n.push(j * i);
+    table += `<td>${i}*${j}=${i*j}</td>`;
+  }
+  table += `</tr>`
+  m.push(n);
+}
+table += "</table>";
+
+document.write(table);

+ 8 - 0
04/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
04/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
04/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
04/src/logo.svg


+ 13 - 0
04/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
04/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';