123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150 |
- // Task sort
- const persons = [
- {name: "Иван", age: 17},
- {name: "Мария", age: 35},
- {name: "Алексей", age: 73},
- {name: "Яков", age: 2},
- ]
- function sort(obj, param, direction){
- return {...obj.sort(byField(param, direction))}
- }
- function byField(param, direction) {
- if (direction === undefined){
- return ((a, b) => a[param] > b[param] ? 1 : -1);
- }
- return direction ? ((a, b) => a[param] > b[param] ? 1 : -1) : (a, b) => a[param] < b[param] ? 1 : -1;
- }
- console.log(sort(persons, "age"));
- console.log(sort(persons, "name", false));
- console.log(sort(persons, "name", true));
- // Task array map
- const arr = ["1", {}, null, undefined, "500", 700];
- function doNumber(array){
- return array.map((elem) => Number(elem) ? Number(elem) : elem);
- }
- console.log(doNumber(arr))
- // Task array reduce
- const arr2 = ["0", 5, 3, "string", null];
- function multiply(arr){
- return arr.reduce((prevElem ,elem )=>{
- return typeof elem === "number" ? prevElem * elem : prevElem;
- }, 1)
- }
- console.log(multiply(arr2));
- // Task object filter
- const phone = {
- brand: "meizu",
- model: "m2",
- ram: 2,
- color: "black",
- };
- function filter(obj, callBack){
- const newObj = {};
- for(let key in obj){
- if(callBack(key, obj[key])){
- newObj[key] = obj[key];
- }
- }
- return newObj;
- }
- console.log(filter(phone,(key,value) => key == "color" || value == 2))
- // Task object map
- const man = {
- name : "Ivan",
- age : "17",
- }
- function map(obj, callBack){
- let res = {};
- for (let key in obj){
- res = {...res, ...callBack(key,obj[key])}
- }
- return res
- }
- console.log(map({name: "Иван", age: 17},function(key,value){
- var result = {};
- result[key+"_"] = value + "$";
- return result;
- }))
- // Task Рекурсия Sum
- function sum(n){
- if (n === 0){
- return 0
- }else{
- return n + sum(n-1);
- }
- }
- console.log(sum(10));
- // Task HTML tree
- const someTree = {
- tagName: "table",
- subTags: [
- {
- tagName: "tr",
- subTags: [
- {
- tagName: "td",
- text: "some text",
- },
- {
- tagName: "td",
- text: "some text 2",
- },
- ]
- },
- ],
- attrs:
- {
- border: 1,
- },
- };
- let domStructure = '';
- fillHtml(someTree);
- document.write(domStructure)
- function fillHtml(objTree) {
- domStructure += `<${objTree.tagName} ${(objTree.attrs) ? Object.keys(objTree.attrs)[0] + "=" + Object.values(objTree.attrs)[0] : ""}>`;
- domStructure += `${objTree.text ? objTree.text : ""}`;
- if(objTree.subTags && (objTree.subTags.length >0)){
- for (let i = 0; i < objTree.subTags.length; i++) {
- fillHtml(objTree.subTags[i]);
- }
- }
- domStructure += `</${objTree.tagName}>`
- }
|