'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));