// 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}>`    
}
