Тестовое задание по Reactjs

PR's Tumblrdome
todays bird
noise dept.

pixel skylines
almost home
cherry valley forever

★
The Stonewall Inn

Kiana Khansmith
Stranger Things

bliss lane

tannertan36
TVSTRANGERTHINGS

oozey mess
Mike Driver
EXPECTATIONS

Andulka
macklin celebrini has autism

seen from Malaysia
seen from United States
seen from Germany
seen from United States

seen from Canada
seen from Colombia

seen from United States

seen from United States

seen from Türkiye
seen from Brazil
seen from Colombia

seen from United States
seen from United States
seen from United States

seen from United Kingdom
seen from United States

seen from United States

seen from United States

seen from United States

seen from United States
@ninachekalina
Тестовое задание по Reactjs

Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
Free to watch • No registration required • HD streaming
Arrow functions
Правильно! Переменные, объявленные с помощью const, имеют неизменяемую привязку, но изменяемое значение.
Правильно! Метод Object.freeze() замораживает объект. Замороженный объект больше нельзя изменить.
TASK 5: Exercise: Refactor the code to use the ES6 String utility methods
// const country = "Bulgaria"; // const city = "Sofia";
// if (country.indexOf("Bulg") > - 1) { // console.log("The country starts with Bulg"); // }
// if (city.indexOf("So") === 0) { // console.log("The name starts with So"); // }
// if (city.lastIndexOf("a") === city.length - 1) { // console.log("The name ends with a"); // }
// console.log( // "The capital of " + country + // " is the city of " + city // );
Исправленный вариант:
// TASK 5: Exercise: Refactor the code to use the ES6 String utility methods const country = "Bulgaria"; const city = "Sofia";
if (country.includes("Bulg")) { console.log("The country starts with Bulg"); } if (city.startsWith("So") ) { console.log("The name starts with So"); }
if (city.endsWith("a")) { console.log("The name ends with a"); }
console.log( `The capital of ${ country}` + `is the city of ${city}` );
// ---------------------------------------------
// TASK 5: Strings and Interpolation const language="English"; console.log(language.includes("g")); console.log(language.startsWith("Eng")); console.log(language.endsWith("Sh")); console.log(language.repeat(3));
console.log(`I speak some languages such as ${language=== "English" ? "British English" : "none"}`)
// TASK 6: Arrow functions
const numbers=[1,2,3,4,5,6] let doubledNumbers=numbers.map( function(number){ return number *2; }
) console.log(doubledNumbers)
Task 7: Exercise
// function Translator() { // this.phrase = "good day"; // this.englishBulgarianDictionary = { // good: "добьр", // day: "день" // } // }
// Translator.prototype.getBulgarianPhrase = function() { // return this.phrase // .split(" ") // .map(function(word) { // return this.englishBulgarianDictionary[word] // }) // .join(" "); // }
// const translator = new Translator(); // console.log(translator.getBulgarianPhrase());
Переделка на Arrow Function
<script> function Translator() { this.phrase = "good day"; this.englishBulgarianDictionary = { good: "добьр", day: "день" } }
Translator.prototype.getBulgarianPhrase = function() { return this.phrase .split(" ") .map((word) =>this.englishBulgarianDictionary[word]) .join(" "); }
const translator = new Translator(); console.log(translator.getBulgarianPhrase()); </script>
<script> const recipe={ name:'Red Lentil Dahl', timeInMinutes:30, ingredients:['red lentils', 'cumin', 'turmeric'] } //const name=recipe.name; //const ingredients=recipe.ingredients; const {name:myName,ingredients:myIngredients}=recipe; console.log(recipe,myName,myIngredients);
const spices=["cardomom", "turmeric","cumin"] const [first,second]=spices; console.log(first,second);
function cook(recipe){ console.log(recipe.name); console.log(recipe.ingredients); } cook(recipe) </script>
деструктуризация
<script>
const ingredients = { tea: 'black', milk: 'soy', sweetener: 'honey', spices: ['ginger', 'cardamom', 'cinnamon', 'nutmeg'] }
// Destructure the parameters function prepareChai(ingredients) { const tea = ingredients.tea; const spices = ingredients.spices; const milk = ingredients.milk; const sweetener = ingredients.sweetener;
console.log("Mix the " + tea + " tea " + "with the " + spices + " in a small pot. " + "Add a cup of water and bring to boil. Boil for 2-3 min. " + "Add " + milk + " milk and " + sweetener + ". " + "Simmer for 3 min. Serve masala chai hot or warm!"); }
prepareChai(ingredients);
</script>
Деструктуризация
<script>
const ingredients = { tea: 'black', milk: 'soy', sweetener: 'honey', spices: ['ginger', 'cardamom', 'cinnamon', 'nutmeg'] }
// Destructure the parameters function prepareChai({tea,spices,milk,sweetener}) {
console.log("Mix the " + tea + " tea " + "with the " + spices + " in a small pot. " + "Add a cup of water and bring to boil. Boil for 2-3 min. " + "Add " + milk + " milk and " + sweetener + ". " + "Simmer for 3 min. Serve masala chai hot or warm!"); }
prepareChai(ingredients);
</script>
<script> const ingredients = { // tea: 'black', milk: 'soy', sweetener: 'honey', spices: ['ginger', 'cardamom', 'cinnamon', 'nutmeg'] }
// Destructure the parameters function prepareChai({tea="regular",spices,milk,sweetener}) {
console.log("Mix the " + tea + " tea " + "with the " + spices + " in a small pot. " + "Add a cup of water and bring to boil. Boil for 2-3 min. " + "Add " + milk + " milk and " + sweetener + ". " + "Simmer for 3 min. Serve masala chai hot or warm!"); }
prepareChai(ingredients); </script>
prepareChai(ingredients); const spices=['cardamom', 'cinnamon', 'nutmeg'] const [spice1]=spices; console.log(spice1)
Возвращение функции из функции
<script> function lifestyle(n){ if (n==1) return function(f,l){return f + l + '<br>';} else if (n==2) return function(f,l){ return f + l+ '<br>';} else if (n==3) return function(f,l) {return document.write(f + l+ '<br>');} return function(){return 'Nina Alexandrovna';}; } let activity=lifestyle(1); document.write(activity('преподаватель' ,'Nina Chekalina')); activity=lifestyle(2); document.write(activity('js developer' ,'street Lesnaja,31 8927345623')); activity=lifestyle(4); document.write(activity('разработчик' ,'Nina Chekalina'));
</script>

Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
Free to watch • No registration required • HD streaming
Функции js в качестве параметра другой функции
<script> function auth(f,l){ return document.write(f + l + '<br>'); }
function adress(f,l){ return document.write(f + l+ '<br>'); }
function activity(f,l,func) { const result = func(f,l); //document.write(result); }
activity('преподаватель' ,'Nina Chekalina',auth); activity('js developer' ,'street Lesnaja,31 8927345623',adress);
</script>
Стрелочные функции
<script> function couch(){ document.write("FirstName: Нина "+ '<br>'); document.write("SecondName: Александровна"+ '<br>'); document.write("LastName: Чекалина"+'<br>'); document.write("Occupation: преподаватель"+'<br>'); document.write("Hobby: programming & walking"+'<br>'); } function greeting(){ document.write("Добрый день. Сейчас - апрель"); }
// передача константе activity ссылки на функцию couch let activity = couch; activity(); activity=greeting;// меняем функцию в переменной greeting activity();
// строим функцию /*const myFunctionName = (name,secondname,lastname) => { return `Hello, ${name} ${secondname} ${lastname} `; } document.write(myFunctionName('Нина','Александровна','Чекалина' + '<br>')); */ //без параметров const myFunctionName=()=> // document.write("FirstName: Нина "+ '<br>'); // document.write("SecondName: Александровна"+ '<br>'); // document.write("LastName: Чекалина"+'<br>'); "Occupation: преподаватель"+'<br>'+"Hobby: programming & walking"+'<br>';
document.write(myFunctionName());
</script>
// Task 2: Variables (let) and Scoping console.log(dogo) var dogo='Akita'; console.log(dogo) var dogo='Shibe' console.log(dogo) dogo='Chow CHow' console.log(dogo)
//console.log(cate) let cate='British Shorthair' console.log(cate) cate='Turkish Angora' console.log(cate)
var dogo='Akita' function printBreed(){ let dogo='Cocker Spaniel'; console.log('inside'+ dogo); }
printBreed(); console.log('outside: ' + dogo);
for(let i=0;i<2; i++){ let parrot='Hey' } //console.log(parrot); //console.log(i)
// Task 2: Execise 1: Fix the code to print 15
let age = 15;
for (let age = 1; age <= 10; age++) { console.log(age); }
console.log(age); // Should print 15 instead of 10
// Task 2: Execise 2: Fix the code to print Jack Russell Terrier
let myDog = "Jack Russell Terrier"; let shortLeggies = true;
if (shortLeggies) { let myDog = "Welsh Corgie"; console.log(myDog); } else { let myDog = "Border Collie"; console.log(myDog); }
console.log(myDog); // Jack Russell Terrier
Сделаем изменения
onst paintings=[ 'The Starry Night', 'The Night Cafe' ]; paintings.push('Irises') console.log(paintings) paintings[0]='Almond Blossoms' console.log(paintings)
const paintingInformation={ name: 'The Starry Night', painter: 'Van Gogh', location:{ museum:"MoMA", city:"New York City" } };
Object.freeze(paintingInformation); Object.freeze(paintingInformation.location);
paintingInformation.year=1889; paintingInformation.name="The" + paintingInformation.name; paintingInformation.location.country='USA' console.log(paintingInformation)
TASK 3: Exercise: Refactor the code to use let/const
var painter = { name: "Van Gogh", nationality: "Dutch", paintings: ["The Starry Night", "Irises", "Almond Blossoms"] }; Object.freeze(painter); Object.freeze(painter.paintings);
//painter.birthDate = "March 30, 1853"; //painter.paintings.push("Something");
console.log(painter); // Should print { name: 'Van Gogh', nationality: 'Dutch', paintings: [ 'The Starry Night', 'Irises', 'Almond Blossoms' ] }
function button1Clicked() {
var target1=document.getElementById("target-1"); if(target1 != null){ target1.innerHTML="Target 1 has been found"; }
}
function button2Clicked() {
// alert("button 2 clicked");
// your turn to try!! // find target2 and change its text to "Target 2 discovered!" var target2=document.getElementById("target-2"); if(target2 != null){ target2.innerHTML="Target 2 discovered"; }
}
// change styles
function button3Clicked() {
// alert("button 3 clicked!"); var target1=document.getElementById("target-1"); if(target1 != null){ target1.style.color="red"; } }
function button4Clicked() {
// alert("button4Clicked!");
// your turn to try!! // find target2 and change its backgroundColor to "orange" var target2=document.getElementById("target-2"); if(target2 != null){ target2.style.backgroundColor="orange"; } }
// generate new HTML tags and dynamic HTML contents by calling log( )
task3.html
<html lang="en"> <head> <meta charset="UTF-8"> <link rel="FaviconIcon" href="favicon.ico" type="image/x-icon"> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv=ÂPragma content=Âno-cacheÂ> <meta http-equiv=ÂExpires content=Â-1?> <meta http-equiv=ÂCACHE-CONTROL content=ÂNO-CACHEÂ> <!-- CSS Stylesheets --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <link rel="stylesheet" href="css/common.css">
<title>Task 3</title> </head>
<body> <img class="corner-hero" src="images/chalk_title.png" alt="Become a JavaScript Pro w/These 7 Skills" /> <h2 class="section-subheading">Task 3: Document Object Model (DOM)</h2> <p><a href="https://www.w3schools.com/js/js_htmldom.asp" target="_blank">View the HTML DOM Tree>>></a></p> <div class="results-div"> <table> <tbody id="log"> <tr><td class="highlight-cell hoverable-cell"><a href="main.html"><<< Back to Main Menu</a></td></tr> <tr> <td> <input class="button btn btn-primary" value="Change target 1" onclick="button1Clicked()"/> <input class="button btn btn-primary" value="Change target 2" onclick="button2Clicked()"/> </td> </tr> <tr> <td> <input class="button btn btn-secondary" value="Change target 1 colour" onclick="button3Clicked()"/> <input class="button btn btn-secondary" value="Change target 2 colour" onclick="button4Clicked()"/> </td> </tr> <!-- log entries will be added here as table rows --> </tbody> </table> </div>
<div class="result-div"> <p id="target-1">I am target 1!</p> <p id="target-2">I am target 2!</p> </div>
<script type = "text/javascript" src = "common.js"></script> <script type = "text/javascript" src = "task 3.js"></script>
</body> <footer> <div class="section-divider"><img src="images/infinity-line.png"></div>
<br /> <p><code class="copyright-text">Powered by </code><img class="baseline-align" src="images/siteicon.png" alt="J" /><code class="copyright-text">avaScript</code></p>
<code class="copyright-text">Crafted with ?? at <a href="https://coursera.org/" target= "_blank">Coursera</a></code>
</footer> </html>
var isTicking = false; var timerID;
function tickerClicked() {
if (isTicking) { isTicking = false; clearInterval(timerID); document.getElementById("ticker-button").value = "Start Ticker!"; log("Ticker stopped!"); } else { isTicking = true; // write the function code to log "tick ..." at each interval timerID = setInterval( { /* insert anonymous function here */ }, 1000); document.getElementById("ticker-button").value = "Stop Ticker!"; log("Ticker started!"); }
}
var isTicking = false; var timerID;
function tickerClicked() {
if (isTicking) { isTicking = false; clearInterval(timerID); document.getElementById("ticker-button").value = "Start Ticker!"; log("Ticker stopped!"); } else { isTicking = true; // write the function code to log "tick ..." at each interval timerID = setInterval( function(){console.log("tick ..."); }, 1000); document.getElementById("ticker-button").value = "Stop Ticker!"; log("Ticker started!"); }
}
c 1 урока
var ultimateAnswer = 42;
function hitchhike(galaxy) {
// movie scenes
var supercomputer = "Deep Thought"; console.log(supercomputer);
return true; }

Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
Free to watch • No registration required • HD streaming
Mutating methods
<script> const numbers=[1,2,3,4,5]; numbers.reverse(); console.log(numbers);
const meals=["Falafel","Hummus","Pita bread"]; meals.push("Olives"); console.log(meals); const last=meals.pop(); console.log(meals,last); meals.pop();meals.pop(); meals.pop(); console.log(meals);
const pets=["Tom","Jerry","Spike"]; pets.unshift("Stanimira"); console.log(pets); const first=pets.shift(); console.log(pets); console.log(first);
const letters=['a','b','c','d','e']; letters.splice(0,2,"first","second","third"); console.log(letters)
const animals=["ant","bison","camel","duck","elephant"]; console.log(animals.slice(2,4)); </script>
Метод Array.map()
<script> const users=[ { firstName:"Randle", lastName:"McMurphy" }, { firstName:"Chief", lastName:"Bromden" }, { firstName:"Billy", lastName:"Bibbit" } ]; const firstNames=users.map(user => user.firstName) //console.log(firstNames); const numbers=[2,4,9,16,25]; //console.log(numbers.map(num => Math.sqrt(num))); const meals=["Falafel","Hummus","Pita bread","Tiki"]; /*const meals2=meals.map((meal,index,array) => { console.log(array); return `${index}.${meal}`; }); console.log(meals2); */ const artists=[ { name:"Sharon Van Etten", age:39 }, { name:"Florence Welch", age:34 }, { name:"Hozier", age:30 } ];
const domifiedArtists=artists.map(artist => `<h1>${artist.name}</h1><h2>${artist.age}</h2>`); console.log(domifiedArtists);
</script>
Методы работы с массивами
<script> const myPets=[ { name:"Tom", type:"cat" }, { name:"Jerry", type:"mouse" }, { name:"Spike", type:"dog" } ] const isCat=pet=>pet.type==="cat"; document.write(myPets.some(isCat)); document.write(myPets.every(isCat)); const numbers=[2,4,6,8,10]; const isPrime = num =>num % 2===0; //console.log(numbers.some(isPrime)); //console.log(numbers.every(isPrime));
const isOdd = num =>num % 2!==0; //console.log(numbers.some(isOdd)); //console.log(numbers.every(isOdd)); const meals=["Falafel","Hummus","Pita bread","Falafel"] //console.log(meals.indexOf("Falafel",1));
console.log(meals.lastIndexOf("Falafel",1));
</script>
Подписка на события
Решение:
Задание
В этом задании необходимо реализовать библиотеку, позволяющую подписываться на события и получать по ним уведомления.
В библиотеке нужно реализовать три метода:
on — подписка на событие;
off — отписка от события;
emit — оповещение всех подписчиков.
Выборка mysql
create table shtat(id integer, fio varchar(10),name varchar(10),adress varchar(30),phone varchar(20)); insert into shtat(id, fio,name,adress,phone) values(1, "Петров","Николай",'ул. Космонавтов,52,кв. 11','89272345679'); insert into shtat(id, fio,name,adress,phone) values(2, "Павлов","Василий",'ул. 1Мая,24,кв. 6','89272545775'); insert into shtat(id, fio,name,adress,phone) values(3, "Степовая","Светлана",'ул. Боевая,22,кв. 10','89275346375'); insert into shtat(id, fio,name,adress,phone) values(4, "Петрова","Анна",'ул. Боевая,101,кв. 2','89271325629'); insert into shtat(id, fio,name,adress,phone) values(5, "Бережко","Валерий",'ул. Чехова,10,кв. 34','89272443665'); insert into shtat(id, fio,name,adress,phone) values(6, "Петрова","Вера",'ул. Космонавтов,19,кв. 3','89272345645'); insert into shtat(id, fio,name,adress,phone) values(7, "Ломакин","Алексей",'ул. Смола,29,кв. 15','89272342279'); select * from shtat; select name as Имя, fio as Фамилия from shtat where name like 'В%' and phone like '%5';
select * from shtat order by fio,name,adress,phone;
№2
create table hobbies(id integer, fio varchar(10),data_birth date,adress varchar(30),place_job varchar(40),job varchar(20), hobby varchar(20)); insert into hobbies(id, fio,data_birth,adress,place_job,job,hobby) values(1, "Сальников",'1990-02-11','ул.Вавилова,44,кв.5','Отдел проектирования и разработки','менеджер','силовые тренировки'); insert into hobbies(id, fio,data_birth,adress,place_job,job,hobby) values(2, "Павлова",'2000-05-18','ул.Фиолетова,34,кв.55','Отдел IT-поддержки','коуч','танцы'); insert into hobbies(id, fio,data_birth,adress,place_job,job,hobby) values(3, "Боева",'2001-12-10','ул.Лесная,41,кв.22','Отдел проектирования и разработки','менеджер','велогонки'); insert into hobbies(id, fio,data_birth,adress,place_job,job,hobby) values(4, "Савоева",'1995-07-13','ул.Дж.Рида,25,кв.115','Отдел разработки','системный аналитик','робототехника'); insert into hobbies(id, fio,data_birth,adress,place_job,job,hobby) values(5, "Уткин",'1991-12-01','ул.Римская,56,кв.67','Отдел разработки','системный аналитик','волонтерство'); insert into hobbies(id, fio,data_birth,adress,place_job,job,hobby) values(6, "Зорина",'2002-10-21','ул.1 Мая,23,кв.59','Отдел разработки','дизайнер','волонтерство'); insert into hobbies(id, fio,data_birth,adress,place_job,job,hobby) values(7, "Алушкин",'2004-05-09','ул.Сотникова,177,кв.2','Отдел внедрения','тестировщик','силовые тренировки');
select * from hobbies;
select place_job,job from hobbies group by place_job,job HAVING count(place_job) > 1 && count(job)>1;
select hobby,count(fio) as Общее_количество from hobbies group by hobby HAVING count(*) > 1;
select id,fio as Фамилия, job as Должность from hobbies where year(data_birth)<=2001 && year(data_birth)>=1989;
№3

Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
Free to watch • No registration required • HD streaming
Collection
<script> let collection = [ {
name: 'Сэм',
gender: 'Мужской',
email: '[email protected]',
favoriteFruit: 'Картофель'
},
{
name: 'Эмили',
gender: 'Женский',
email: '[email protected]',
favoriteFruit: 'Яблоко'
} ];
function cloneItem(item, properties) { var newItem = {}; // Копируем каждый ключ элемента в новый элемент for (var i = 0; i < properties.length; i++) { var property = properties[i];
// Присваивание происходит по значению // так как по условию тип поля строка либо число // Проверяем, что свойство существует у исходного элемента if (item.hasOwnProperty(property)) { newItem[property] = item[property]; } } // return console.log(newItem); return newItem; }
function select() {
// Получаем список свойств, которые будем выбирать var properties = str.slice.call(arguments); // Возвращаем функцию, которая позже будет применена к коллекции. function operationSelect(collection) { return collection.map(function (item) {
// Клонируем объект с переданными свойствами return console.log(cloneItem(item, properties)); }); }; } function filterIn(property, values) { // Возвращаем функцию, которая позже будет применена к коллекции. return function operationFilter(collection) { // Фильтруем коллекцию по значению поля return collection.filter(function (item) { var value = item[property];
return values.indexOf(value) > -1; }); }; }
function cloneCollection(collection) { var collections=collection.map(function (item) { var properties = Object.keys(item);
// Клонируем элемент со всеми его свойствами return cloneItem(item, properties);
// return item;
}); // console.log(collections); } cloneCollection(collection); let str=['name','gender','email']; select(str); filterIn('favoriteFruit', ['Яблоко', 'Картофель']);
</script>
Задача из курса
Код:
<script>
var dates = new Date(2016, 8, 16, 15, 0); let s = function (date){
return { first: function (minut,s) {
date.setMinutes(date.getMinutes() + minut); document.write(date); return this; }, second: function (day1,d) { date.setDate(date.getDate() + day1); document.write(date); return this; }, third: function (hour1,m) { date.setHours(date.getHours() + hour1); document.write(date); return this; }, four: function (month1,mn) { date.setMonth(date.getMonth() + month1); document.write(date); return this; } } }; s(dates).first(10,'minutes').second(7,'days').third(1,'hourses').four(2,'monthes'); </script>