Kaynağa Gözat

done homework 7 Omelchienko Hryhorii

unknown 2 yıl önce
ebeveyn
işleme
969648deca
4 değiştirilmiş dosya ile 389 ekleme ve 1 silme
  1. 47 0
      html-css/css/style.css
  2. 18 1
      html-css/index.html
  3. 205 0
      javascript/hw.js
  4. 119 0
      javascript/someTree.js

+ 47 - 0
html-css/css/style.css

@@ -8,3 +8,50 @@ html {
   box-sizing: inherit;
 }
 
+td {
+  width: 20px;
+  background-color: grey;
+  text-align: center;
+}
+
+table {
+  padding: 10px;
+  background-color: rgb(211, 208, 208);
+}
+input {
+  margin-right: 10px;
+}
+
+.calc{
+  display: flex;
+  justify-content: center;
+}
+
+#result{
+  text-align: center;
+  color: aqua;
+  font-size: 20px;
+}
+
+.greetings ,.introduction {
+  display: flex;
+  justify-content: center;
+  height: auto;
+  margin-bottom: 5px;
+  background-color: grey;
+}
+
+.greetings__p , .introduction__p{
+  color: green;
+  margin: 0;
+  margin-right: 5px;
+  font-size: 15px;
+}
+
+.greetings__span ,.introduction__span{
+  color: rgb(255, 161, 10);
+  margin: 0;
+  margin-right: 5px;
+  font-size: 15px;
+}
+

+ 18 - 1
html-css/index.html

@@ -7,6 +7,23 @@
 		<title>Homework</title>
 		<link rel="stylesheet" href="./css/style.css" />
 	</head>
-	<body> </body>
+	<body>
+		<div class="calc">
+			<input
+				id="first"
+				type="number"
+				class="input"
+				placeholder="Write number into calc"
+			/>
+			<input
+				id="second"
+				type="number"
+				class="input"
+				placeholder="Write number into calc"
+			/>
+			<button type="button" id="submitCalc">Calc</button>
+		</div>
+		<p id="result"></p>
+	</body>
 	<script src="../javascript/hw.js" type="module"></script>
 </html>

+ 205 - 0
javascript/hw.js

@@ -1 +1,206 @@
 'use strict';
+import htmlObj from './someTree.js';
+
+//Домашнее задание. Функции 2, ES6
+//Переделайте предыдущее ДЗ используя максимум возможностей ES6. Отметьте облегчение (или утяжеление) синтаксиса.
+// Easier: used loop forEach on row 34 ,and arrow function on row 60
+// Harder : We cant totally replace simple loop from ES5 because it's not suit to use ES6 for already counted iterations
+
+const table = document.createElement('table');
+for (let i = 0; i < 10; i++) {
+	const tr = document.createElement('tr');
+	for (let j = 1; j < 11; j++) {
+		const td = document.createElement('td');
+		td.id = String(i) + String(j);
+		td.dataset.col = String(i);
+		if (j === 10) {
+			td.textContent = String(i);
+			tr.prepend(td);
+			continue;
+		}
+		td.textContent = String((i === 0 ? 1 : i) * j);
+		tr.append(td);
+	}
+	table.append(tr);
+}
+
+document.body.append(table);
+
+table.onmouseover = function ({
+	target: {
+		cellIndex,
+		tagName,
+		id,
+		dataset: { col },
+	},
+}) {
+	this.childNodes.forEach((element) => {
+		element.childNodes.forEach((td) => {
+			if (td.cellIndex === cellIndex) {
+				td.style.backgroundColor = 'yellow';
+			} else if (td.dataset.col === col) {
+				td.style.backgroundColor = 'orange';
+			} else {
+				td.style.backgroundColor = 'grey';
+			}
+		});
+	});
+	if (tagName === 'TD')
+		document.getElementById(id).style.backgroundColor = 'green';
+};
+
+//Calc
+const btnSubmit = document.getElementById('submitCalc');
+const resultP = document.getElementById('result');
+
+btnSubmit.addEventListener('click', updateValue);
+function updateValue(e) {
+	const values = e.target.parentNode.children;
+	resultP.textContent = String(+values[0].value * +values[1].value);
+}
+//Calc Live
+const firstInput = document.getElementById('first');
+const secondInput = document.getElementById('second');
+const handelInputs = (e, inputValue) => {
+	resultP.textContent = String(+e.target.value * +inputValue.value);
+};
+firstInput.addEventListener('change', (e) => handelInputs(e, secondInput));
+secondInput.addEventListener('change', (e) => handelInputs(e, firstInput));
+
+//sort
+//Сделайте обобщенную функцию сортировки массива
+//Функция позволяет отсортировать любой набор данных по имени поля (второй параметр).
+//Третьим параметром идет необязательный Boolean, который в случае true делает сортировку по
+//возрастанию, в случае false - по убыванию.По умолчанию(без третьего параметра) происходит сортировка по возрастанию.
+const persons = [
+	{ name: 'Canvas', age: 17 },
+	{ name: 'Bogdan', age: 35 },
+	{ name: 'Anton', age: 73 },
+	{ name: 'Dango', age: 120 },
+];
+
+const sort = (arr, sortBy, flag = true) => {
+	const sorted = [
+		...arr.sort(function (a, b) {
+			if (a[sortBy] < b[sortBy]) {
+				return -1;
+			} else if (a[sortBy] > b[sortBy]) {
+				return 1;
+			}
+			return 0;
+		}),
+	];
+	return flag ? sorted : sorted.reverse();
+};
+
+console.log(sort(persons, 'age')); //sort increase by age
+console.log(sort(persons, 'age', false)); //decrease sort increase by age
+console.log(sort(persons, 'name')); //sort increase by name
+console.log(sort(persons, 'name', false)); //decrease sort increase by name
+
+//array map
+//Используя Array.map приведите все строки в массиве к числу. Элементы других типов оставьте как есть:
+//должно превратиться в
+//[1, {}, null, undefined, 500, 700]
+
+const arrValues = ['1', {}, null, undefined, '500', 700];
+const rightArray = arrValues.map((el) => {
+	console.log(isNaN(el));
+	if (typeof el === 'string') return Number(el);
+	return el;
+});
+console.log(rightArray);
+
+//array reduce
+//Получите произведение всех чисел в массиве, используя Array.reduce. Не обрабатывайте типы данных, не являющиеся числом.
+//результат должен быть 15
+
+const arrForReduce = ['0', 5, 3, 'string', null];
+const amountOfNumbers = arrForReduce.reduce((acc, el) => {
+	if (typeof el === 'number') return (acc *= el);
+	return acc;
+}, 1);
+console.log(amountOfNumbers);
+
+//object filter
+//Напишите свою реализацию Array.filter для объектов:
+//должно вернуть
+// {
+//     ram: 2,
+//     color: "black",
+// }
+//Для удаления пары ключ-значение используйте delete. Или сделайте копию объекта.
+
+const phone = {
+	brand: 'meizu',
+	model: 'm2',
+	ram: 2,
+	color: 'black',
+};
+
+function objectFilter(arr, f) {
+	const result = {};
+	for (const [key, value] of Object.entries(arr)) {
+		if (f(key, value)) result[key] = value;
+	}
+	return result;
+}
+
+console.log(
+	objectFilter(phone, (key, value) => key === 'color' || value === 2)
+);
+
+//object map
+//Напишите свою реализацию Array.map для объектов:
+// map({name: "Иван", age: 17},function(key,value){
+// var result = {};
+// result[key+"_"] = value + "$";
+// return result;
+// }) //должен вернуть {name_: "Иван$", age_: "17$"}
+//"Напишите свою реализацию" значит написать function map.... и её тело, после чего код выше заработает
+
+const mapObjects = (obj, cb) => {
+	const result = {};
+	for (const key in obj) {
+		if (cb(key, obj[key])) result[key + '_'] = obj[key] + '$';
+	}
+	return result;
+};
+const object = { name: 'Hryhorii', age: 24 };
+console.log(
+	mapObjects(object, (key, value) => (key === 'name') | (value === 'Hryhorii'))
+);
+
+//Рекурсия
+//Sum
+//Напишите функцию, который будет считать сумму арифметической прогрессии рекурсивно.
+
+const sumRecursion = (n) => {
+	if (n === 1) return 1;
+	return n + sumRecursion(n - 1);
+};
+
+console.log(sumRecursion(5)); // recursion
+
+//HTML Tree
+//Сделать задание на синий пояс, используя рекурсию, без ограничения вложенности.
+
+const htmlConstructor = (htmlObj, previousHtml) => {
+	if (htmlObj.children === undefined) return previousHtml;
+	if (previousHtml === undefined) {
+		return htmlConstructor(htmlObj, document.createElement(htmlObj.tagName));
+	}
+	htmlObj.children.forEach((innerObj, i) => {
+		const { tagName, text, attrs } = innerObj;
+		const tag = document.createElement(tagName);
+		tag.textContent = text;
+		for (const atr in attrs) {
+			tag.setAttribute(atr, attrs[atr]);
+		}
+		previousHtml.append(tag);
+		return htmlConstructor(innerObj, previousHtml.children[i]);
+	});
+	return previousHtml;
+};
+
+document.body.prepend(htmlConstructor(htmlObj));

+ 119 - 0
javascript/someTree.js

@@ -0,0 +1,119 @@
+export default {
+	tagName: 'main',
+	children: [
+		{
+			tagName: 'section',
+			children: [
+				{
+					tagName: 'div',
+					children: [
+						{
+							tagName: 'p',
+							text: 'Hello',
+							attrs: {
+								class: 'greetings__p',
+							},
+						},
+						{
+							tagName: 'p',
+							text: 'my',
+							attrs: {
+								class: 'greetings__p',
+							},
+						},
+						{
+							tagName: 'p',
+							text: 'dear friends',
+							attrs: {
+								class: 'greetings__p',
+							},
+						},
+					],
+					text: '',
+					attrs: {
+						class: 'greetings',
+					},
+				},
+				{
+					tagName: 'div',
+					children: [
+						{
+							tagName: 'span',
+							text: 'We are',
+							attrs: {
+								class: 'greetings__span',
+							},
+						},
+						{
+							tagName: 'span',
+							text: 'glad to see you',
+							attrs: {
+								class: 'greetings__span',
+							},
+						},
+						{
+							tagName: 'span',
+							text: 'Here!',
+							attrs: {
+								class: 'greetings__span',
+							},
+						},
+					],
+					text: '',
+					attrs: {
+						class: 'greetings',
+					},
+				},
+			],
+			attrs: {},
+		},
+		{
+			tagName: 'section',
+			children: [
+				{
+					tagName: 'div',
+					children: [
+						{
+							tagName: 'p',
+							text: 'You are here to study!',
+							attrs: {
+								class: 'introduction__p',
+							},
+						},
+					],
+					text: '',
+					attrs: {
+						class: 'introduction',
+					},
+				},
+				{
+					tagName: 'div',
+					children: [
+						{
+							tagName: 'span',
+							text: 'And get a lot new information ',
+							attrs: {
+								class: 'introduction__span',
+							},
+						},
+						{
+							tagName: 'span',
+							text: 'with our educationl platform A-level.',
+							attrs: {
+								class: 'introduction__span',
+							},
+						},
+					],
+					text: '',
+					attrs: {
+						class: 'introduction',
+					},
+				},
+			],
+			text: '',
+			attrs: {},
+		},
+	],
+	text: '',
+	attrs: {},
+};